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

如何修复Python中输入‘Stop’无法终止的while循环代码

Fixing Your Python Fruit Loop Termination Issue

Hey there! Let's break down why your loop keeps running indefinitely instead of stopping when you type "Stop":

The Root Problem

Your code only asks for user input once, right before the loop starts. After that, the user_input variable never gets updated inside the loop—so it keeps using the original value forever. Also, that if user_input == "Stop" check inside the loop is totally redundant: since your loop condition is user_input != "Stop", that branch will never run anyway.

The Easy Fix

All you need to do is re-prompt the user for input at the end of each loop iteration (or start of it, whichever you prefer). This updates the user_input variable so the loop can check if you typed "Stop" next time around. Here's the adjusted code:

user_input = input("Enter a fruit ") 
while user_input != "Stop": 
    if len(user_input) <= 5: 
        print(f"I like {user_input}") 
    else: 
        print(f"I do not like {user_input}") 
    # Critical line: Refresh the input for the next loop check
    user_input = input("Enter a fruit ") 
print("Goodbye")

A Couple of Bonus Tweaks

  • I swapped the elif len(user_input) >5 for an else—since if the length isn't ≤5, it has to be >5, this makes the code cleaner.
  • Used an f-string (print(f"I like {user_input}")) instead of concatenating strings—it's more readable and Pythonic.

Now when you type "Stop", the loop condition will fail, the loop exits, and you'll see the "Goodbye" message as expected!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 14:08:14