在 if 语句中使用或 (Python)

Jus*_*kid 0 python conditional if-statement

我只是在写一个简单的 if 语句。只有当用户输入“Good!”时,第二行才会评估为真。如果“太好了!” 输入它会执行else语句。我可以不使用或喜欢这个吗?我需要逻辑还是?

    weather = input("How's the weather? ")
if weather == "Good!" or "Great!": 
    print("Glad to hear!")
else: 
    print("That's too bad!")
Run Code Online (Sandbox Code Playgroud)

blu*_*ote 6

你不能那样使用它。该or运营商必须有两个布尔操作数。你有一个布尔值和一个字符串。你可以写

weather == "Good!" or weather == "Great!": 
Run Code Online (Sandbox Code Playgroud)

或者

weather in ("Good!", "Great!"): 
Run Code Online (Sandbox Code Playgroud)

你写的内容被解析为

(weather == "Good") or ("Great")
Run Code Online (Sandbox Code Playgroud)

在 python 的情况下,非空字符串总是计算为True,所以这个条件将始终为真。