Computer >> Computer tutorials >  >> Programming >> Python

Python program to check if the string is pangram


In this tutorial, we are going to write a program that checks whether a string is a pangram or not. Let's start the tutorial by talking about the pangram.

What is pangram?

If a string contains all the alphabets whether small or caps then, the string is called panagram.

We can achieve the goal in different ways. Let's see two of them in this tutorial.

1.General

Try to write the program using the following steps.

Algorithm

1. Import the string module.
2. Initialize a variable with ascii_lowercase string. string.ascii_lowercase Contains all the
alphabets as a string.
3. Initialize the string which we have to check for pangram.
4. Define a function called is_anagram(string, alphabets).
   4.1. Loop over the alphabets.
      4.1.1. If the character from alphabets is not in the string.
         4.1.1.1. Return False
   4.2. Return True
5. Print pangram if the returned value is true else print not pangram.

Example

## importing string module
import string
## function to check for the panagram
def is_panagram(string, alphabets):
   ## looping over the alphabets
   for char in alphabets:
      ## if char is not present in string
      if char not in string.lower():
         ## returning false
         return False
   return True
## initializing alphabets variable
alphabets = string.ascii_lowercase
## initializing strings
string_one = "The Quick Brown Fox Jumps Over The Lazy Dog"
string_two = "TutorialsPoint TutorialsPoint"
print("Panagram") if is_panagram(string_one, alphabets) else print("Not Panagram")
print("Panagram") if is_panagram(string_two, alphabets) else print("Not Panagram")

Output

If you run the above program, you will get the following results.

Panagram
Not Panagram

2. Using Sets

Let's see how to get the same results using sets data structure. See the steps below to get an idea.

Algorithm

1. Import the string module.
2. Initialize a variable with ascii_lowercase string. string.ascii_lowercase contains all the alphabets as a string.
3. Initialize the string which we have to check for pangram.
4. Convert both alphabets and string(lower) to sets.
5. Print pangram if string set is greater than or equal to alphabets set else print not pangram.

Let's write the code.

Example

## importing string module
import string
## initializing alphabets variable
alphabets = string.ascii_lowercase
## initializing strings
string_one = "The Quick Brown Fox Jumps Over The Lazy Dog"
string_two = "TutorialsPoint TutorialsPoint"
print("Panagram") if set(string_one.lower()) >= set(alphabets) else print("Not Pana gram")
print("Panagram") if set(string_two.lower()) >= set(alphabets) else print("Not Pana gram")

Output

If you run the above program, you will get the following results.

Panagram
Not Panagram

Conclusion

If you have any doubts regarding the tutorial, please do mention them in the comment section.