训练任务python if循环的问题

时间:2020-11-05 10:50:06

标签: python

我正在尝试创建一个循环以收集天气信息并打印天气在某些预设中的日期。我很努力,因为印刷品仅使用最后一个输入来列出日期,而第一个输入则被丢弃。

使用注释中的更新后,我的代码看起来像这样,但是仍然无法正常工作,该代码忽略了大于和小于,并且正在打印前三天。还会产生此错误:IndexError:字符串索引超出范围

week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

rainlist = []
windlist = []
temperaturelist = []

for day in week:
    rain = input('What is the amount of rain today? ')
    rainlist.append(rain)

    wind = input('What is the current windspeed?  ')
    windlist.append(wind)

    temperature = input('What is the temperature? ')
    temperaturelist.append(temperature)

for idx, day in enumerate(week) : 
    if rain[idx] > '1':
        print(f'it is more than 1mm rain on {day} . It was  {rainlist[idx]}')
    if wind[idx] > '10':
        print(f'it is more than 10m/s of wind on {day}. It was  {windlist[idx]} m/s')     
    if temperature[idx] < '5':
        print(f'it was less than 5 degrees on {day}. It was {temperaturelist[idx]} degrees celsius')

1 个答案:

答案 0 :(得分:1)

您需要索引风,雨和温度列表,可以为此使用enumerate。还要使用format进行输出:

for idx, day in enumerate(week) : 
    if rain[idx] > 1:
        print('it is more than 1mm rain on {}. It was {} mm'.format(day,
        rain[idx]))
    if wind[idx] > 10:
        print('it is more than 10m/s of wind on {}. It was \ 
        {} m/s'.format(day, wind[idx]))        
    if temperature[idx] < 5:
        print('it was less than 5 degrees on {}. It was {} degrees \
        celsius'.format(day, temperature[idx]))