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

uqzxnwby  于 2021-07-13  发布在  Java
关注(0)|答案(2)|浏览(324)
def start():
    print("select any one of the operators: ")
    print("SI")
    print("BMI")
    print("AP")
    print('QE')
    s = 'SI'
    b = 'BMI'
    a = 'AP'
    q = 'QE'
    x = input('type the required operation: ')

try:
 intro = "select any one of the operators: "
 print(red + intro.upper())
 print('__________________________')
 print("SI(simple interest)")
 print("BMI(body mass index)")
 print("AP(arithmetic progression)")
 print("QE(quadratic equations)")
 print('__________________________')
 s =  'SI'
 b = 'BMI'
 a = 'AP'
 q = 'QE'
 yellow = '\033[33m'
 x = input(yellow + 'Type the required operation: ')
 if x.upper() == s:
     si()
 if x.upper() == b:
    bmi()
 if x.upper() == a:
    ap()
 if x.upper() == q:
    qe()
except :
    print('spelling error, please try again')
    start()

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

list = ['SI', 'BMI', 'AP', 'QE']
while x != list:
    print('spelling error')
    start()
    if x == list:
        break

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

fumotvh3

fumotvh31#

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

x = ''
while True:
    print("select any one of the operators: ")
    print('__________________________')
    print("SI(simple interest)")
    print("BMI(body mass index)")
    print("AP(arithmetic progression)")
    print("QE(quadratic equations)")
    print('__________________________')
    x = input('type the required operation: ').upper()
    if x == "SI":
        si()
    elif x == "BMI":
        bmi()
    elif x == "AP":
        ap()
    elif x == "QE":
        qe()
    else:
        print("spelling error")
        continue
    break
cqoc49vn

cqoc49vn2#

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

print ( 'type the required operation: ', end='')
while True: 
   inp = input()
   if not inp in ['AP','BMI','SE','QE']:
       print ("spelling error")
   else:
       break;

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

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

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

age = input('Your age ?')
try:
    age_int = int(age)
except:
    # error in converting string to int
    pass
else:
    # string was converted to an int without errors
    print (f'You claim to be {age_int} years')

相关问题