HANDLING USER INPUT
Python enables you to read user input from the command line via the input() function or the raw_input() function. Typically, you assign user input to a variable, which will contain all characters that users enter from the keyboard. User input terminates when users press the <return> key (which is included with the input characters). Listing 1.11 displays the content of user_input1.py that prompts users for their name and then uses interpolation to display a response.
LISTING 1.11: user_input1.py
userInput = input("Enter your name: ")
print ("Hello %s, my name is Python" % userInput)
The output of Listing 1.11 is here (assume that the user entered the word Dave):
Hello Dave, my name is Python
The print() statement in Listing 1.11 uses string interpolation via %s, which substitutes the value of the variable after the % symbol. This functionality is obviously useful when you want to specify something that is determined at run-time.
User input can cause exceptions (depending on the operations that your code performs), so it is important to include exception-handling code.
Listing 1.12 displays the content of user_input2.py that prompts users for a string and attempts to convert the string to a number in a try/except block.
LISTING 1.12: user_input2.py
userInput = input("Enter something: ")
try:
x = 0 + eval(userInput)
print('you entered the number:',userInput)
except:
print(userInput,'is a string')
Listing 1.12 adds the number 0 to the result of converting a user’s input to a number. If the conversion was successful, a message with the user’s input is displayed. If the conversion failed, the except code block consists of a print() statement that displays a message.
NOTE This code sample uses the eval() function, which should be avoided so that your code does not evaluate arbitrary (and possibly destructive) commands.
Listing 1.13 displays the content of user_input3.py that prompts users for two numbers and attempts to compute their sum in a pair of try/except blocks.
LISTING 1.13: user_input3.py
sum = 0
msg = 'Enter a number:'
val1 = input(msg)
try:
sum = sum + eval(val1)
except:
print(val1,'is a string')
msg = 'Enter a number:'
val2 = input(msg)
try:
sum = sum + eval(val2)
except:
print(val2,'is a string')
print('The sum of',val1,'and',val2,'is',sum)
Listing 1.13 contains two try blocks, each of which is followed by an except statement. The first try block attempts to add the first user-supplied number to the variable sum, and the second try block attempts to add the second user-supplied number to the previously entered number. An error message occurs if either input string is not a valid number; if both are valid numbers, a message is displayed containing the input numbers and their sum. Be sure to read the caveat regarding the eval() function that is mentioned earlier in this chapter.