Check whether a character is an alphabet or not in Python
Understanding Alphabets
An alphabet is any letter from A to Z (both uppercase and lowercase). Any other character is not considered an alphabet.
We will explore three different methods to check whether a character is an alphabet or not in Python.
Method 1: Using if-else
This method checks if the character falls within the range of alphabets.
ch = input("Enter a character: ")
if ('a' <= ch <= 'z') or ('A' <= ch <= 'Z'):
print(f"{ch} is an alphabet")
else:
print(f"{ch} is not an alphabet")
Output: A is an alphabet
Method 2: Using ASCII Values
This method checks the ASCII values of the character.
ch = input("Enter a character: ")
if (65 <= ord(ch) <= 90) or (97 <= ord(ch) <= 122):
print(f"{ch} is an alphabet")
else:
print(f"{ch} is not an alphabet")
Output: 1 is not an alphabet
Method 3: Using a Function
This method defines a function to check if a character is an alphabet.
def is_alphabet(ch):
return ('a' <= ch <= 'z') or ('A' <= ch <= 'Z')
def check_alphabet(ch):
if is_alphabet(ch):
print(f"{ch} is an alphabet")
else:
print(f"{ch} is not an alphabet")
ch = input("Enter a character: ")
check_alphabet(ch)
Output: z is an alphabet