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

编写add_up函数实现用户输入整数累加至Stop停止的代码报错排查

Fixing Your add_up Function

Let's break down the issues in your code and fix them step by step:

Problems with the Original Code

  • Dependence on external input parameter: Your function takes x as an argument, which means it relies on a value passed from outside instead of handling the input flow internally. This breaks encapsulation and can lead to unexpected behavior if the function is called with a non-user-input value.
  • Typos in input prompt: "Another numer" should be "Another number" — a small mistake, but it affects user clarity.
  • No error handling for invalid inputs: If the user enters something that's neither an integer nor "Stop", your code will throw a ValueError and crash immediately.
  • Loop logic relies on initial input: While the loop technically works if the first input is valid, using a while True loop with an explicit break is cleaner and more maintainable.

Corrected Code

def add_up():
    total = 0
    while True:
        user_input = input("Enter a number (or 'Stop' to finish): ")
        # Make the stop command case-insensitive and ignore extra spaces
        if user_input.strip().lower() == "stop":
            break
        try:
            num = int(user_input)
            total += num
        except ValueError:
            print("Oops! Please enter a valid integer or type 'Stop' to exit.")
    return total

# Call the function and print the result
print(add_up())

Key Improvements

  1. Self-contained input handling: The function now manages the entire input process on its own, no need to pass an initial value from outside.
  2. Robust stop detection: Using strip().lower() means inputs like "stop", " STOP", or "Stop" will all trigger the loop to end — more user-friendly.
  3. Error resilience: The try-except block catches invalid integer inputs and gives a helpful message instead of crashing the program.
  4. Cleaner loop structure: while True with break makes the logic easier to follow compared to relying on the initial input value for the loop condition.
  5. PEP8 compliant naming: Changed Num to total to follow Python's naming conventions (snake_case for variables).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:48:22