Answer to Question #97171 in Python for yousif

Question #97171
Write a program that asks the user to enter a single character and then outputs the ASCII number of that character. Please follow the same format as in the sample run.

Try it: What happens if you type in a word like paper?

Sample Run

Enter a character: %
ASCII #37

Enter a character: 8
ASCII #56
1
Expert's answer
2019-10-24T08:01:34-0400

The program can be made using the main method (chr_to_ASCII_number.py) and without it (chr_to_ASCII.py).


# chr_to_ASCII_number.py

# convert single charachter to ASCII number
def main():
    ch = input("Enter a character: ")
    print('ASCII #{0:d}'.format(ord(ch)))


if __name__ == '__main__' :
    main()


# chr_to_ASCII.py

# convert single charachter to ASCII number
ch = input("Enter a character: ")
print('ASCII #{0:d}'.format(ord(ch)))


Both programs work the same way.

Function ch = input("Enter a character: ")

 asks the user to enter a character, wait for input and return the entered char

To get formated output we use function print with format.

When printing, instead of {0:d}, the value returned function ord(ch) is substituted.

Function ord(ch) returns ASCII code of the character.

If we type in a word an error occurs.


the output of the programs:


$ python3 chr_to_ASCII.py

Enter a character: 8

ASCII #56

$ python3 chr_to_ASCII.py

Enter a character: word 

Traceback (most recent call last):

 File "chr_to_ASCII.py", line 10, in <module>

  main()

 File "chr_to_ASCII.py", line 4, in main

  print('ASCII #{0:d}'.format(ord(ch))) 

TypeError: ord() expected a character, but string of length 4 found



$ python3 chr_to_ASCII_number.py

Enter a character: %

ASCII #37

t$ python3 chr_to_ASCII_number.py

Enter a character: 8

ASCII #56

$ python3 chr_to_ASCII_number.py

Enter a character: word

ASCII #Traceback (most recent call last):

 File "chr_to_ASCII_number.py", line 3, in <module>

  print(ord(ch))

TypeError: ord() expected a character, but string of length 4 found


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS