0

I try to validate user input if is integer not in a function.

while True:
    try:
        number = int(input('Enter the number: '))
    except ValueError:
        print('Try again. Input phone number, must containing digits. ')

    break

print (number)

If I enter number it works prints the number (however Pycharm tells me that variable number in last line might ve undefined) however when it crash instead asking for enter again:

Enter the number: s
Try again. Input phone number, must containing digits. 
Traceback (most recent call last):
  line 9, in <module>
    print (number)
NameError: name 'number' is not defined

In a function it seems easier to make but in this case I'm lost.

1 Answers1

0

break means you leave the loop, even if you've had the ValueError, despite number not being assigned yet.

Instead of putting the break outside the try, have you considered putting it inside, so it only triggers if number gets assigned successfully?

while True:
    try:
        number = int(input('Enter the number: '))
        break
    except ValueError:
        print('Try again. Input phone number, must containing digits. ')

print(number)
Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
  • ha, I solved it but in not as good way :-) [code] while True: try: number = int(input('Enter the number: ')) except ValueError: print('Try again. Input phone number, must containing digits. ') else: break print (number) [code] – Ziggy Witkowski Dec 21 '20 at 14:07