Data types and variables
Operators
Modules and Packages
Conversion Programs
More Code Examples
Cheat Sheet

Python Code Example: ASCII Value of Character

This Python script takes a single character input from the user, computes its ASCII value, and then displays both the character and its corresponding ASCII value.

Code Example

character = input("Please enter character: ")

asciiValue = ord(character)
originalValue = chr(asciiValue)

print("ASCII value of the character " + repr(originalValue)
      + " is: " + repr(asciiValue))

Output

Please enter character: c
ASCII value of the character 'c' is: 99

Code Explanation

Character Input

character = input("Please enter character: ")
  • Purpose: Prompts the user to enter a single character.
  • input(...): Displays a message asking for user input and reads the entered character.

ASCII Value Calculation

asciiValue = ord(character)
  • Purpose: Converts the input character to its corresponding ASCII value.
  • ord(character): Returns the ASCII value of the provided character.

Character Retrieval

originalValue = chr(asciiValue)
  • Purpose: Converts the ASCII value back to the original character.
  • chr(asciiValue): Returns the character represented by the provided ASCII value.

Printing the Results

print("ASCII value of the character " + repr(originalValue)
      + " is: " + repr(asciiValue))
  • repr(originalValue): Converts the character to a string for printing.
  • repr(asciiValue): Converts the ASCII value to a string for printing.
  • Message: Outputs the original character and its ASCII value.