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

Python嵌套if/else语句问题:如何正确触发else分支?

修正Python餐桌安排程序的嵌套逻辑错误

原代码的核心问题

  1. 未保存用户的确认输入:原代码里print(input("..."))只是打印了用户输入的内容,但没有将这个值存储到变量中,导致后续的if/else判断完全没用到用户的实际回答。
  2. 条件判断逻辑失效:if 'yes':这个条件永远为真——在Python中,非空字符串会被视为布尔值True,所以不管用户输入什么,都会执行yes对应的分支,else分支永远不会触发。

修正方案

要实现“输入包含yes就执行等待提示,包含no就执行告别提示”的逻辑,需要做以下修改:

  • 先将用户的确认输入保存到变量中,同时统一转为小写并去除前后空格,避免大小写和空格干扰判断
  • 使用in关键字检查输入内容中是否包含目标字符串
  • 增加对无效输入的处理逻辑(可选但更友好)

修正后的完整代码

# Write a program that asks the user how many people
# are in their dinner group. If the answer is more than eight, print a message saying
# they’ll have to wait for a table. Otherwise, report that their table is ready.

people = input("How many people will you be having in your dinner group? ")
people = int(people)

if people > 8:
    # 保存用户回答并统一格式,消除大小写和空格干扰
    wait_response = input("We'll have to put you on a short wait, is that okay? ").strip().lower()
    if 'yes' in wait_response:
        print("Okay, we will call your table in the next 15 minutes.")
    elif 'no' in wait_response:
        print("Okay, we will see you another night, then. Thank you for stopping by.")
    else:
        # 处理既不含yes也不含no的无效输入
        print("Sorry, I didn't catch that. Please respond with 'yes' or 'no'.")
else:
    print("Perfect! Right this way; follow me.")

关键修改说明

  • wait_response = input(...).strip().lower():strip()去除输入前后的空格,lower()将所有字符转为小写,确保Yes、YES、yes这类输入都能被正确识别
  • 'yes' in wait_response:通过子串匹配实现“无论位置包含yes即触发”的需求
  • 新增elif和默认else分支,覆盖了所有可能的输入场景,避免程序逻辑遗漏

内容的提问来源于stack exchange,提问作者Mark W.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 01:30:21