【发布时间】:2015-06-13 10:35:43
【问题描述】:
我不明白为什么当输入不是浮点数时我的循环不会继续! 加法显然是问题所在,但我不明白为什么 python 在任何非浮点输入应终止异常中的循环时尝试加法。
代码:
tot1 = 0.0
count1 = 0.0
while(True):
inp1 = input('Enter a number or done to end:')
try:
float(inp1)
except:
str(inp1)
if(inp1 == 'done'):
print("done!")
break
print("Error")
continue
tot1 = tot1+inp1
count1 = count1+1
if(tot1 >0 and count1 >0):
print("Average: ", tot/count )
输出:
Traceback (most recent call last):
File "C:/Users/GregerAAR/PycharmProjects/untitled/chap5exc.py", line 16, in <module>
tot1 = tot1+inp1
TypeError: unsupported operand type(s) for +: 'float' and 'str'
【问题讨论】:
-
请阅读此内容 — stackoverflow.com/editing-help。
-
Sergey,我的问题有什么可以改进的吗?任何反馈将不胜感激:)
-
现在我觉得没问题了。我的意思是格式化。
标签: python while-loop break continue