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

Python新手求助:如何让加法程序回到起始位置重新运行?

Fixing Your Reusable Python Addition Program

Hey there! Let's work through the issues with your code and get that addition program restarting properly. Here's what's going wrong, plus a corrected version:

First, let's break down the bugs in your original code:

  • Indentation & Function Definition: Your start() function was commented out (#def start()), and even if it wasn't, the code inside the function wasn't indented—Python relies entirely on indentation to group code into blocks, so this would break the function structure.
  • Broken Condition Checks: Lines like if restart == "Again" or "again" don't work as intended. The or "again" part always evaluates to True (non-empty strings are truthy in Python), so this condition would trigger no matter what the user types. You need to either check the variable against each value separately, or use .lower() to simplify case handling.
  • Exit Doesn't Execute: exit is a built-in function, so you need to call it with parentheses: exit(). Without parentheses, you're just referencing the function, not actually running it to end the program.
  • Recursion Risk: Using recursive calls to start() could lead to a stack overflow if the user runs the program many times. A loop is a far more reliable approach for repeated execution.

Here's the corrected code using a loop (the best approach for this use case):

while True:
    a = int(input("num1: "))
    b = int(input("num2: "))
    c = a + b
    print("sum of {0} + {1} = {2}".format(a, b, c))
    
    restart = input("Exit or Again?: ")
    # Convert input to lowercase to handle both "Again"/"again" and "Exit"/"exit"
    if restart.lower() == "exit":
        break  # Exit the loop to end the program
    # If user types any variation of "again", the loop will restart automatically

If you still want to use a function approach (for learning purposes), here's a fixed version:

def start():
    a = int(input("num1: "))
    b = int(input("num2: "))
    c = a + b
    print("sum of {0} + {1} = {2}".format(a, b, c))
    
    restart = input("Exit or Again?: ")
    if restart.lower() == "again":
        start()
    elif restart.lower() == "exit":
        exit()

# Call the function to kick off the program
start()

The loop version is preferable for long-term use because recursion has a depth limit in Python—you can only call the function so many times before hitting an error. The loop will keep running indefinitely until the user types any case variation of "Exit".

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 18:29:06