Sign in
Log inSign up

Python program to check if a given character is alphabet, digit, or special character

Kartik Nagila
·Jul 28, 2021·

2 min read

In this article, we will make a function to check if a given character is an alphabet, digit, or other special character using two methods.

Method 1: Using elif statement

def check():
        char = input('enter your character : ')
        if((char >= 'A' and char <= 'Z') or (char >= 'a' and char <= 'z')):
                print("The Given Character ", char, "is an Alphabet")
        elif(char >= '0' and char <= '9'):
                print("The Given Character ", char, "is a Digit")
        else:
                print("The Given Character ", char, "is a Special Character")
check()

Here we have taken input from the user and check the input character using elif statement. In the first condition, we checked if the character lies between the capital A to Z or small a to z, if true the character is an Alphabet. Secondly, we checked if the character lies between the numerical 0-9, if true the character is a Digit. Else the character will be a special character.

Method 2: Using isalpha() and isdigit() functions

def check():
        char = input('enter your character : ')
        if (char.isalpha()):
                print("The Given Character ", char, "is an Alphabet")
        elif (char.isdigit()):
                print("The Given Character ", char, "is a Digit")
        else:
                print("The Given Character ", char, "is a Special Character")
check()

Using the isalpha function we can easily check if the char is an alphabet or not, and with the isdigit if the character was digit the function will return true and the condition will be passed.

image.png