如果输入无效,请重新输入

时间:2019-05-29 14:10:45

标签: python

我想这样编程,因此在输入num1,num2和操作时,如果用户未以适当的类型提供输入,则会再次询问用户输入。

operation=(input('1.add\n2.subtract\n3.multiply\n4.divide'))
num1 =int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

if operation == "add" or operation == '1' :
   print(num1,"+",num2,"=", (num1+num2))
elif operation =="subtract" or operation == '2':
   print(num1,"-",num2,"=", (num1-num2))
elif operation =="multiply" or operation == '3':
   print(num1,"*",num2,"=", (num1*num2))
elif operation =="divide" or operation == '4':
   print(num1,"/",num2,"=", (num1/num2))

1 个答案:

答案 0 :(得分:0)

您正在寻找一个while循环:

num1 = None
while num1 is None:
    try:
        num1 = int(input('Enter a number: '))
    except ValueError:
        print('Invalid, input must be an integer!')
    else:
       # Examples of further tests you could add.
       # code here in the try-else block is only executed if the "try-part" was successful
       if num1 < 0:
           print('Number might not be negative')
           num1 = None
       elif:
           ...



注意:请先考虑在论坛上搜索类似的问题,然后再发布自己的问题,否则人们可能会投票否决您并将其标记为重复。

相关问题