Here are two ways to validate email addresses in Python. One approach is by using loops and IF conditions, and the other one is using regular expressions (regex) with the re-module.
#1 Use For and If conditions
To summarize, it asks the user to supply an email address. It validates conditions with the help of Python’s for loops and if conditions. Accordingly, it prints the result.
email=input("enter your email")
k=0
if len(email) >= 6:
if email[0].isalpha():
if ("@" in email) and (email.count("@") ==1):
if (email[-4]== ".") ^ (email[-3] =="."):
for i in email:
if i.isspace():
k=1
if k==1:
print("wrong email5")
else:
print("wrong email 4")
else:
print("wrong email3")
else:
print("wrong email2")
else:
print("wrong email1")
output
enter your email sri.com
wrong email3
#2 Using regular expression
Alternatively, using the regular expression’s search function you can validate whether the given email follows the specified pattern or not. Further, the below regular expressions have the following meanings.
^[a-z]+: The first letter one or more must be in a to z.
[\._]?: Should have either period or underscore
[a-z 0-9]+: Should have one or more a to z or 0 to 9.
[@\w]: One @ word
[.]: One period
\w{2,3}$: Two or three words at the end.
import re
email_condition="^[a-z]+[\._]?[a-z 0-9]+[@\w]+[.]\w{2,3}$"
user_input=input("enter email")
if re.search(email_condition, user_input):
print("Right Email")
else:
print("Wrong email")
Output
enter email srini@gmail.comRight Email
Related






