Validate Email in Python
In this tutorial, we will learn how to validate email in Python.
Email validation is required in order to determine whether the mail address is valid, risky or Invalid. A valid email is an essential part of any professional. So let’s get right into it.
Email Validation in Python
First of all, we will create a function email_validation() which will take email as a parameter. If you do not know how to define a function, then learn here (Define functions in Python).
Then, we will create a counter a and initialize it with 0. It will be used later to check if our email contains at least one character.
Now, We will use a built-in function len() which will take a string as a parameter and return its length. We store the returned value in y. Also, We will use another built-in function find(). It is used to find and return the index of a particular character or string in a given complete string. Learn about built-in functions in Python here.
y=len(x) dot=x.find(".") at=x.find("@")
Here we have calculated the length of email passed in the function and the position of “@” and “.” in the email.
Basic validations for an email are:
- It must contain at least one alphabet.
- Email cannot start with @
- @ and dot cannot exist together.
- There must be at least one character before @ and after the dot.
To check for the first condition to exist, we will use for loop.
for i in range (0,at): if((x[i]>='a' and x[i]<='z') or (x[i]>='A' and x[i]<='Z')): a=a+1
If there exists an alphabet in the email, we increment our counter a by 1.
Now for all the remaining validations, we use the if-else statement.
if(a>0 and at>0 and (dot-at)>0 and (dot+1)<y): print("Valid Email") else: print("Invalid Email")
If a>0, it means our email contains at least one alphabet.
If our if condition holds, it means our email is valid and we print Valid Email else we print Invalid Email.
Finally, Our code looks like this.
def email_validation(x): a=0 y=len(x) dot=x.find(".") at=x.find("@") for i in range (0,at): if((x[i]>='a' and x[i]<='z') or (x[i]>='A' and x[i]<='Z')): a=a+1 if(a>0 and at>0 and (dot-at)>0 and (dot+1)<y): print("Valid Email") else: print("Invalid Email")
Now let’s try our code by calling the function.
Let’s see another example.