Intro to Python

9. User Input

Have you ever wondered how online websites take in and verify the usernames and passwords that you enter? Well, these websites ask the user for input and process the information that the user sends in, typically storing this information in variables.

This process used by those programs is called user input, and it is any information that is sent by the user to a computer using an input device. In almost every program, user input is utilized in some form. For example, console applications, desktop applications, databases, and website pages all use user input.

Below is an example of prompting the user for a password, taking in the user input, storing the input into a variable, and printing the password back out.

# prompting user and reading input
password = input("Enter a password: ")

# outputting user input
print("Password is " + password) 

> Enter a password:
User types in "coolCats23"
> Password is coolCats23

If you input into the same variable multiple times, only the last info is kept.

User input works for a variety of data types, including numerical values. The syntax is different for numerical values, but not significantly.

Taking in user input and storing it in variables also allows for the manipulation of input data before producing a final output value. In other words, calculations could be performed on the input data to create a different output value, similar to how a function in math produces an output f(x) from an input x. For example, we could take in a number x, add 10 to x, and then print out x.

Below is an example of prompting the user for their favorite number, taking in the user input, multiplying the number by 2, and then outputting the result.

# prompting user and reading input
favNumber = int(input("Enter your favorite number: "))

# multiplying favorite number by 2
favNumber*=2

# outputting user input
print("Favorite Number X 2 = " + str(favNumber))

> Enter your favorite number: 
User types in "50"
> Favorite Number X 2 = 100

Note: It is extremely important that the variables you are storing the inputs in are the correct variables or the ones you want. For example, if a user inputs 0.55 when a program expects an integer, it will return an integer (the input is usually rounded to the nearest one). If a user inputs the string “hello!” when the program expects an integer, it will fail entirely as the program expects an integer, and has received something which is not one.

You can play around with all the code we've used in this article on Trinket: