如何在循环中将所有输入值存入列表?气象程序开发问题求助
Fixing Your Precipitation Data Collection Code
Hey there! Let's work through why your list is only storing the last input value, and fix it up so you can properly collect all 12 months of data for your weather program.
What's Going Wrong in Your Current Code
Let's break down the key issues:
- You're resetting the list every time: Your
arr = []line is inside the while loop, which means every time you enter a new month's data, you wipe out all previous entries and start fresh. - Unnecessary nested loop: The
for A in range(1,12)loop is adding the same single input value 11 times to the list—this is why you end up with a list full of the last number you entered. - Redundant variables: You're tracking
num_valuesandnseparately, which complicates the loop logic unnecessarily.
Corrected Code
Here's a cleaned-up version that properly collects 12 months of precipitation data into a list:
def input_precipitation(): # Initialize the empty list OUTSIDE the loop so it doesn't get reset precip_data = [] month_num = 0 # Loop until we have 12 valid entries while len(precip_data) < 12: month_num += 1 user_input = input(f"Enter precipitation data for month {month_num}: ") # Add error handling to catch non-integer inputs try: precip_value = int(user_input) precip_data.append(precip_value) except ValueError: print("Oops, please enter a valid whole number for precipitation.") month_num -= 1 # Don't increment the month if input is invalid # Print the collected data to verify print("\nCollected monthly precipitation data:") for value in precip_data: print(value) return precip_data # Call the function to get your data weather_data = input_precipitation()
Key Improvements Explained
- Persistent list: By initializing
precip_dataoutside the while loop, we keep all entries as we add them, instead of wiping the list each time. - Simpler loop condition: Using
len(precip_data) < 12directly checks if we have all 12 months of data, no need for extra counters. - Input validation: The
try/exceptblock prevents the program from crashing if someone enters text instead of a number, and lets the user retry the same month. - Clearer naming: Renamed variables to be more descriptive (e.g.,
precip_datainstead ofarr) so your code is easier to read and maintain later.
Bonus: Adding Your Calculations
Once you have the list of data, you can easily compute the values you need:
# Calculate average monthly precipitation monthly_average = sum(weather_data) / len(weather_data) print(f"\nAnnual average monthly precipitation: {monthly_average:.2f}") # Find highest and lowest monthly precipitation max_precip = max(weather_data) min_precip = min(weather_data) print(f"Highest monthly precipitation: {max_precip}") print(f"Lowest monthly precipitation: {min_precip}")
内容的提问来源于stack exchange,提问作者Beastmaster64
相关产品推荐
相关产品推荐

