Input Validation in Python
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:
num = int(input("Enter a number: "))
break
except ValueError:
print("Invalid input!")
print(num)
Output
Enter a number: 5
5
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)
Output
Enter age: 144
Enter a valid age inside the range (0-120)
Enter age: 23
23
Explanation: In this case, the function will repeatedly prompt the user until they enter a valid age.
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)
Output
Enter email: aryan.tanwar
Invalid email format
Enter email: aryan.tanwar@geeksforgeeks.org
aryan.tanwar@geeksforgeeks.org
Explanation: regular expression pattern ensures that the input matches the typical structure of an email address.
Related Articles: