【问题标题】:'float' object not iterable?“浮动”对象不可迭代?
【发布时间】:2023-03-09 09:46:01
【问题描述】:

我正在尝试以英寸为单位汇总总降雨量以显示总数,但是当我运行代码时,我得到一个 TypeError 说“'float' object is not iterable”。知道我做错了什么吗?

months = 12

def main():

    rain = get_rain()

    total = get_total(rain)

    avg = total / len(rain)

    low = min(rain)

    high = max(rain)

    print('The total rainfall in inches for the year is: ', format(total, ',.2f'))
    print()
    print('The average monthly rainfall this year was: ', format(avg, ',.2f'))
    print()
    print('The lowest rainfall in inches this year was: ', format(low, ',.2f'))
    print()
    print('The highest rainfall in inches this year was: ', format(high, ',.2f'))
    print()

def get_rain():

    rain_in = []

    print('Enter the amount of rainfall in inches for each month of the year.')
    print('------------------------------------------------------')

    for index in range(months):
          print('Enter the total rainfall in inches for month #', index + 1, ': ', sep='', end='')
          rain_inches = float(input())

          rain_in.append(rain_inches)

    return rain_inches

def get_total(rain_in_list):

          total = 0.0

          for num in rain_in_list:
              total += num

          return total

main()

追溯:

Traceback (most recent call last):
  File "C:/Users/Robert Rodriguez/Desktop/fall 2013-2014/Intro-python/python6/exercise8-3.py", line 50, in <module>
    main()
  File "C:/Users/Robert Rodriguez/Desktop/fall 2013-2014/Intro-python/python6/exercise8-3.py", line 9, in main
    total = get_total(rain)
  File "C:/Users/Robert Rodriguez/Desktop/fall 2013-2014/Intro-python/python6/exercise8-3.py", line 45, in get_total
    for num in rain_in_list:
TypeError: 'float' object is not iterable

即使是在正确的方向上稍微推动一下也会有所帮助。我觉得我正处于解决这个问题的边缘。

【问题讨论】:

  • 请发布完整的回溯
  • input() 接受提示字符串,所以最好使用input("Enter the amount of rainfall...")
  • 与您的异常无关:您可以使用str.format 方法而不是内置的format 函数来简化一些打印调用。例如,print('The total rainfall in inches for the year is: {.2f}'.format(total))。对于您的输入提示,您可以直接在 input 调用中执行此格式化(它将在请求输入的行的开头打印):input('Enter the total rainfall in inches for month #{}: '.format(index + 1))
  • 请注意:您的 get_toal 函数已经存在于 Python 中。它被称为sum
  • 感谢您的提示! @blckknght- 这是一些有用的建议,我会尝试一下,看看我能学到什么 :) ryanthompson- 有道理,我将如何实现它?

标签: python typeerror iterable


【解决方案1】:

get_rain你返回

return rain_inches #float

而不是

return rain_in #list

【讨论】:

  • 啊!所以很容易被忽视。会做出调整,希望不会再错过。谢谢!
猜你喜欢
  • 2014-03-16
  • 1970-01-01
  • 2011-12-28
  • 2018-05-15
  • 1970-01-01
  • 2021-03-01
  • 2021-05-16
  • 2014-03-24
  • 1970-01-01
相关资源
最近更新 更多