While loop break/continue not working for me

936 views Asked by At

I can't see why my loop won't continue when the input is not a float! The addition is clearly the issue, but I don't understand why python tries addition when any non float input should terminate the loop in the exception.

Code:

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 )

Output:

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'
2

There are 2 answers

0
Alex Huszagh On

You are never assigning inp1 to the float you return from float(inp1).

You need to reassign inp1 = float(inp1). This isn't a loop/break issue, it's you not properly assigning variables. float(inp1) returns the floating point number of inp1, which you then never assign to anything.

In summary, inp1 is still a string from raw_input, which is why you get the TypeError.

0
Padraic Cunningham On

check for 'done' first then cast to float with inp1 = float(inp1), you don't need to call str(inp1) as it is already a string, furthermore it actually does nothing as you don't assign it to any variable anyway.

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