函数内部while循环触发ValueError的问题分析及修复(add_up函数)
Fixing the ValueError in Your
add_up Function Let's break down why your code is throwing a ValueError when inputting "Stop" first, then fix it up properly.
The Root Problem
Your current code tries to convert every input directly to an integer with string = int(input()) before checking if it's "Stop". When the user types "Stop", Python can't turn that string into an integer—hence the ValueError crash.
Revised Code with Error Handling
Here's a robust version that handles the "Stop" case gracefully, plus deals with other invalid non-integer inputs:
def add_up(): total = 0 while True: # Grab the raw input first, trim any accidental whitespace user_input = input().strip() # Check if we need to stop first if user_input == "Stop": break # Try converting to integer, catch errors if input is invalid try: number = int(user_input) total += number except ValueError: # Optional: Let the user know their input was invalid print(f"Oops, '{user_input}' isn't a valid integer. Please enter a number or 'Stop'.") print(f"Total sum: {total}") add_up()
Key Improvements:
- Check for "Stop" first: We get the raw string input before attempting any conversion, so we can exit the loop immediately when the user types "Stop".
- Try-except block: This catches ValueError whenever the input can't be converted to an integer (like random text or symbols), preventing the program from crashing.
- Cleaner loop structure: Using
while Truewith abreakstatement makes the exit condition clearer than your original loop setup. - Whitespace handling:
strip()ensures accidental spaces around "Stop" (like " Stop ") still trigger the exit.
Quick Note on Your Original Code's Quirks
- Initializing
string = 0(an integer) and then checkingstring is not "Stop"is a bit odd—integers and strings will never be the same object, so that condition was always True anyway. The bigger issue was the premature integer conversion, though.
内容的提问来源于stack exchange,提问作者Liviu Iosif
相关产品推荐
相关产品推荐

