We'll learn how to prompt the user to type text into our program, and learn how to convert that input into the type that we want.

Getting user input

Computer programs are, at their essence, a way for us to process data. So, what we've learnt so far isn't too useful, as we don't really have any data to process. Let's change that, by accepting user input while our program is running.

The function to take note of is input(). Like print(), input is a function, and it allows the user to type in text while the program is running. Then, when the user presses Enter, input will return the stuff the user typed in. Here's an example:

variable = input()
# type some text and press Enter.
# say we typed [hello] without the [ square brackets ]:
print(variable)
# hello

print(type(variable))
# <class 'str'>

Don't worry about the last two lines and the type function there, or what it says. All we need to know is that variable is a string - that input() will always return a string value, no matter what you type in.

Function returns

You might be a little confused - what is variable = input()? Why are we assigning a variable to a function?

So far, we've only really covered sending stuff into a function. We can send parameters to print(), for instance. But so far, we haven't really covered the function sending stuff out. When it does that, like input() does, we can capture it and store it in a variable, the same way that we can store the number 5 or the string "hi" in a variable.

input() - a function with both input and output

We can also pass a parameter into input(), a string which we want it to print before it asks for our input.

<aside> ❗ Stuff in the [square brackets] is what I have typed in.

</aside>

variable = input("prompt>")
# prompt>[hello]
print(variable)
# hello

Notice how the input() function can both ask us to send in parameters - "prompt>" - and also output parameters.