In this article, we will learn about python program to check character is uppercase or not.
Getting Started
Our task to write a python program that checks if a character, entered by user, is in uppercase or not. For example,
If user enters M, it returns True.
If user enters d, it returns False.
If user enters 3, it returns False.
We can do so in many ways –
Simple Comparison
We can simply compare entered character if it lies in the range of `A` to `Z` or not. For example,
def isUpperCharacter(ch): if len(ch) != 1 : return None else : return (ch >= 'A' and ch <= 'Z') ch = input('Enter a character') print(isUpperCharacter(ch))
Output:
Enter a character W True
In isUpperCharacter method,
- At first, we compared if length of entered character is 1 or not. If not 1, it means we have entered more than 1 character. So, it returns None.
- In else condition, we have compared if entered character lies between A and Z or not.
- Depending upon else condition, isUpperCharacter returns True or False.
Using ASCII Value
We can use ASCII value of characters and check if entered value lies in that range or not. For example,
def isUpperCharacter(ch): if len(ch) != 1 : return None else : return (ord(ch) >= 65 and ord(ch) <= 90) ch = input('Enter a character') print(isUpperCharacter(ch))
Output:
Enter a character K True
In above program,
- 65 is ASCII value of Capital letter A. 90 is ASCII value of Capital letter Z.
- ord() function returns ASCII value of given character.
- Entered value is in uppercase if it lies between 65 and 90. Otherwise, it’s not.
Using built-in method – isupper()
We can easily use built-in method – isupper() in our python program to check if entered character is in uppercase or not. For example,
def isUpperCharacter(ch): if len(ch) != 1 : return None else : return ch.isupper() ch = input('Enter a character') print(isUpperCharacter(ch))
Output:
Enter a character K True
In above program,
- isupper() method checks if character is in uppercase or not. If yes, it returns True. Otherwise, it returns False.
Learn more about our python program at – https://tutorialwing.com/python-tutorial/