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

如何将新输入值传递给Python变量'playing'以实现while循环读取新值及代码逻辑咨询

问题分析与解决方案

看起来你在通过用户输入控制while循环时遇到了两个关键问题,我来帮你拆解并修正:

你的代码里的核心问题

  • while循环条件逻辑错误:你写的while playing.lower().strip() != "yes" or "no"存在逻辑漏洞。在Python中,or "no"会被当成布尔值判断,非空字符串永远为True,所以这个条件等价于(输入不等于"yes") or True,结果永远是True,循环会无限执行下去。正确的逻辑应该是判断输入既不是"yes"也不是"no"。
  • 变量赋值搞反了:你写的playing_2 = playing是把旧的playing值覆盖到playing_2,完全没把新输入的内容传递给playing,应该反过来写成playing = playing_2,甚至可以直接省略playing_2,把输入结果直接赋值给playing。

修正后的完整代码

print("Welcome to my computer game!")
print("Would you like to play my computer knowledge game ?..")
playing = input("waiting... ")

playing_clean = playing.lower().strip()
if playing_clean == "no":
    quit()
if playing_clean == "yes":
    print("Okay, lets play !..")

# 修正循环条件:判断输入既不是yes也不是no时,继续询问
while playing.lower().strip() not in ["yes", "no"]:
    # 直接把新输入赋值给playing,无需额外变量
    playing = input("Would you like to play the Squid game?!... ")
    # 新增即时判断,让流程更清晰
    current_input = playing.lower().strip()
    if current_input == "yes":
        print("Great! Let's dive into Squid Game!")
    elif current_input == "no":
        print("No problem! See you next time!")
        quit()

额外优化建议

  • 可以把重复的lower().strip()操作封装成小函数,让代码更简洁:
    def clean_input(s):
        return s.lower().strip()
    
    之后就可以用clean_input(playing)替代重复的字符串处理。
  • 初始的两个if可以合并成elif,避免多余的判断:
    playing_clean = clean_input(playing)
    if playing_clean == "no":
        quit()
    elif playing_clean == "yes":
        print("Okay, lets play !..")
    

这样修改后,新输入的值会正确传递给playing变量,while循环也能根据最新的输入值判断是否继续执行啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.01 02:14:11