You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中or逻辑判断语句未按预期工作的问题求助

问题:麦当劳自助点餐系统中or逻辑判断失效

原代码

import time

repeat=0
price=0
print("Welcome to McDonald's self order system")
time.sleep(0.5)
name_person=str(input("\nPlease enter your name to continue: "))
while True:
    order=int(input("\n---Menu---\n 1.Burger\n 2.McPuff\n 3.Ice Cream\n 4.Cold Drink\n\nPlease order by typing the number: "))
    if order in range(1,4) :
        repeat=str(input("Do you want to order more? Yes/No: "))
        if repeat == "No" or "no":
            print("Ok")
            break
    else :
        print("\n!!Invalid input!!")
        time.sleep(0.5)

问题现象

输入“No”时程序正常退出,但输入“Yes”或其他任意内容时,也会触发“Ok”并退出循环;移除or "no"后功能恢复正常。


修复方案

问题出在or的逻辑写法上,以下两种写法都能解决问题:

写法1:完整的逻辑判断

import time

repeat=0
price=0
print("Welcome to McDonald's self order system")
time.sleep(0.5)
name_person=str(input("\nPlease enter your name to continue: "))
while True:
    order=int(input("\n---Menu---\n 1.Burger\n 2.McPuff\n 3.Ice Cream\n 4.Cold Drink\n\nPlease order by typing the number: "))
    if order in range(1,4) :
        repeat=str(input("Do you want to order more? Yes/No: "))
        # 修正or的逻辑:分别判断repeat等于"No"或"no"
        if repeat == "No" or repeat == "no":
            print("Ok")
            break
    else :
        print("\n!!Invalid input!!")
        time.sleep(0.5)

写法2:用in判断(更简洁)

import time

repeat=0
price=0
print("Welcome to McDonald's self order system")
time.sleep(0.5)
name_person=str(input("\nPlease enter your name to continue: "))
while True:
    order=int(input("\n---Menu---\n 1.Burger\n 2.McPuff\n 3.Ice Cream\n 4.Cold Drink\n\nPlease order by typing the number: "))
    if order in range(1,4) :
        repeat=str(input("Do you want to order more? Yes/No: "))
        # 检查输入是否在指定的集合中
        if repeat in {"No", "no"}:
            print("Ok")
            break
    else :
        print("\n!!Invalid input!!")
        time.sleep(0.5)

错误原因

原代码中的repeat == "No" or "no"在Python中会被解析为(repeat == "No") or "no"。由于非空字符串在布尔判断中会被视为True,所以不管repeat的值是什么,整个条件表达式的结果都是True,导致程序直接退出循环。


内容的提问来源于stack exchange,提问作者CreeperOnCoding

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 16:57:21