嵌套循环中的类型错误

0 投票
3 回答
979 浏览
提问于 2025-04-16 14:14

这是一个课堂作业,涉及到使用多个循环,作业内容如下:

平均温度

写一个程序,使用嵌套循环来收集数据并计算几个月的平均温度。程序首先要询问用户几个月。外层循环会针对每个月执行一次。内层循环会执行四次,分别对应一个月中的每一周。每次内层循环都会询问用户那一周的平均温度。在所有循环结束后,程序应该显示每个月的平均温度,以及整个期间(所有月份)的平均温度。

这是我写的代码:

def avg_temp():
temp_sum=0
num= input('Please enter the number of months: ')
for i in range(1,num+1):
    for y in range(1,5):
        num1= input('Please enter the average temperature for week ',y,'in month ',i,': ')
        temp_sum+=num1
    avg_temp_month==(temp_sum/4)
    print 'The average temperature for month ',i,'is: ',avg_temp_month
avg_temp_period==(avg_temp_month/num)
print 'The average temperature for all ',num,' months is: ',avg_temp_period
avg_temp()

当我输入一个值,比如5时,我收到这个错误:

Please enter the number of months: 5
Traceback (most recent call last):
File "C:/Users/Jonathan Cohen/Desktop/School/CISC 106 Spring/lab4.py", line 22, in     
avg_temp() File "C:/Users/Jonathan Cohen/Desktop/School/CISC 106 Spring/lab4.py", line 
15, in avg_temp num1= input('Please enter the average temperature for week ',y,'in    
month ',i,': ') TypeError: [raw_]input expected at most 1 arguments, got 5

任何帮助都非常感谢!

3 个回答

0

正如评论中提到的,看看其他连接字符串的方法。

http://skymind.com/~ocrow/python_string/

1

看看这个错误提示:你输入了5个参数。

连接字符串的时候用+号,而不是用逗号。

1

这行代码的意思是:让用户输入一个数字,这个数字代表某个月(%s表示一个占位符)里某一周(%s也是一个占位符)的平均温度。这里的'y'和'i'是之前定义的变量,它们会被实际的值替换掉。用户输入的这个温度值会被存储在变量'num1'里。

撰写回答