我只是写了一个简单的if语句。仅当用户键入“Good!”时,第二行才计算为 true。 如果“太棒了!”输入后,它将执行 else 语句。我可以不使用或喜欢这个吗?我需要逻辑或吗?
weather = input("How's the weather? ")
if weather == "Good!" or "Great!":
print("Glad to hear!")
else:
print("That's too bad!")
你不能这样使用它。由于运算符优先级,您所编写的内容将被解析为
(weather == "Good") or ("Great")
左边部分可能是假的,但右边部分是true(Python有“truth-y”和“fals-y”值),所以检查总是成功的。
写下你的意思的方法是
if weather == "Good!" or weather == "Great!":
或者(更常见的Python风格)
if weather in ("Good!", "Great!"):