我在这个问题上有分歧

2024-09-28 22:23:06 发布

您现在位置:Python中文网/ 问答频道 /正文

howManyNames = (float(input("Enter how many student names do you want to enter? ")))
studentNames = []
ages = []
averageAge = 0
counter = 0

while (counter < int(howManyNames)):
    studentNames.append(input("Enter student names. "))
    ages.append(float(input("Enter that persons age. ")))
    counter += 1

averageAge = (float(ages)) / (float(howManyNames))
print (averageAge)

我一直得到这样的类型错误:float()参数必须是字符串或数字

我知道了,但我似乎找不到我的错误,我知道你不能用和浮除数组。。。。谢谢大家!你知道吗


Tags: inputnames错误counterfloatdostudentmany
1条回答
网友
1楼 · 发布于 2024-09-28 22:23:06

更改:

averageAge = (float(ages)) / (float(howManyNames))

收件人:

averageAge = sum(ages) / float(howManyNames)

(注意:出于美观的考虑,我刚刚删除了多余的括号。)

解释:

如果打开repl并键入

In [2]: help(float)

您将获得float的文档,其中说明:

Help on class float in module __builtin__:

class float(object)
 |  float(x) -> floating point number
 |  
 |  Convert a string or number to a floating point number, if possible.
 |  
 |  Methods defined here:
...

换句话说,您可以:

In [3]: float(3)
Out[3]: 3.0

In [4]: float("3")
Out[4]: 3.0

但你不能这样做:

In [5]: float([])
                                     -
TypeError                                 Traceback (most recent call last)
<ipython-input-5-79b9f7854b4b> in <module>()
  > 1 float([])

TypeError: float() argument must be a string or a number

因为[]是一个list,而不是一个字符串或数字,根据它的文档,float是可以接受的。float接受列表也没有意义,因为它的目的是将字符串或数字转换为浮点值。你知道吗

在你的问题中,你定义了:

ages = []

正在将ages设置为[](类型为list

当然,要找到平均值,需要取这些值的和除以它们的值。当然,python碰巧有一个内置的sum函数,它将为您汇总一个列表:

In [6]: sum([])
Out[6]: 0

In [7]: sum([1,2,3]) # 1 + 2 + 3
Out[7]: 6

你只需要除以数值的个数就可以转换平均值。你知道吗

相关问题 更多 >