Find the ASCII value of a character in Python
Understanding ASCII Values
ASCII (American Standard Code for Information Interchange) assigns numerical values to characters. For example, 'A' has an ASCII value of 65.
We will explore three different methods to find the ASCII value of a character in Python.
Method 1: Using ord() Function
This method prints the ASCII value of a character using the built-in ord() function.
char = input("Enter a character: ") print("ASCII value of", char, "is", ord(char))
Output: ASCII value of A is 65
Method 2: Using a Function
This method uses a function to return the ASCII value of a character.
def get_ascii_value(ch): return ord(ch) char = input("Enter a character: ") print("ASCII value of", char, "is", get_ascii_value(char))
Output: ASCII value of z is 122
Method 3: Using Dictionary Mapping
This method stores ASCII values in a dictionary for quick lookup.
ascii_dict = {chr(i): i for i in range(128)} char = input("Enter a character: ") print("ASCII value of", char, "is", ascii_dict.get(char, "Not a valid ASCII character"))
Output: ASCII value of B is 66