Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Input

Without thinking about the process of programming itself, take a second to think about the programs you use. These can be mobile applications, websites, or other applications/appliances. Of the normal programs you use, how many of them only output data? How many use an input of sorts? How many require you to press a button or enter a value into an input, or simply require you to input information?

Many programs we use on a day-to-day basis require us, the user, to input some information. Some applications do only give us data, but in order to update that data, we often have to input something. For example, take a simple weather application. In order to get the weather of the current location, either the application has to request the user to enter the location or it will use the Location Services behind the scenes. If the location is incorrect, the user may have to go in and input the correct location. This an example of using inputs, the main focus of this section.

In order to get the user to input information, we must use the input function.

The input function requires us to use parentheses after the word, with some information inside of the parentheses. The information we place inside of the parentheses is intended to output some instruction for the user. For example, input("Enter your name: ") will print out the text Enter your name: . We can then store this information into a variable, allowing us to use it later.

This would look like the following code block:

name = input("Enter your name: ")
print("Ah, your name is:", name)

The input function will give us the information we entered in as a string. If we want to convert the entered information into a different type, then we’ll have to cast the value into another type. We’ll look at that when we cover the casting section.

Unlike the print function, when we place values within the parentheses of the input function, we cannot use a comma to separate values. For example, input("Enter your name", "here") won’t work. This is because input can only take in a single value at a time. If we’d like to print out multiple values in the prompt, we can either make use of string concatenation and concatenate the information together, or use a formatted-string. We’ll look at Formatted Strings in the Strings chapter, but the string concatenation method follows: input("Enter your name " + " here: ").

To read more about casting and converting our inputted value into another type, go on over to the casting section.