无法使用while循环或尝试查找python中的拼写错误

uqzxnwby  于 2021-07-13  发布在  Java
关注(0)|答案(2)|浏览(469)
  1. def start():
  2. print("select any one of the operators: ")
  3. print("SI")
  4. print("BMI")
  5. print("AP")
  6. print('QE')
  7. s = 'SI'
  8. b = 'BMI'
  9. a = 'AP'
  10. q = 'QE'
  11. x = input('type the required operation: ')
  12. try:
  13. intro = "select any one of the operators: "
  14. print(red + intro.upper())
  15. print('__________________________')
  16. print("SI(simple interest)")
  17. print("BMI(body mass index)")
  18. print("AP(arithmetic progression)")
  19. print("QE(quadratic equations)")
  20. print('__________________________')
  21. s = 'SI'
  22. b = 'BMI'
  23. a = 'AP'
  24. q = 'QE'
  25. yellow = '\033[33m'
  26. x = input(yellow + 'Type the required operation: ')
  27. if x.upper() == s:
  28. si()
  29. if x.upper() == b:
  30. bmi()
  31. if x.upper() == a:
  32. ap()
  33. if x.upper() == q:
  34. qe()
  35. except :
  36. print('spelling error, please try again')
  37. start()

我试图创建一个程序,其中列出了四个操作(简单兴趣,ap,二次方程,bmi),并要求用户输入。如果输入与任何操作都不匹配,则需要打印拼写错误并让用户再次尝试输入。但是如果我输入了操作以外的任何东西,程序就会结束而不打印任何东西。我也尝试过使用while循环,但也失败了

  1. list = ['SI', 'BMI', 'AP', 'QE']
  2. while x != list:
  3. print('spelling error')
  4. start()
  5. if x == list:
  6. break

请帮助我找到打印拼写错误的方法,并允许用户重试

fumotvh3

fumotvh31#

首先, list 是python中的保留关键字,因此不能将其用作变量名。其次,如果要查看字符串是否在列表中,则必须使用 in 关键字,不是 == . 你的 start 函数应返回 x ,否则while循环将无法识别 x 你指的是。
下面是一个使用while循环进行拼写检查的示例:

  1. x = ''
  2. while True:
  3. print("select any one of the operators: ")
  4. print('__________________________')
  5. print("SI(simple interest)")
  6. print("BMI(body mass index)")
  7. print("AP(arithmetic progression)")
  8. print("QE(quadratic equations)")
  9. print('__________________________')
  10. x = input('type the required operation: ').upper()
  11. if x == "SI":
  12. si()
  13. elif x == "BMI":
  14. bmi()
  15. elif x == "AP":
  16. ap()
  17. elif x == "QE":
  18. qe()
  19. else:
  20. print("spelling error")
  21. continue
  22. break
展开查看全部
cqoc49vn

cqoc49vn2#

我会用这样的方法来验证输入:

  1. print ( 'type the required operation: ', end='')
  2. while True:
  3. inp = input()
  4. if not inp in ['AP','BMI','SE','QE']:
  5. print ("spelling error")
  6. else:
  7. break;

然后创建and if、elif、else语句来选择一个操作如果您希望允许您的条目也以小写形式输入,请使用例如:

  1. if not inp.upper() in ['AP','BMI','SE','QE']:

另外,尽量与空格保持一致。如果您已经为第一个缩进添加了4,那么尝试将4也用于try except块。
try子句下的语句也应尽可能少;只添加您真正想要测试的语句,否则所有其他错误也会被捕获,从而使调试更加困难。

  1. age = input('Your age ?')
  2. try:
  3. age_int = int(age)
  4. except:
  5. # error in converting string to int
  6. pass
  7. else:
  8. # string was converted to an int without errors
  9. print (f'You claim to be {age_int} years')
展开查看全部

相关问题