0

So i'm new to python and i was wondering how to repeat code after an exception.

Like for and example:

try:
    number = int(input('Enter a number: ')
    print(number)
except ValueError:
    print('You must enter a number')

so insted of ending the code I would want to make the Enter a number: input appear again after without repeating the same code again.

Puffy
  • 11
  • 1

2 Answers2

1

https://www.w3schools.com/python/python_while_loops.asp

If you don't want it to repeat if it's successful add keyword 'break' after print.

while True:
    try:
        number = int(input('Enter a number: ')
        print(number)
    except ValueError:
        print('You must enter a number')
Daniel Boyer
  • 371
  • 3
  • 18
  • I meant repeating the code after after the error appears like if some1 types letters into the output instead of the numbers – Puffy Oct 24 '20 at 14:35
  • This will work, if you don't want it to repeat after correct input add the work "break" after print(number) – Daniel Boyer Oct 24 '20 at 14:36
0

You can use a while loop like this:

is_no_number = True
while is_no_number:
    try:
        number = int(input('Enter a number: '))
        print(number)
        is_no_number = False
    except ValueError:
        print('You must enter a number')