Welcome to Python Basics, my blog series of how to work with Python. In this guide I will be showing you how you can get Python to ask you for your name and then say Hello to you, by name.
In this tutorial, you will learn how to:
- Use Python’s print function.
- Use Python’s input function to get the user to enter various information.
- Use the print function in assistance with a variable.
First of all, let’s learn the print
function. This function allows you to print text onto the screen. Let’s practice it with “Hello world!”
We start with the print
function, and then we open brackets to tell print that we are going to use arguments with it. We use quotation marks to show that it is a quote for print
to display, not part of code. We then close brackets to end the line of code.
Run the code in your IDE and you should get this:
Secondly, let’s understand the input
function, which asks for user input. It can be used without a variable but a variable is recommended for it to be stored and used with other things.
Try this bit of code:
To explain this, first of all we are declaring a variable with username =
, which is the name for our variable, which stores data in the code. input
is the function to use, and declaring brackets, similar to when we used print
, is to tell the function what to say with arguments. We once again use quotation marks to show it as a quote and then enter in “What’s your name?” as a question prompt, and then we close it off again.
Run the code, and the program will ask you for a name. Type it in and press enter.
However, this code is currently useless as it does not do anything with the name, it just stores it while the program is running and then erases it when it instantly quits. This is where the print
and input
functions come in. Try this bit of code:
Let’s explain what the second line does. “Hello there,” is in quotation marks, as that is always going to be an unconditional part of this mini program. We then close off the quotation marks, but use a plus sign to add on the variable. This causes the program to say what it is programmed to say by default, and then say what you entered as input. We then close off the brackets as usual to end off the line of code.
Run the program and you will get something like this:
Congratulations! You have made your first Python program that interacts in some way with the user. Make sure to follow this blog as I will be posting more of this Python basics series in the coming weeks.
Thank you for reading!