Python最大最小数查找程序故障排查:多值输入时报错问题
First off, let's tackle the immediate error you're seeing when entering comma-separated numbers like 3,4,5: your code uses int(input(...)), which expects a single integer string. When you type a comma-separated list, that's a string with non-numeric characters (the commas) — Python can't convert that directly to an integer, hence the ValueError. The original program is designed to accept one number per input prompt, not multiple values at once. But we can fix that too if you want multi-input support.
Let's walk through all the issues in your code and fix them step by step:
1. Mismatched Sentinel Value & Input Prompt
Your code uses -99 as the "stop" value, but the prompt tells users "Zero indicates end of input" — this is confusing and will lead users to enter the wrong sentinel. We'll align these to match.
2. Redundant Variable Initialization
The line inputNum = int(); smallest = int(); largest = int() is completely unnecessary. You immediately overwrite smallest and largest to None right after, and inputNum gets reassigned in every loop iteration. We'll remove this dead code.
3. Edge Case: No Valid Numbers Entered
If a user immediately enters -99 without inputting any numbers, largest and smallest stay None, resulting in odd output. We'll add a check to handle this scenario gracefully.
Option 1: Fixed Single-Input Program (Original Design)
This keeps the program working as intended (one number per input) but fixes all bugs and improves user experience:
def main(): displayWelcome() smallest = None largest = None SENTINEL = -99 while True: try: inputNum = int(input(f'Enter a number ({SENTINEL} indicates end of input): ')) except ValueError: print("Please enter a valid integer!") continue if inputNum == SENTINEL: print('End of program') break if smallest is None or inputNum < smallest: smallest = inputNum if largest is None or inputNum > largest: largest = inputNum displayLargestSmallest(largest, smallest) def displayWelcome(): print('This program displays the largest and smallest numbers entered by the user from a series of numbers') def displayLargestSmallest(largest, smallest): if largest is None or smallest is None: print("No valid numbers were entered.") else: print(f'The largest number input is {largest}') print(f'The smallest number input is {smallest}') if __name__ == "__main__": main()
Key improvements:
- Aligned the input prompt to correctly mention
-99as the end value - Removed redundant variable initialization
- Added a
try-exceptblock to catch invalid inputs (like letters or symbols) and prompt the user again - Added a check in
displayLargestSmallestto handle empty input cases
Option 2: Support Multi-Input (Comma-Separated Values)
If you want users to enter multiple numbers at once (e.g., 3,4,5), we can modify the input handling to split the string and process each number individually:
def main(): displayWelcome() smallest = None largest = None SENTINEL = -99 while True: user_input = input(f'Enter numbers separated by commas, or {SENTINEL} to end: ') # Check if user entered the sentinel to exit if user_input.strip() == str(SENTINEL): print('End of program') break # Split input into individual number strings num_strings = user_input.split(',') for num_str in num_strings: num_str = num_str.strip() # Remove extra spaces around numbers try: inputNum = int(num_str) except ValueError: print(f"Skipping invalid input: '{num_str}' (not an integer)") continue # Update smallest and largest values if smallest is None or inputNum < smallest: smallest = inputNum if largest is None or inputNum > largest: largest = inputNum displayLargestSmallest(largest, smallest) def displayWelcome(): print('This program displays the largest and smallest numbers entered by the user from a series of numbers') def displayLargestSmallest(largest, smallest): if largest is None or smallest is None: print("No valid numbers were entered.") else: print(f'The largest number input is {largest}') print(f'The smallest number input is {smallest}') if __name__ == "__main__": main()
This version lets users enter multiple numbers per line (comma-separated), skips any invalid entries, and still uses -99 to end the program.
内容的提问来源于stack exchange,提问作者Muhammad Abyan

