0

I have this code:

try:
    phone = int(input("Enter your telephone no. : "))
except ValueError:
    print("You must enter only integers!")
    phone = int(input("Enter your telephone no. : "))

I want the user to enter their telephone number. But if they type anything else apart from integers an error message comes up saying that you can only type integers. What I want to do is to loop this section of the code so that every time the user enters a non-integer value the error message comes up. So far all this code does is, it prints the error message only for the first time. After the first time if the user enters a non-integer value the program breaks.

Please provide a not too complicated solution...I'm just a beginner. I'm thinking you're meant to use a while loop but I don't know how?

2 Answers2

2

I believe the best way is to wrap it in a function:

def getNumber():
    while True:
        try:
            phone = int(input("Enter your telephone no. : "))
            return phone
        except ValueError:
            pass
galah92
  • 3,621
  • 2
  • 29
  • 55
1

You can do it with a while loop like this

while True:
    try:
        phone = int(input("Enter your telephone no. : "))
    except ValueError:
        print("You must enter only integers!")
    else:  # this is executed if there are no exceptions in the try-except block
        break  # break out of the while loop
JakeD
  • 2,788
  • 2
  • 20
  • 29