fbpx

Input function

What's your favorite color?

Someone asking another person what their favorite color is

In the real world, we verbally ask this question.

In Python, we'd utilize an input function to ask the question.

The input function enables us to ask the user for a value.

Variables explained

After asking someone for their favorite color, we'd remember their response mentally.

In Python, we need to remember this response with a variable.

Variables are utilized to remember values for later use in a program.

This is commonly used with input functions to save the values that users input for later use in the program.

How to code an input function

Let's write an input function asking the user for their favorite color. Then, we'll utilize a variable to remember it and print it in the output.

Let's check out this template for input functions.

input(question)

Since we're asking the user for their favorite color, we'll make our question ask this.

input("What is your favorite color?")

If we were to run this single line of code, the user's response would not be stored. We wouldn't be able to reference it later in the program.

Why? Because we haven't declared a variable to remember the user's input.

Declaring variables to remember

Let's declare a variable for the input function that we have. We'll call it favorite_color...

favorite_color = input("What's your favorite color?")

Now, whatever the user inputs will be saved to the value of favorite_color.

You might be asking, why is it "favorite_color" and not "favorite color" or "Favorite Color"?

Because...

In Python, you must declare your variables without spaces and lowercased. Any spaces should be depicted with an underscore.

Although we're remembering the value of the user's favorite color from the input into favorite_color, we're not doing anything meaningful with that variable yet.

Let's test that Python has actually remembered the value of favorite_color with a print function!

favorite_color = input("What's your favorite color?")
print(favorite_color)

Essentially, what we're doing here is printing the value of whatever the user enters in the input in the output.

Type the above code in your new Trinket file. It should look like so:

Now, press the "Run" button. You should get the following output, depicted in the slideshow below:

  • User is asked for their favorite color.

Notice how after we press enter in the input, the favorite_color variable's value successfully appears in the output!


Input function – Practice!