Home > Software engineering >  While Try Except Python
While Try Except Python

Time:08-17

what i want is if the user enter the email address in a wrong format, it should trigger the except, print the error and head back to try.

x = True
while x==True:
    try:
        email = (input("Enter Email: "))
        if re.fullmatch(regex,email):
        x = False
    except:
        print("Email is inValid. Please type in this format: [email protected]")

the code works fine if you correctly input the email, but when you do it wrong, it will head back to try without triggering the except

CodePudding user response:

Your code does not raise any exception. Just use a good old "if/else" statement instead, as follows:

x = True
while x==True:
    email = (input("Enter Email: "))
    if re.fullmatch(regex,email):
        x = False
    else:
        print("Email is inValid. Please type in this format: [email protected]")

And it could be a little shorter, as follows:

while True:
    email = input("Enter Email: ")
    if re.fullmatch(regex, email):
        break
    print("Email is inValid. Please type in this format: [email protected]")

CodePudding user response:

You can use the assert statement if you prefer the flow of raising and catching an exception:

while True:
    try:
        email = input("Enter Email: ")
        assert re.fullmatch(regex, email)
        break
    except AssertionError:
        print("Email is inValid. Please type in this format: [email protected]")
  • Related