You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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 (since range is 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: sum is a built-in Python function, so renaming that variable to something like total_temp avoids 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_num will 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 += temperature is just a more concise way to write the addition—functionally identical to your original line, but cleaner and more Pythonic.

内容的提问来源于stack exchange,提问作者user16946766

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 13:47:45