close
close

Ask a user for input

Ask a user for input

Let’s look at a built-in Python function that: get input from a user while our Python program is running.

Asking for user input

Python has a built-in input function we can use to ask a user of our program to enter some text:

>>> color = input("Favorite color:")
Favorite color:▯

Our Python REPL is now hanging and waiting for us (the user) to enter some text. Let’s type purple:

>>> color = input("Favorite color:")
Favorite color:purple▯

After the user types the text he wants to enter, he can press the Enter key to lock the value.

>>> color = input("Favorite color:")
Favorite color:purple
>>>

Now the color variable contains the string purple:

Customize the prompt text

Please note that the input function will print any string we give it, so we can make our input prompt as friendly as we want. For example, here we are asking a question and we have put a space at the end of our prompt:

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

Prompt users with built-in Python function input function

To get input from a user while your program is running, you can use the built-in Python function input function to set up your program break And ask the user for input.

Learn the 5 Keys to Python Success 🔑

Sign up for my free 5 day email course and learn essential concepts often overlooked in introductory courses:
iterables, available on request, hands, duck typesAnd namespaces.