Back to Python
2025-12-105 min read

Email Field (Python Programming)

Learn Email Field (Python Programming) step by step with clear examples and exercises.

Title: Email Field (Python Programming)

Why This Matters

In programming, handling user input is crucial for creating interactive applications. One common type of user input is an email address, which can be validated to ensure it follows a specific format. In this lesson, we will learn how to create an email field in Python and validate its input using regular expressions (regex). This skill is essential for building robust web applications and ensuring user data quality.

Prerequisites

To follow along with this lesson, you should have a basic understanding of the following concepts:

  • Python syntax and variables
  • String manipulation in Python
  • Regular expressions (regex) basics

Core Concept

Creating an Email Field

In Python, we can create an email field using the input() function. This function reads a line from input (usually from the keyboard), converts it to a string, and returns that string. Here's a simple example:

email = input("Enter your email address: ")
print("You entered:", email)

When you run this code, Python will prompt you to enter an email address, and then print the entered email address back to you. However, this approach doesn't validate the email address format, so it may accept invalid emails.

Validating Email Addresses with Regular Expressions (regex)

To ensure that the user enters a valid email address, we can use regular expressions (regex). A regex pattern for a simple email address might look like this:

import re
email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'

This pattern checks for the following:

  • At least one alphanumeric character ([a-zA-Z0-9.])
  • Followed by zero or more of ._%+- characters
  • An @ symbol
  • One or more alphanumeric characters, followed by a period
  • Two or more alphabetic characters ([a-zA-Z]) to represent the domain extension

Validating User Input with regex in Python

Now that we have our email pattern, let's use it to validate user input:

import re
email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'

email = input("Enter your email address: ")
if re.match(email_pattern, email):
print("Valid email address.")
else:
print("Invalid email address.")

In this code, we first import the re module, which provides support for regular expressions in Python. We then define our email pattern and use the input() function to get user input. The re.match() function checks if the entered email matches the defined pattern. If it does, we print "Valid email address."; otherwise, we print "Invalid email address."

Handling Multiple Attempts for Valid Input

In a real-world application, you may want to give users multiple attempts to enter a valid email address. Here's an example of how you can do this:

import re
email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'

attempts = 3
while attempts > 0:
email = input("Enter your email address (you have " + str(attempts) + " attempts left): ")
if re.match(email_pattern, email):
print("Valid email address.")
break
else:
print("Invalid email address.")
attempts -= 1
if attempts == 0:
print("Sorry, you have no more attempts left.")

In this code, we define a variable attempts to keep track of the number of attempts allowed. We then use a while loop to continue asking for user input until they enter a valid email address or run out of attempts.

Worked Example

Let's work through an example together:

import re
email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'

attempts = 3
while attempts > 0:
email = input("Enter your email address (you have " + str(attempts) + " attempts left): ")
if re.match(email_pattern, email):
print("Valid email address.")
break
else:
print("Invalid email address.")
attempts -= 1
if attempts == 0:
print("Sorry, you have no more attempts left.")

Try entering the following emails and observe the output:

  • john.doe@example.com (valid)
  • john_doe@example (invalid — missing domain extension)
  • john.doe@example.co (invalid — incorrect domain extension length)
  • john.doe@example..com (invalid — extra period)
  • john.doe@example.com@example.com (invalid — nested email addresses)

Common Mistakes

  1. Not importing the re module: Remember to import the re module at the beginning of your script, as shown in the examples above.
  2. Incorrect regex pattern: Make sure your regex pattern is correct and captures all valid email addresses you want to accept. You may need to adjust it based on your specific requirements.
  3. Not handling multiple attempts: In a real-world application, you should give users multiple attempts to enter a valid email address.
  4. Forgetting to check for user input: If you forget to assign the input() function to a variable, the validation will not work as expected.
  5. Not accounting for case sensitivity: The regex pattern is case-sensitive by default. To make it case-insensitive, add (?i) before the pattern:
email_pattern = r'(?i)^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'

Practice Questions

  1. Write a Python script that validates a user's email address using the provided regex pattern and allows for an unlimited number of attempts.
  2. Modify the regex pattern to accept domain extensions with more than two characters (e.g., .co.uk).
  3. Modify the script from question 1 to print a custom message after the user enters a valid email address.
  4. Add a check for the local part of the email address (the part before the @ symbol) to ensure it contains at least one alphanumeric character and no spaces.
  5. Create a list of common typos in email addresses (e.g., missing periods, extra spaces, misspelled domains). Write a Python script that validates user input against this list of typos as well as the regex pattern.

FAQ

  1. Why is my regex pattern not accepting some valid emails?: Make sure your pattern covers all the email formats you want to accept. You may need to adjust it based on your specific requirements.
  2. How can I make my regex pattern case-insensitive?: Add (?i) before the pattern, as shown in the "Common Mistakes" section.
  3. Can I use a different library for email validation instead of regular expressions?: Yes, there are other libraries available for email validation in Python, such as EmailValidator and validators.email. You can explore these options if you prefer them over using regex.
Email Field (Python Programming) | Python | XQA Learn