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

如何让while循环适配quit的所有大小写输入以正常终止?

问题:披萨配料程序无法识别大小写格式的"quit"终止命令

编写了一个用while循环询问披萨配料的程序,仅当输入小写"quit"时能终止循环,但输入"Quit"、"QUIT"等任意大小写组合时无法正常终止。原代码如下:

order = "\nWhat topping do you want? "
response = "\nWe will add that topping to your pizza. Enter 'quit' to finish ordering toppings. "
topping = ""

while topping != "quit":
    topping = input(order)
    if topping != "quit":
        print(response)

解决方案

核心思路是将用户输入的文本统一转换为小写(或大写)后再与目标字符串比较,忽略输入的大小写差异。

修改后的代码

order = "\nWhat topping do you want? "
response = "\nWe will add that topping to your pizza. Enter 'quit' to finish ordering toppings. "
topping = ""

# 将输入转换为小写后判断终止条件
while topping.lower() != "quit":
    topping = input(order)
    # 同样转换为小写判断,避免错误输出提示信息
    if topping.lower() != "quit":
        print(response)

说明

  • 调用字符串方法lower(),把用户输入的topping转为全小写格式,这样无论输入"Quit"、"QUIT"还是其他大小写组合,都会被统一处理为"quit",从而正确触发循环终止逻辑。
  • 两处判断都使用lower(),避免出现用户输入非小写"quit"时,先输出提示信息再终止循环的逻辑漏洞。

也可以使用upper()方法实现相同效果,只需将目标字符串改为"QUIT":

order = "\nWhat topping do you want? "
response = "\nWe will add that topping to your pizza. Enter 'quit' to finish ordering toppings. "
topping = ""

while topping.upper() != "QUIT":
    topping = input(order)
    if topping.upper() != "QUIT":
        print(response)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 12:02:45