gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 03:35:52 25 4
gpt4 key购买 nike

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

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'

最佳答案

为什么不先做简单版再优化呢?

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 会自动初始化数据类型。因此,需要显式强制转换。如果我错了请纠正我,但这就是我的看法。

希望我有帮助:)

关于python - 如何使用带有输入函数的for循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40404093/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com