Python无列表实现输入年龄取最大两个值程序的BUG排查请求
Fixing Your Age Tracking Program
Let's break down the issues in your code and fix them step by step:
Main Problems in Your Original Code
- Unprocessed First Input: You read the first age, but immediately overwrite it with a new input at the start of the loop before ever checking if it should update
oldest_ageorsecond_oldest_age. That's why your input of 10 was completely ignored! - Premature Printing: Your
printstatement is inside theelseblock, which means it runs every time an age doesn't fit theiforelifconditions—way too early. You only need to print once after all input is done. - Missing Duplicate Handling: If you enter duplicate maximum ages (like 20, 20), your original code wouldn't update the second oldest age correctly.
Corrected Code
oldest_age = 0 second_oldest_age = 0 # Read the first age to start the loop age = int(input()) while age != -1: # Process the current age before reading the next one if age > oldest_age: second_oldest_age = oldest_age oldest_age = age elif age > second_oldest_age: second_oldest_age = age # Read the next age for the next iteration age = int(input()) # Print the results once after input is complete print(oldest_age, second_oldest_age)
How It Works with Your Test Case (10, 11, -1)
- First input is 10: we process it, updating
oldest_ageto 10 andsecond_oldest_agestays 0. - Next input is 11: it's larger than 10, so
second_oldest_agebecomes 10 andoldest_agebecomes 11. - Final input is -1: loop exits, and we print 11 and 10—exactly what you need!
Edge Case Notes
- If you enter duplicate maximum ages (e.g., 20, 20, -1), the code will correctly output 20 and 20.
- If you only enter one age before -1 (e.g., 5, -1), it will output 5 and 0—you could add a check for this if you want to handle single-input cases differently, but that's beyond the original problem scope.
内容的提问来源于stack exchange,提问作者Annahita
相关产品推荐
相关产品推荐

