๐ Day 102/150 – Email Validation Program in Python
Email validation is a common task in many applications such as registration forms, login systems, and contact forms. A valid email address should follow a proper format, such as containing an @ symbol, a domain name, and a valid extension.
In this post, we'll explore four different ways to validate an email address in Python.
Method 1 – Basic Email Validation
Check whether the email contains both @ and ..
Sample Input
user@example.comValid Email
Output
Explanation
input() reads the email address.
The program checks if the email contains both @ and ..
If both are present, it considers the email valid.
Otherwise, it prints "Invalid Email".
Method 2 – Check Email Format
Ensure the email contains exactly one @ and ends with a common domain extension.
python@gmail.comemail = input("Enter your email: ") if email.count("@") == 1 and email.endswith((".com", ".org", ".net")): print("Valid Email") else: print("Invalid Email")
Sample Input
Output
Valid EmailExplanation
- count("@") ensures there is only one @.
- endswith() checks if the email ends with .com, .org, or .net.
- Both conditions must be true for the email to be valid.
Method 3 – Using Regular Expressions
Use Python's re module for more accurate email validation.
hello123@gmail.comimport re email = input("Enter your email: ") pattern = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$" if re.match(pattern, email): print("Valid Email") else: print("Invalid Email")
Sample Input
Output
Valid EmailExplanation
The re module provides support for regular expressions.
re.match() checks whether the email matches the specified pattern.
This method is more reliable than checking only for @ and ..
Method 4 – Validate Multiple Email Addresses
Check several email addresses stored in a list.
alice@gmail.com - Validemails = [ "alice@gmail.com", "bob@yahoo", "charlie@example.com" ] for email in emails: if "@" in email and "." in email: print(email, "- Valid") else: print(email, "- Invalid")
Output
Explanation
A list of email addresses is created.
The for loop checks each email one by one.
Emails containing both @ and . are marked as valid.
Others are marked as invalid.
Comparison of Methods
| Method | Best For |
|---|---|
| Basic Validation | Beginners learning string operations |
| Format Check | Simple real-world validation |
| Regular Expressions | Accurate email validation |
| Multiple Emails | Validating lists of email addresses |
๐ฅ Key Takeaways
Email validation helps ensure users enter properly formatted email addresses.
Basic validation checks for the presence of @ and ..
count() and endswith() provide additional format checks.
The re module offers a more robust way to validate email addresses using regular expressions.
Email validation is commonly used in registration forms, login systems, and web applications.
Stay tuned for Day 103 of the #150DaysOfPython series! ๐


0 Comments:
Post a Comment