所以我是新编码(从python开始),我正在尝试制作一个超级简单/基本的计算器。我之前在另一组代码中遇到了这个问题,我无法弄清楚原因。即使它是假的,代码行也会返回true。所以说我做了100除以5,它返回为" *"和"乘以"给出500的结果,而不是正确的答案应该是20.如果有人可以解释/说明为什么它返回真实而不是假?
def calculator():
Number_input_one = int(raw_input("Enter your first number: "))
Math_symbol = raw_input("What do you want to do? ")
Number_input_two = int(raw_input("Enter your second number: "))
if Math_symbol == "*" or "Multiply":
print Number_input_one * Number_input_two
elif Math_symbol == "/" or "Divide":
print Number_input_one / Number_input_two
elif Math_symbol == "+" or "Add":
print Number_input_one + Number_input_two
elif Math_symbol == "-" or "subtract":
print Number_input_one - Number_input_two
else:
print "it doesn't match anything!"
答案 0 :(得分:4)
你犯了一个经典错误:
if Math_symbol == "*" or "Multiply":
没有做你认为的事情。正确的版本是:
if Math_symbol in ("*", "Multiply"):
您的代码版本正在检查if Math_symbol == "*"
或"Multiply"
是否存在(即它不是空字符串)。这将始终评估为True
,因为字符串"Multiply"
确实存在。
其他if
语句需要进行类似的更正:
if Math_symbol in ("*", "Multiply"):
print Number_input_one * Number_input_two
elif Math_symbol in ("/", "Divide"):
print Number_input_one / Number_input_two
elif Math_symbol in ("+", "Add"):
print Number_input_one + Number_input_two
elif Math_symbol in ("-", "subtract"):
print Number_input_one - Number_input_two
else:
print "it doesn't match anything!"
答案 1 :(得分:1)
你也可以试试这个:
if (Math_symbol == "*") or (Math_symbol=="Multiply"):
elif (Math_symbol == "/") or (Math_symbol == "Divide"):
等等!
答案 2 :(得分:0)
您想要math_symbol == "-" or math_symbol == "subtract"
语句“string”始终评估true