7.1 Code Practice: Question 2
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.

Your program should accept one character only for each ask. Test your code by entering a word, such as paper. What happens? Review any error messages received in CodeSkulptor.

Sample Run 1
Enter a character: %
ASCII #37
Sample Run 2
Enter a character: 8
ASCII #56

Respuesta :

Answer:

I used CodeSkulptor to run the program as asked in the question. The code is given below in the explanation section. However, to run multiple time sample runs, this program asks the user to enter the number of times he wants to execute the sample run. Then for loop is used that will run until entering limit exceeded or enter a string rather than a character. if you want to run and execute this program user "codeSkulptor", search on internet, you can easily find its link. Copy the below given code and run in it......

Explanation:

# CodeSkulptor runs Python programs in your browser.

# Click the upper left button to run this simple demo.

# CodeSkulptor runs in Chrome 18+, Firefox 11+, and Safari 6+.

# Some features may work in other browsers, but do not expect

# full functionality.  It does NOT run in Internet Explorer.

import simplegui

# asked user to enter integer number, how many times to execute the smple run

sampleRun=raw_input("How many time you want a sample run : ")#taking input from user  

for x in range(0, int(sampleRun), 1):    # running for loop, it will get terminated as limit get exceeded or user enter the string

   print "Sample run" + str(x)

   character = raw_input("Enter a character :  ")# user enter the character  

   

   print"ASCII ", ord(character)  

   print""#line break between runs

# end of program

As you enter the string instead of entering a character, CodeSkulptor through an error. for example, if you enter "Ali" instead of entering a character. The following error will get displayed

"Line 17: TypeError: ord() expected a character, but string of length 3 found"

because the ord() function expected and get character always not a string. ord() is a Python built-in function that converts the character into equivalent ASCII value and it always expecting the character length equal to 1.