我不明白为什么当输入不是浮点数时我的循环不会继续! 添加显然是个问题,但我不明白为什么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'
答案 0 :(得分:1)
您永远不会将inp1
分配给从float(inp1)
返回的浮动广告。
您需要重新分配inp1 = float(inp1)
。这不是循环/中断问题,而是您没有正确分配变量。 float(inp1)
返回inp1
的浮点数,然后您永远不会将其分配给任何内容。
总之,inp1
仍然是来自raw_input
的字符串,这就是您获得TypeError
的原因。
答案 1 :(得分:1)
首先检查'done'
然后使用inp1 = float(inp1)
转换为浮动,你不需要调用str(inp1)
,因为它已经是一个字符串,而且它实际上什么也没做,因为你不是无论如何都要将它分配给任何变量。
tot1 = 0.0
count1 = 0.0
while True:
inp1 = input('Enter a number or done to end:')
if inp1 == 'done':
print("done!")
break
try:
inp1 = float(inp1) # cast and actually reassign inp1
except ValueError: # catch specific errors
print("error")
continue
tot1 += inp1
count1 += 1
if tot1 > 0 and count1 > 0:
print("Average: ", tot1 / count1 ) # tot1/count1 not tot/count