+ 1
How to use while loop for exception handling?
try: age=int(input("How old are you?: ")) except ValueError: age=int(input("Please enter a number: ")) #If user make a mistake for the second time , it will not work #I know the isdigit() method , But need some thing for floats too.
3 Antworten
+ 3
while True:
try:
print( 'Enter a number: ' )
val = float( input() )
print( f'Input given {val}' )
break
except ( TypeError, ValueError ):
continue
except EOFError:
break
+ 1
I mean can we write a code like this?:
while ValueError:
age=int(input("Enter a number: "))
+ 1
Loop input does not work in the code playground.
Maybe, you should separate the logic of initializing situation and exception.
age = input("How old are you?: ")
while True:
if age.isdigit():
age = int(age)
break
else:
age = input("Enter a number: ")