Editor

Python Program to Check if a String Is a Pangram

Beginner · Strings

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". This program checks each letter from a to z and lists any that are missing.

Program

pangram.py
import string
text = "The quick brown fox jumps over the lazy dog" # or: text = input("Enter a sentence: ")
lower_text = text.lower()
missing = []
for letter in string.ascii_lowercase: # "abcdefghijklmnopqrstuvwxyz"
if letter not in lower_text:
missing.append(letter)
print("Sentence:", text)
if len(missing) == 0:
print("It is a pangram")
else:
print("It is not a pangram. Missing letters:", missing)
Output
Sentence: The quick brown fox jumps over the lazy dog
It is a pangram

How it works

  1. string.ascii_lowercase is the string of the 26 small letters, from a to z.
  2. The sentence is lower-cased once, so capital letters count as well.
  3. Every letter that does not appear in the sentence is added to missing.
  4. If no letters are missing, the sentence is a pangram; otherwise the program shows which letters it lacks.

Other ways to write it

Using sets

Using sets
import string
alphabet = set(string.ascii_lowercase)
sentences = [
"The quick brown fox jumps over the lazy dog",
"Hello world",
"Pack my box with five dozen liquor jugs",
]
for s in sentences:
letters = set(s.lower())
if alphabet <= letters:
print("Pangram:", s)
else:
print("Not a pangram:", s, "| missing:", "".join(sorted(alphabet - letters)))
Output
Pangram: The quick brown fox jumps over the lazy dog
Not a pangram: Hello world | missing: abcfgijkmnpqstuvxyz
Pangram: Pack my box with five dozen liquor jugs

alphabet <= letters asks whether every letter of the alphabet is in the sentence. alphabet - letters is the set of missing letters, sorted so they print in order.

Using all()

Using all()
def is_pangram(sentence):
lower = sentence.lower()
return all(letter in lower for letter in "abcdefghijklmnopqrstuvwxyz")
for s in ["Sphinx of black quartz, judge my vow", "Python is fun"]:
if is_pangram(s):
print("Pangram:", s)
else:
print("Not a pangram:", s)
Output
Pangram: Sphinx of black quartz, judge my vow
Not a pangram: Python is fun

all() is True only when the check passes for every letter, and it stops as soon as one letter is missing.

Try it yourself

Change the program to also print how many different letters the sentence uses.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises