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'
You are never assigning
inp1
to the float you return fromfloat(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 ofinp1
, which you then never assign to anything.In summary,
inp1
is still a string fromraw_input
, which is why you get theTypeError
.