【问题标题】:While loop break/continue not working for me虽然循环中断/继续对我不起作用
【发布时间】: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


【解决方案1】:

首先检查'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

【讨论】:

    【解决方案2】:

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

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

    总之,inp1 仍然是来自raw_input 的字符串,这就是你得到TypeError 的原因。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-09-30
      • 1970-01-01
      • 1970-01-01
      • 2021-09-20
      • 2012-04-26
      相关资源
      最近更新 更多