我只需要对三个数字求和并计算平均值
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'
该input()
函数返回一个字符串(str),Python不会自动将其转换为float / integer。您需要做的就是将其转换。
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))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句