Email Validator in Python.
About the project: This will be self-contained script that checks if a given email address follows a valid format.
This Python script is a complete and interactive email validator.
It uses the re module for regular expressions, which is a powerful way to handle string pattern matching.
How to use this program:
Run the Python script.
When you run it, you can enter any email address, and the program will tell you if it's valid.
The program will continue to run until you type q to quit.
The program will use regular expressions to perform a robust validation of the email format.
It will run in a continuous loop, so you can check multiple email addresses without restarting the program.
Project Level: Beginner
You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.
Steps: Follow these stepsStep 1: Copy below code using green 'copy' button.
Step 2: Paste the code on your chosen editor.
Step 3: Save the code with filename and .py extention.
Step 4: Run (Press F5 if using python IDLE)
# email_validator.py
import re
def validate_email(email):
"""
Validates an email address using a regular expression.
The regex checks for a basic email format:
- A username (one or more word characters, dots, or hyphens)
- Followed by an '@' symbol
- Followed by a domain name (one or more word characters, dots, or hyphens)
- Followed by a top-level domain (e.g., .com, .org, .net)
Args:
email (str): The email address to validate.
Returns:
bool: True if the email is in a valid format, False otherwise.
"""
# Regex for a basic email validation
regex = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
# Use re.fullmatch() to ensure the entire string matches the pattern
if re.fullmatch(regex, email):
return True
else:
return False
def main():
"""
Main function to run the Email Validator in a continuous loop.
"""
print("--- Python Email Validator ---")
print("Enter an email address to validate (or 'q' to quit).")
while True:
user_input = input("\nEnter an email address: ").strip()
# Check if the user wants to quit
if user_input.lower() == 'q':
print("Exiting Email Validator. Goodbye!")
break
if not user_input:
print("Please enter an email address.")
continue
if validate_email(user_input):
print(f"Result: '{user_input}' is a valid email address.")
else:
print(f"Result: '{user_input}' is not a valid email address.")
# This ensures that main() is called only when the script is executed directly.
if __name__ == "__main__":
main()