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

Python While循环无法终止问题求助

问题解决:While循环无法终止的原因及修复方案
  • 核心错误:你在循环条件中写了yn.lower != "n",这里的lower是字符串的内置方法,必须通过加括号调用(即yn.lower())才能得到转换为小写的字符串值。直接写yn.lower得到的是方法对象本身,永远不可能等于字符串"n",这就是循环无法终止的根本原因。

  • 基础修复版本(支持输入'n'/'N'终止循环):

yn = ""
while yn.lower() != "n":
    usr_choice = userChoice()
    com_choice = compChoice()
    winner(usr_choice, com_choice)
    yn = input("Would you like to continue? y/n: ")
  • 进阶优化版本(支持输入'n'/'N'/'no'/'NO'终止循环):
    如果要兼容更多终止输入,可将条件改为判断小写后的输入是否在终止列表内:
yn = ""
while yn.lower() not in ["n", "no"]:
    usr_choice = userChoice()
    com_choice = compChoice()
    winner(usr_choice, com_choice)
    yn = input("Would you like to continue? y/n (or no): ")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 01:10:57