Input Validation in Python - GeeksforGeeks

Input Validation in Python

Last Updated : 22 Sep, 2026

Input validation checks whether user-provided data meets the required type, range, or format before it is processed. Python provides several approaches for validating input, including exception handling, conditional statements, and regular expressions.

Using try-except for Type Validation

The try-except block can validate whether the entered value can be converted to the required data type.

Python
while True:
    try:
        num = int(input("Enter a number: "))
        break
    except ValueError:
        print("Invalid input!")

print(num)

Output:

ex1py

Explanation:

  • int() attempts to convert the input into an integer.
  • ValueError occurs when the input cannot be converted.
  • The loop continues until a valid integer is entered

Using if Statements for Range Validation

An if statement can check whether a numeric input falls within a specified range.

Python
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:

ex-2-py

Explanation:

  • 0 <= age <= 120 checks whether the age is within the allowed range.
  • The loop continues when the value is outside the range.
  • The valid age is printed after it passes the condition.

Using Regular Expressions for Format Validation

Regular expressions can validate input that follows a specific pattern, such as an email address.

Python
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:

ex-3-py

Explanation:

  • re.fullmatch() checks the complete input against the pattern.
  • The regular expression checks the basic structure of an email address.
  • The program prints whether the entered email matches the required format.
Comment