+ 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.

9th Jan 2022, 3:31 PM
Erfan Bazri
Erfan Bazri - avatar
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
9th Jan 2022, 3:46 PM
Ipang
+ 1
I mean can we write a code like this?: while ValueError: age=int(input("Enter a number: "))
9th Jan 2022, 3:34 PM
Erfan Bazri
Erfan Bazri - avatar
+ 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: ")
9th Jan 2022, 4:07 PM
FanYu
FanYu - avatar