【问题标题】:Type Error in nested for loops嵌套 for 循环中的类型错误
【发布时间】:2011-03-23 05:13:55
【问题描述】:

涉及调用多个 for 循环的类的作业问题,这是硬件问题:

平均温度

编写一个程序,使用嵌套循环来收集数据并计算几个月内的平均温度。该程序应首先询问月数。外部循环将每月迭代一次。内部循环将迭代四次,每月每周一次。内部循环的每次迭代都会询问用户该周的平均温度。在所有迭代之后,程序应该显示每个月的平均温度,以及整个时期(所有月份)

这是我所做的:

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

非常感谢任何帮助!

【问题讨论】:

  • num1= input('请输入',y,'月',i,'月'的平均气温,':') 这个函数只接受1个参数,不接受5个
  • 考虑为每个输入变量编写多个输入调用

标签: python debugging loops for-loop


【解决方案1】:

阅读错误:您正在输入 5 个参数。

用 + 操作符连接字符串,而不是逗号

【讨论】:

    【解决方案2】:

    num1 = input('Please enter the average temperature for week %s in month %s: '%(y,i))

    【讨论】:

      【解决方案3】:

      按照 cmets 中的建议,看看其他连接字符串的方法。

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

      【讨论】:

        猜你喜欢
        • 2019-03-12
        • 2012-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-02
        • 1970-01-01
        相关资源
        最近更新 更多