Python中如何退出循环?学生开发文字冒险游戏遇while循环无法退出问题
问题原因
- 你编写的while循环条件存在逻辑错误:Python中单独的非空字符串会被判定为布尔值
True,你写的playerchoice != "wake" or "remain asleep"等价于(playerchoice != "wake") or True,因此无论用户输入任何内容,整个循环条件永远成立,程序会进入死循环无法正常退出。 - 原逻辑中你想表达的是「当用户输入既不是wake也不是remain asleep时继续循环」,对应逻辑运算符应该用
and而不是or。
修正方案
两种实现方式可选,第二种可读性更高:
- 修正逻辑运算符和判断条件
playerchoice = "" # 两个不等判断用and连接 while playerchoice != "wake" and playerchoice != "remain asleep": playerchoice = input("Do you wake, or remain asleep? wake/remain asleep: ") if playerchoice == "wake": print ("'Finally! I was starting to think I'd need to call the undertaker. Try not falling asleep in my front yard next time you're feeling tired?'") elif playerchoice == "remain asleep": print ("'Are you dead?' they ask again, kicking you in the leg this time. Reluctantly, you sit up. 'Oh, good.'") else: print ("Please type a valid answer.")
- 使用
not in简化判断
playerchoice = "" # 直接判断输入是否不在合法选项集合中 while playerchoice not in ("wake", "remain asleep"): playerchoice = input("Do you wake, or remain asleep? wake/remain asleep: ") if playerchoice == "wake": print ("'Finally! I was starting to think I'd need to call the undertaker. Try not falling asleep in my front yard next time you're feeling tired?'") elif playerchoice == "remain asleep": print ("'Are you dead?' they ask again, kicking you in the leg this time. Reluctantly, you sit up. 'Oh, good.'") else: print ("Please type a valid answer.")
内容的提问来源于stack exchange,提问作者lewsie
相关产品推荐
相关产品推荐

