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
Comments
Leave a comment