Menu

Input Validation

Pattern Checks

A pattern check confirms that input follows an allowed format or contains only permitted types of character. It does not compare the input with one exact string; it tests the kind of characters and the layout the input is allowed to use.

Python's string methods make character-type pattern checks simple. isalpha() returns True only when every character is a letter, isdigit() only when every character is a digit, and isalnum() when every character is a letter or a digit. Each method returns a Boolean, so you can use the call directly in a condition.

MethodTrue only when every character is...AcceptsRejects
isalpha()a letterMapleMaple1, Maple Leaf
isdigit()a digit482148 21, 48A
isalnum()a letter or a digitCedar9Cedar 9, Cedar-9

For example, a competition entry code may contain only letters and digits. entry_code.isalnum() accepts Blue7 but rejects Blue 7, because the space is neither a letter nor a digit. Spaces and punctuation cause all three methods to return False.

Comparing entry_code == "Blue7" would accept only that one exact code, which is why a pattern check is different: it allows any code that matches the permitted character types.

entry_code = input("Enter your competition code: ")
if entry_code.isalnum():
    print("Code accepted")
else:
    print("Code must use only letters and digits")

Output when the user types Blue7:

Enter your competition code: Blue7
Code accepted

Practise this