Back to: Python Programming
Input validation ensures that data entered by the user is correct, safe, and in the expected format. In Python, input validation is essential for creating robust, error free programs that can handle incorrect or unexpected inputs. Python provides several ways to validate user inputs, let’s explore some.
Using try-except for Type Validation
One of the simplest methods to ensure the input is of the correct type is to use a try-except block. For example, when accepting numeric input, we can ensure that the user enters a valid integer.
while True:
try:
age = int(input("Enter a number: "))
break
except ValueError:
print("Invalid input!")
print(age)
Output:
Enter a number: Bob
Invalid input!
Enter a number: 23
23
Explanation: If the user enters something that cannot be converted to an integer (like a string), a ValueError is raised, and the user is prompted again.
Using if Statements for Range Validation
For situations where you need to ensure the input is within a certain range, you can use a simple if statement.
while True:
age = int(input("Enter age: "))
if 0 <= age <= 120:
break
else:
print("Enter a valid age inside the range (0-120)")
print(age)
Outputs:
Enter age: 150
Enter a valid age inside the range (0-120)
Enter age: 16
16
Explanation: In this case, the function will repeatedly prompt the user until they enter a valid age.
Combining the two: if statement & try-except for Type & Range Validation
while True:
try:
age = int(input("Enter age: "))
if 0 <= age <= 120:
break
else:
print("Enter a valid age inside the range (0–120)")
except ValueError:
print("Invalid input! Please enter a number.")
print(age)
Outputs:
Enter age: Bob
Invalid input! Please enter a number.
Enter age: 150
Enter a valid age inside the range (0–120)
Enter age: 45
45
Using Regular Expressions for Format Validation
For more complex input validation, such as ensuring an email address or phone number follows a particular format, regular expressions (regex) are useful.
import re
while True:
email = input("Enter email: ")
pattern = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"
if re.match(pattern, email):
break
else:
print("Invalid email format")
print(email)
Outputs:
Enter email: bob$gmail.com
Invalid email format
Enter email: bob@gmail.com
bob@gmail.com
Explanation: regular expression pattern ensures that the input matches the typical structure of an email address.
Validation using a function
It can be extremely useful to wrap input validation logic into a reusable function:
def get_valid_age(prompt="Enter age: ", min_age=0, max_age=120):
while True:
try:
age = int(input(prompt))
if min_age <= age <= max_age:
return age
else:
print(f"Enter a valid age inside the range ({min_age}–{max_age})")
except ValueError:
print("Invalid input! Please enter a number.")
# Example usage:
user_age = get_valid_age()
print(f"Validated age: {user_age}")
Outputs:
Enter age: Bob
Invalid input! Please enter a number.
Enter age: 133
Enter a valid age inside the range (0–120)
Enter age: 13
Validated age: 13
Benefits of this function:
- Reusable: You can call
get_valid_age()anywhere in your code. - Customisable: You can change the prompt and range if needed, like:
age = get_valid_age(prompt="Please enter your age: ", min_age=1, max_age=100)
- Clean: Keeps your main program logic separate from input handling.
More Validation of Name, Email and Age using functions
Full input validation can involve quite a bit of complexity.
import re
def get_valid_age(prompt="Enter age: ", min_age=0, max_age=120):
while True:
try:
age = int(input(prompt))
if min_age <= age <= max_age:
return age
else:
print(f"Enter a valid age inside the range ({min_age}–{max_age})")
except ValueError:
print("Invalid input! Please enter a number.")
def get_valid_name(prompt="Enter name: "):
while True:
name = input(prompt).strip()
if name.isalpha() and len(name) >= 2:
return name
else:
print("Invalid name! Use letters only and at least 2 characters.")
def get_valid_email(prompt="Enter email: "):
email_regex = r"^[\w\.-]+@[\w\.-]+\.\w{2,}$"
while True:
email = input(prompt).strip()
if re.match(email_regex, email):
return email
else:
print("Invalid email! Please enter a valid email address.")
# Example usage
name = get_valid_name()
email = get_valid_email()
age = get_valid_age()
print(f"\nValidated Inputs:\nName: {name}\nEmail: {email}\nAge: {age}")
Outputs:
Enter name: 23
Invalid name! Use letters only and at least 2 characters.
Enter name: Shane
Enter email: shane
Invalid email! Please enter a valid email address.
Enter email: shane@dickinson.com.au
Enter age: 133
Enter a valid age inside the range (0–120)
Enter age: 33
Validated Inputs:
Name: Shane
Email: shane@dickinson.com.au
Age: 33
Full Validation of Name, Email and Age using functions
Lets get silly (this is well beyond what you need to know – but if you understand it, use it:
import re
def get_valid_age(prompt="Enter age: ", min_age=0, max_age=120):
while True:
try:
age = int(input(prompt))
if min_age <= age <= max_age:
return age
else:
print(f"Enter a valid age inside the range ({min_age}–{max_age})")
except ValueError:
print("Invalid input! Please enter a number.")
def get_valid_name(prompt="Enter full name: "):
while True:
name = input(prompt).strip()
if all(part.isalpha() for part in name.split()) and len(name) >= 2:
return name
else:
print("Invalid name! Use letters only and at least 2 characters.")
def get_valid_email(prompt="Enter email: "):
email_regex = r"^[\w\.-]+@[\w\.-]+\.\w{2,}$"
while True:
email = input(prompt).strip()
if re.match(email_regex, email):
return email
else:
print("Invalid email! Please enter a valid email address.")
def get_valid_phone(prompt="Enter phone number: "):
phone_regex = r"^\+?[\d\s\-()]{7,20}$"
while True:
phone = input(prompt).strip()
if re.match(phone_regex, phone):
return phone
else:
print("Invalid phone number! Use digits, spaces, dashes, and optional +.")
def get_valid_password(prompt="Enter password: "):
print("Password must be at least 8 characters, include a number, a capital letter, and a special character.")
password_regex = r"^(?=.*[A-Z])(?=.*\d)(?=.*[^A-Za-z0-9]).{8,}$"
while True:
password = input(prompt)
if re.fullmatch(password_regex, password): # changed from re.match to re.fullmatch
return password
else:
print("Weak password! Please follow the password rules.")
# Example usage
name = get_valid_name()
email = get_valid_email()
phone = get_valid_phone()
age = get_valid_age()
password = get_valid_password()
print("\n✅ Validated Inputs:")
print(f"Name: {name}")
print(f"Email: {email}")
print(f"Phone: {phone}")
print(f"Age: {age}")
print(f"Password: {'*' * len(password)}") # Hide actual password
Outputs:
Enter full name: 45
Invalid name! Use letters only and at least 2 characters.
Enter full name: Shane Dickinson
Enter email: shane
Invalid email! Please enter a valid email address.
Enter email: shane@dickinson.com.au
Enter phone number: (03)98765432
Enter age: 155
Enter a valid age inside the range (0–120)
Enter age: 55
Password must be at least 8 characters, include a number, a capital letter, and a special character.
Enter password: ASDasd123!@#
Validated Inputs:
Name: Shane Dickinson
Email: shane@dickinson.com.au
Phone: (03)98765432
Age: 55
Password: ************
Example:
Here’s a simple Python script that uses a function to validate whether the user input is an integer. The function is called twice to get the length and width of a rectangle, and then it calculates the area.
def get_integer(prompt):
while True:
try:
value = int(input(prompt))
return value
except ValueError:
print("Invalid input. Please enter a whole number.")
# Get validated inputs
length = get_integer("Enter the length of the rectangle: ")
width = get_integer("Enter the width of the rectangle: ")
# Calculate area
area = length * width
# Display result
print(f"The area of the rectangle is {area}")
Explanation:
get_integer(prompt)prompts the user and keeps asking until they enter a valid integer.int(input(prompt))attempts to convert the input to an integer.- If the input is not a valid integer, it catches the
ValueErrorand asks again. - The function is used to get both the
lengthand thewidthbefore calculating the area.