我想这样编程,因此在输入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))
答案 0 :(得分:1)
您可以使用in
关键字。
例如:
>>> "1" in ["1","add"]
True
>>> "add" in ["1","add"]
True
修改代码,例如:
operation=(input('1.add\n2.subtract\n3.multiply\n4.divide'))
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if operation in ["1","add"] :
print(num1,"+",num2,"=", (num1+num2))
elif operationi in ["2", "subtract"]:
print(num1,"-",num2,"=", (num1-num2))
elif operation in ["3", "multiply"]:
print(num1,"*",num2,"=", (num1*num2))
elif operation in ["4", "divide"]:
print(num1,"/",num2,"=", (num1/num2))
else:
print("Invalid Input")
答案 1 :(得分:1)
尝试一下
operation=(input('1.add\n2.subtract\n3.multiply\n4.divide'))
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if operation == "1" or operation == "add" :
print(num1,"+",num2,"=", (num1+num2))
elif operation == "2" or operation == "subtract":
print(num1,"-",num2,"=", (num1-num2))
elif operation == "3" or operation == "multiply":
print(num1,"*",num2,"=", (num1*num2))
elif operation == "4" or operation == "divide":
print(num1,"/",num2,"=", (num1/num2))
else:
print("Invalid Input")
说明:
在您的代码中, IF 将检查条件1或条件2为真还是假
if operation == "1" or operation == "add"
在这里
条件1: operation == "1"
条件2: operation == "add"
if operation == "1" or operation == "add"
在这里
condition-1: operation == "1"
条件2: "add" # Always True as string contains elements.
答案 2 :(得分:0)
此代码有效,因为在Python中,值是真实的和虚假的。但是,多条件if子句的语法错误。应该是if a == something and b == anotherthing
。
因此它将如下。
if operation == "1" or operation == "add" :
print(num1,"+",num2,"=", (num1+num2))