PythonMastery
Python programs · Strings · beginner

Check if a sentence is a pangram in Python

Check whether a sentence uses every letter from a to z, and print the letters it is missing, with a set difference or a simple loop.

A pangram is a sentence that uses every letter of the alphabet at least once, like "The quick brown fox jumps over the lazy dog". If you take away the letters the sentence uses from the 26 letters a to z, whatever is left is missing.

The program

python
import string

def missing_letters(sentence):
    used = set(sentence.lower())
    return sorted(set(string.ascii_lowercase) - used)

sentences = [
    "The quick brown fox jumps over the lazy dog",
    "Pack my box with five dozen liquor jugs",
    "Grace Hopper wrote the first compiler",
]

for sentence in sentences:
    missing = missing_letters(sentence)
    if missing:
        print(f"{sentence!r}: not a pangram, missing {''.join(missing)}")
    else:
        print(f"{sentence!r}: pangram")
output
'The quick brown fox jumps over the lazy dog': pangram
'Pack my box with five dozen liquor jugs': pangram
'Grace Hopper wrote the first compiler': not a pangram, missing bdjknquvxyz

How it works

Another way: a loop

Without sets, check each letter of the alphabet with in:

python
sentence = "Grace Hopper wrote the first compiler"
text = sentence.lower()

missing = ""
for letter in "abcdefghijklmnopqrstuvwxyz":
    if letter not in text:
        missing += letter

print("Missing:", missing)
print("Pangram" if missing == "" else "Not a pangram")
output
Missing: bdjknquvxyz
Not a pangram

If you only need a yes or no answer, set(string.ascii_lowercase) <= set(sentence.lower()) is True for a pangram. <= between sets means "is a subset of". See subset and superset for more about it.

Learn the idea: Working with Strings, Sets: Unordered, Unique, Lightning Fast