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

Python 3中elif语句失效求助:输入需重复两次触发

人生模拟程序elif语句多次输入问题修复方案

问题原因

你代码里第10-15行的if和elif分别调用了一次input(),每次调用都会让程序等待用户输入一次。这就导致:

  • 如果第一次输入不是"cry",程序会走到elif分支再次要求输入,必须再输入一次才能判断是否符合"stay quite"
  • 你感知到的"需要输入两次'cry'才能触发",大概率是误操作(比如第一次输入错误内容,第二次输入"cry"才触发),本质是多次调用input()导致的交互逻辑混乱

修复方法

把用户的输入先存储到一个变量中,只调用一次input(),再用这个变量做所有条件判断。这样程序只会要求用户输入一次,逻辑更清晰。

修改后的代码片段(第10-15行)

print("You Are Born On Monday The Fourth Of March Would You Like To start To cry or stay quite")
# 存储输入到变量,strip()去除前后空格,避免输入空格导致判断失效
choice = input().strip()
if choice == "cry":
    print("You Cry For The Rest Of Your Life And Die Of Depression At The Age Of 12 YOU DIED RE-RUN THE PROGRAM")
    exit()
elif choice == "stay quite":
    p("----------------------")
    print("You Stay Quiet And Your Mother Is Very Confeused Mother: Why Are You So Quiet?. You Fell Asleep And Woke Up The Next Day At 2:34 AM")
else:
    # 新增默认分支处理无效输入
    print("Invalid choice! Please enter 'cry' or 'stay quite'.")

额外建议

你程序中其他交互判断(比如"dance"、"go away"部分)也存在同样的多次调用input()的隐患,建议统一改成先存变量的方式。例如后面的"dance"判断可以修改为:

print("do you want to go to sleep or dance")
print("go to sleep|dance")
sleep_dance_choice = input().strip()
if sleep_dance_choice == "dance":
    print("You dance For The Rest Of Your Life And die from exhaustion YOU DIED RE-RUN THE PROGRAM")
    exit()
elif sleep_dance_choice == "go to sleep":
    print("You Go To Sleep And the next day you Wake Up you open your eyes to people looking at you and saying aww look at that cute little baby") 
    # 后续逻辑...
else:
    print("Invalid choice! Please enter 'go to sleep' or 'dance'.")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 18:10:38