我正在使用Python创建一个非常基本的计算器。不管出于什么原因,这些数字只会相加——它们不会做任何其他功能。请帮助!
equation_type = input("What kind of math do you want to do? ")
equation_type = equation_type.lower()
first_number = float(input("What is the first number? "))
second_number = float(input("What is the 2nd number? "))
if equation_type == "add" or "addition":
result = first_number + second_number
elif equation_type == "subtract" or "subtraction":
result = (first_number - second_number)
elif equation_type == "multiply" or "multiplication":
result = first_number * second_number
elif equation_type == "divide" or "division":
result = first_number / second_number
else:
print("not a valid entry :/")
print(result)
equation_type == "add" or "addition"
并不像你想象的那样。
很容易把Python代码当成英语来读。不是的!Python仍然是一种编程语言,编程语言有严格的规则。
表达式equation_type == "add" or "addition"
被解析为(equation_type == "add") or "addition"
。第一部分(equation_type == "add")
可能是真或假,这取决于用户的输入。然而,第二部分"addition"
总是正确的从if
的角度来看。
因此,Python总是使用if
/elif
/else
链中的第一个分支,而忽略其他分支,因为第一个分支总是"true"从它的角度看!
or
操作符只有一个目的:使用逻辑析取来组合表达式。它不会重复地对多个值应用相等性检查!有关or
和and
等操作符能做什么和不能做什么的详细信息,请参阅官方文档。
你可能想写if equation_type in ("add", "addition"):
。in
操作符检查值是否为某个集合的元素:
x = "apple"
if x in ("carrot", "celery"):
print("vegetable")
elif x in ("apple", "pear"):
print("fruit")
in
操作符适用于所有类型的集合:元组(a, b, c)
,列表[a, b, c]
,字典{a: 1, b: 2}
的键(不是值!)。
条件应该是这样的(许多方法之一):
equation_type == "add" or equation_type == "addition":
当检查多个条件时,需要重复相等。还有其他方法,但既然你是初学者,你应该试着让这个方法起作用。
对其他条件做同样的操作,看看是否有效。