python - While loop break/continue not working for me -
i can't see why loop won't continue when input not float! addition issue, don't understand why python tries addition when non float input should terminate loop in exception.
code:
tot1 = 0.0 count1 = 0.0 while(true): inp1 = input('enter number or done 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 , 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) +: 'float' , 'str'
check 'done'
first cast float inp1 = float(inp1)
, don't need call str(inp1)
string, furthermore nothing don't assign variable anyway.
tot1 = 0.0 count1 = 0.0 while true: inp1 = input('enter number or done end:') if inp1 == 'done': print("done!") break try: inp1 = float(inp1) # cast , reassign inp1 except valueerror: # catch specific errors print("error") continue tot1 += inp1 count1 += 1 if tot1 > 0 , count1 > 0: print("average: ", tot1 / count1 ) # tot1/count1 not tot/count
Comments
Post a Comment