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

函数内部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 True with a break statement 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 checking string 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:41:35