如何修复Python中输入‘Stop’无法终止的while循环代码
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) >5for anelse—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

