编写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
xas 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
ValueErrorand crash immediately. - Loop logic relies on initial input: While the loop technically works if the first input is valid, using a
while Trueloop with an explicitbreakis 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
- Self-contained input handling: The function now manages the entire input process on its own, no need to pass an initial value from outside.
- Robust stop detection: Using
strip().lower()means inputs like "stop", " STOP", or "Stop" will all trigger the loop to end — more user-friendly. - Error resilience: The
try-exceptblock catches invalid integer inputs and gives a helpful message instead of crashing the program. - Cleaner loop structure:
while Truewithbreakmakes the logic easier to follow compared to relying on the initial input value for the loop condition. - PEP8 compliant naming: Changed
Numtototalto follow Python's naming conventions (snake_case for variables).
内容的提问来源于stack exchange,提问作者Michael
相关产品推荐
相关产品推荐

