如何在 Python 中退一步?



我为我缺乏知识而道歉。我刚刚开始学习python,我使用youtube视频创建了一个基本的计算器。它是这样的:

user_continue = True
while user_continue:
validInput = False
while not validInput:
# Get user input
try:
num1 = int(input("What is number 1?"))
num2 = int(input("What is number 2?"))
operation = int(input("What do you want to do with these? 1. add, 2. subtract, 3. multiply 4. divide. Enter number:"))
validInput = True
except:
print("Invalid Input. Please try again.")
if(operation == 1):
print("Adding...")
print(add(num1, num2))
elif(operation == 2):
print("Subtracting...")
print(sub(num1, num2))
elif(operation == 3):
print("Multiplying...")
print(mul(num1, num2))
elif(operation == 4):
print("Dividing...")
print(div(num1, num2))
else:
print("I don't understand. Please try again.")
user_yn = input('Would you like to do another calculation? ("y" for yes or any other value to exit.)')
if(user_yn == 'y'):
continue
else:
break

我想做的是,如果用户输入的数字不是 1、2、3 或 4,我希望程序要求另一个"操作"输入。

我再次为任何错误道歉,我才刚刚开始。

这是一个非常简单的修改。在您的代码中:

operation = int(input("What do you want to do with these? 1. add, 2. subtract, 3. multiply 4. divide. Enter number:"))
validInput = True

您应该简单地检查输入是否有效,然后再将validInput标记为True。要继续使用您的try-except块,您可以使用如下断言进行检查:

operation = ...
assert operation in (1,2,3,4)
validInput = True

如果operation不在(1,2,3,4)则代码将抛出一个AssertionError,您的try-except块将捕获该。

在不相关的说明中,您可能不应该像您在此处所做的那样使用捕获所有错误的except子句。事实上,此块也会捕获KeyboardInterrupt错误,这意味着您将无法退出程序!最好使用except ValueErrorexcept AssertionError

使用现有代码,只需进行简单的更改:

while not validInput:
# Get user input
try:
num1 = int(input("What is number 1?"))
num2 = int(input("What is number 2?"))
operation = int(input("What do you want to do with these? 1. add, 2. subtract, 3. multiply 4. divide. Enter number:"))
if 1 <= operation <=4:
validInput = True
else:
print("Invalid Input. Please try again.")
except:
print("Invalid Input. Please try again.")

函数是你的朋友。 这个只会返回 1-4,在内部循环,直到输入正确。break退出无限while循环。 如果未输入整数,则会抛出一个ValueError,并且except子句将忽略它。 任何无效的内容都将打印"无效输入"并继续循环。

def get_operation():
while True:
try:
op = int(input('Enter 1-add, 2-subtract, 3-muliply, 4-divide: '))
if 1 <= op <= 4:
break
except ValueError:
pass
print('Invalid input')
return op
operation = get_operation()

最新更新