Home > database >  Try-except or Exceptions in Python
Try-except or Exceptions in Python

Time:12-12

I'm new to programming and am struggling to get my Try-except function to work. I want the user to be able to only write a number using digits and when they type in a letter or symbol I want the except statement to start. How should I do? Thank you very much!

while True:
  try:
    x = int(input("Please write your phone number to receive a confirmation: "))
     
  except: 
    print("Obs!")
    break
    
print("You did not write a real number : {0}".format(x))
print("No symbols or letters allowed!!")

CodePudding user response:

You want to put all of those warning prints in the exception handler. And assuming you want to keep prompting until a number is entered, do the break after the successful conversion.

When int fails, the assignment to x is skipped and its value is not available in the exception. Since you want to echo wrong choices back to the user, save the text value to an intermediate variable.

while True:
    try:
        answer = input("Please write your phone number to receive a confirmation: ")
        x = int(answer)
        break
     
    except ValueError: 
        print("Obs!")    
        print("You did not write a real number : {0}".format(answer))
        print("No symbols or letters allowed!!")

CodePudding user response:

No need to use try/except statements. A more pythonic way to do it is to simply wrap it in a while statement and use x.isnumeric(). The benefit of this is that you can continue execution afterwards

done = False

while not done:
    x = input('Please write your phone number to receive a confirmation: ')

    if x.isnumeric():
        done = True
        x = int(x)
    else:
        print("Obs!")    
        print("You did not write a real number : {0}".format(x))
        print("No symbols or letters allowed!!")
# anything else here
  • Related