The `print()` Function
In the previous lesson, we saw how to create variables in python. We learned how to point/reference values using name(the variables).
In this lesson, we will learn how to show/display these values or the variable that contain them. We are going to the discovery of the Python function called print()
. We have not seen what functions are yet, but understand this as a keyword that the Python Interpreter knows as a special keyword, and the only thing it does is to give the order to show something on the screen.
The print()
function is used to display output in Python. It helps us see what’s happening in our code by printing values to the screen. Let's see how to use it:
Printing plain text
print("Hello, World!")
print('Hello, World 2')
Output:
Hello, World!
Hello, World 2
Note how I used single our double quotes to put around the plain text. That's how we tell Python that we are dealing with only plain text.
Printing Variables
We can print variables instead of hardcoded text. Since, variables point to some value(content), we can also display them.
name = "Mohammed"
age = 25
print(name) # Mohammed
print(age) # 25
Printing Multiple Items
We can print multiple values by separating them with commas. Here you can see that we are mixing plain text portions with variable., information of different nature.
name = "Alice"
age = 25
print("My name is", name, "and I am", age, "years old.")
Output:
My name is Alice and I am 25 years old.
Using String Concatenation (+
)
We can combine strings using the +
operator.
first_name = "John"
last_name = "Doe"
print("My full name is " + first_name + " " + last_name)
Using f-strings
f-strings
allow us to insert variables directly into a string. We will re-visit this trick later on.
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
Escape Characters
Escape characters allow us to improve the way the displayed content shows.
\n
- New line\t
- Tab space\'
- Single quote\"
- Double quote
We use single and double quotes to display plain text. What happens we we want the displayed plain text to have quotes? Like Hello, I am an 'artist';
print("Hello\nWorld!") # New line
print("Hello\tWorld!") # Tab space
print("Hello, I am \'artist\' ") # Quotes in text
Exercise: Try It Yourself!
- Print
"Python is fun!"
usingprint()
. - Print your name using a variable.
- Print
"I love programming"
on two lines using\n
. - Print
"Python"
and"Programming"
with a tab space between them.