Skip to main content

Python: 6 Getting User Input

Getting input is key to making an interactive program.

User input is the main way of handling this.

In Python there is a function called input().

Inside the () you can provide a string to provide a message to display to the user.

The input function will return a value which can be assigned = to a variable

first_name = input("What is your name? ")

Note that there is a space at the end of the string inside the input function. Without this the input would start right next to the end of the text in the string.

You can then print out your responses as shown below

The input function reads in data as a string.

Enter the code below and see what happens

Enter any number of icecreams to purchase.

The example above enters 7 a valid answer but the input method saves it as the string "7" we can't multiply strings.

We need to convert / parse the string into an integer (int). There are other types like float for decimal values.

To do that we put the variable we want to convert inside another function called int().

Inside the () we put the name of the variable. In this case num_purchased

We can also combine those first two lines together.

But what happens if we enter the word five instead of five?

The program has crashed with an error "invalid literal for int()..." this means that it couldn't convert the contents of the string "five" to a number.

The code below shows how to prevent these types of errors. The example includes the use of a while loop which will be covered later.

This code will check if the num_purchased congains digits. we use the not keyword do get all the options that are not digits. If there is not a digit entered e.g. "five" it will ask the user to reenter an input until a valid input is entered.

More work on while loops will be given in a later tutorial.