如何使用带有输入函数的for循环

新手上路,请多包涵

我只需要将三个数字相加并计算平均值

import sys
sums=0.0
k=3
for w in range(k):
    sums = sums + input("Pleas input number " + str(w+1) + " ")
print("the media is " + str(sums/k) + " and the Sum is " + str(sums))

和错误:

 Pleas input number 1 1
Traceback (most recent call last):
  File "/home/user/Python/sec001.py", line 5, in <module>
    sums = sums + input("Pleas input number " + str(w+1) + " ");
TypeError: unsupported operand type(s) for +: 'float' and 'str'

原文由 userDepth 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 573
2 个回答

input() 函数返回一个字符串(str),Python 不会自动将其转换为浮点数/整数。您需要做的就是转换它。

 import sys;
sums=0.0;
k=3;
for w in range(k):
    sums = sums + float(input("Pleas input number " + str(w+1) + " "));
print("the media is " + str(sums/k) + " and the Sum is " + str(sums));

如果你想做得更好,你可以使用 try/except 来处理无效输入。此外,不需要 import sys ,您应该避免使用分号。

 sums=0.0
k=3
for w in range(k):
    try:
        sums = sums + float(input("Pleas input number " + str(w+1) + " "))
    except ValueError:
        print("Invalid Input")
print("the media is " + str(sums/k) + " and the Sum is " + str(sums))

原文由 BernardoGO 发布,翻译遵循 CC BY-SA 3.0 许可协议

为什么不做简单的版本然后优化呢?

 def sum_list(l):
    sum = 0
    for x in l:
        sum += x
    return sum

l = list(map(int, input("Enter numbers separated by spaces:  ").split()))
sum_list(l)

您的问题是您没有将输入从“str”转换为“int”。请记住,Python 会自动初始化数据类型。因此,需要显式转换。如果我错了,请纠正我,但这就是我的看法。

希望我有所帮助 :)

原文由 MichaelMMeskhi 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题