简体   繁体   中英

Try-except or Exceptions in Python

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!!")

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!!")

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

Why would you want negative numbers??? It's a phone number, and with my solution, you can easily edit it and add conditions. try/except should be a fallback, not a default.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM