Python中的非空字符串是truthy。这意味着在if语句中使用时,它们的求值结果始终为
我对一般编码非常陌生,最近才开始学习python。我正在试着做一个简单的计算器。然而,我遇到了一个问题,而如果用户输入的数学运算无效,我希望它终止程序。然而,在我的情况下,它只是继续程序。
这是我的代码的一部分
if use_calculator.lower() == "yes":
print("That's great to hear, " + name + " please proceed")
operation = input("What mathematical operation would you like to execute? ")
num1 = float(input("Please input a number: "))
num2 = float(input("Please input another number: "))
if operation.lower() == "+" or "addition":
print(num1 + num2)
elif operation.lower() == "-" or "subtraction":
print(num1 - num2)
elif operation.lower() == "division" or "/":
print(num1 / num2)
elif operation.lower() == "multiplication" or "*" or "x":
print(num1 * num2)
else:
exit()
else:
print("That is very sad to hear, " + name)
True
。这可以在if块的or
之后看到。相反,您应该检查operation.lower()
是否包含在每个if语句的集合中,例如
if operation.lower() in ("+", "addition"):
....