6 Getting User Input

Getting input is key to making an interactive program.

User input is the main way of handling this.

In Python[3] there is a function[1] called input().

Inside the () you can provide[4] a string[5] to provide a message to display to the user.

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

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[6] 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[7] to convert / parse the string into an integer[8] (int). There are other types like float[9] 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[10] 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.

Terms definitions
1. function. A named section of a computer program that performs a specific task. Functions help make code more efficient and reusable. They may take input parameters and produce output.
2. variable. A placeholder for a piece of information that can change.
3. Python. A type of programming language. It is one of many high-level, general-purpose programming languages. It was first released in 1991
4. provide. When information have been given to the user, developer, designer, tester.
5. string. A data type used to store text. Often enclosed in “” or ”