如何在Python循环中实现输入语句的天数序号递增?——求平均温度程序调试求助
Fixing the Day Number in Temperature Inputs
Got it, let's get that dynamic day number showing up in your input prompts! The issue right now is that your loop uses range(days) which starts at 0, and you aren't inserting that number into your input string. Here's how to adjust it:
Key Changes:
- Instead of looping from 0 to days-1, use
range(1, days+1)to get numbers starting at 1 and going up to your total days (sincerangeis exclusive of the end value). - Use an f-string to inject the current day number directly into your input prompt—this keeps the code clean and readable.
- A quick best practice note:
sumis a built-in Python function, so renaming that variable to something liketotal_tempavoids accidentally overriding the built-in (not strictly necessary here, but avoids potential headaches later!).
Modified Code:
# Determine average temperature days = input("How many days are you entering temperatures for:") days = int(days) total_temp = 0 # Renamed from 'sum' to avoid overriding built-in function for day_num in range(1, days + 1): temperature = input(f"What temp was it on day {day_num}?") temperature = int(temperature) total_temp += temperature # Shorthand for total_temp = total_temp + temperature average_temperature = total_temp / days print("Average temperature:", average_temperature)
How It Works:
- The loop variable
day_numwill take values 1, 2, ..., days on each iteration, perfectly matching the day sequence users expect. - The f-string
f"What temp was it on day {day_num}?"replaces{day_num}with the current iteration's number, so users see the correct day label every time they're asked for a temperature. - Using
total_temp += temperatureis just a more concise way to write the addition—functionally identical to your original line, but cleaner and more Pythonic.
内容的提问来源于stack exchange,提问作者user16946766
相关产品推荐
相关产品推荐

