User Input, a Closer Look

Getting Data From the User

What function allows our program to retrieve data from the user?

The built-in function, input, reads in a line of input from the user. Input returns this as a value in your program. What type is the value that is returned by input?

Input always returns a string.

Input Always Gives Back a String

Input Example 1

animal = "aardvark"
adjective = input("Give me an adjective that starts with an 'a' please!\n> ")
print(adjective + " " + animal)

What will this program output to the screen if the user types in 'apprehensive'?

apprehensive aardvark

Input Example 2

number_of_cheers = input("How many cheers?\n> ")
print("hip " * number_of_cheers + "hooray")

What will this program output to the screen if the user types in 20?

We get a run-time error! (TypeError: can't multiply sequence by non-int of type 'str')

Fixing Input Example 2

How would we fix this program?

number_of_cheers = input("How many cheers?\n> ")
print("hip " * number_of_cheers + "hooray")

We can convert the string that we get from input into an int by using the int function…

number_of_cheers = input("How many cheers?\n> ")
print("hip " * int(number_of_cheers) + "hooray")

Another Way to Fix Example 2

Using function composition, we could also call int on the return value of input:

number_of_cheers = int(input("How many cheers?\n> "))
print("hip " * number_of_cheers + "hooray")

Definitions

Definitions Continued

Finishing up the Review…

Let's take a look at that handout again.