当环路中断/继续不工作时

2024-04-23 11:37:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我不明白为什么当输入不是浮点时,我的循环不会继续! 加法显然是问题所在,但我不明白为什么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 )

输出:

^{pr2}$

Tags: orto代码truenumberinputif浮点
2条回答

您永远不会将inp1分配给从float(inp1)返回的浮点。在

您需要重新分配inp1 = float(inp1)。这不是一个循环/中断问题,而是你没有正确分配变量。float(inp1)返回inp1的浮点数,然后永远不会将其分配给任何东西。在

总之,inp1仍然是来自raw_input的字符串,这就是为什么得到TypeError。在

首先检查'done',然后用inp1 = float(inp1)转换为float,不需要调用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

相关问题 更多 >