As a software developer, our goal is to design and implement solutions that provide value for our users. As such, it is crucial to learn how to best receive and manage input from those users! Let’s take the first step towards developing this skill now.
The easiest way we can listen for user input with Python is by utilizing the input()
function. This function will wait for the user to type something into our console, and return whatever value was typed.
<aside>
✏️ We will get more in-depth on return values during the Functions lesson, for now just understand that we can assign input()
to a variable, and that variable will hold the value typed in by our user!
</aside>
The very first Python program you created was likely a “Hello World” script that looked something like print("Hello world!")
. Let’s take this a single step further, and greet the user by their name! First, we need to know their name. The best way to know somebody’s name is to ask them, so lets do it!
print("excuse me, what is your name?")
their_name = input()
print("thank you! Hello, " + their_name)
If you run this script, you will see that whatever is typed into the console will be stored in the their_name
variable, and is added to the end of the last print statement.
<aside>
✏️ We added the string name
to our hello message using concatenation with the +
operator. There are a few different ways to accomplish this in Python, so feel free to use a different method. My personal preference is using f-strings!
</aside>
If we look at the official documentation for the Python input function, you can see that there is an option to include a prompt within the parentheses. This will allow us to convert our request for the user’s name into a single line!
their_name = input("excuse me, what is your name? ")
print("thank you! Hello, " + their_name)
This concludes our introduction to accepting User Input from the console, try building the mini-project below for practice!