F.E. PPS Unit 3 Practical 7 solution

Practical 7: Program to demonstrate the usage of ord() and chr() functions.

Problem Statement

Write a Python program to demonstrate the usage of ord() and chr() functions.
The program should:

  • Accept a character from the user and display its ASCII value using ord().
  • Accept an ASCII value from the user and display its corresponding character using chr().

Solution Code

				
					# Program to understand ord() and chr() functions

# Taking a character input from the user
char = input("Enter a character: ")

# Getting the ASCII value of the character
ascii_value = ord(char)

# Taking an ASCII value as input
ascii_num = int(input("Enter an ASCII value (between 0 to 127): "))

# Getting the corresponding character
character = chr(ascii_num)

# Displaying the results
print(f"ASCII value of '{char}' is: {ascii_value}")
print(f"Character corresponding to ASCII value {ascii_num} is: {character}")


				
			

Output:

  • The program takes a character input from the user and returns its ASCII value.
  • It then takes an ASCII value as input and returns the corresponding character.

Example output:

				
					Enter a character: A
Enter an ASCII value (between 0 to 127): 97
ASCII value of 'A' is: 65
Character corresponding to ASCII value 97 is: a
Process finished with exit code 0
				
			

Explanation

Below is the explanation of F.E. PPS Unit 3 Practical 7 solution where we have written Python program to demonstrate the usage of ord() and chr() functions.

  1. Taking a Character Input:
    • The input() function is used to accept a single character from the user.
  2. Using ord() Function:
    • ord(char) → Converts a character to its ASCII value.
    • Example: ord(‘A’) returns 65.
  3. Taking an ASCII Value as Input:
    • The user enters a numeric value representing an ASCII code.
  4. Using chr() Function:
    • chr(ascii_num) → Converts an ASCII value to its corresponding character.
    • Example: chr(97) returns ‘a’.
  5. Displaying the Results:
    • The program prints both conversions using formatted strings.

Key Concepts Learned

  • ord() Function
    • Converts a character to its ASCII value.
    • Example: ord(‘B’) → 66.
  • chr() Function
    • Converts an ASCII value back to its corresponding character.
    • Example: chr(100) → ‘d’.
  • ASCII Values
    • The standard ASCII table assigns numbers (0-127) to characters.
    • Uppercase letters: A-Z (65-90), Lowercase letters: a-z (97-122).
Tech Amplifier Final Logo