In Python, we can print multiple variables easily with the print() function. Just pass each variable to print() separated by commas to print multiple variables on one line.
x = 0
y = 1
z = 2
print(x,y,z)
#Output:
0 1 2
In Python, when writing programs, being able to check the value of certain variables can be useful.
Many times, when we want to check the value of a variable, printing it to the console is the easiest way.
We can print one variable, or print multiple variables, to the console using print().
To print multiple variables in Python, you just need to call print() and separate the variables by commas.
Below is a simple example of how to print multiple more than one variable to the console in a Python program.
x = 0
y = 1
z = 2
print(x,y,z)
#Output:
0 1 2
The rest of this article goes into some other cases where you can output the value of multiple variables to the console.
Printing Multiple Variables to the Console with f-strings in Python
Python f-strings, or formatted string literals, were introduced in Python 3.6. f-strings make it incredibly easy to insert variables into other strings.
We can use f-strings to be able to easily print multiple variables to the console with Python.
Below is a simple example of how to use f-strings with print() to output multiple variables in Python.
fruit = "apple"
num = 3
print(f"We have {num} {fruit}s.")
#Output:
We have 3 fruits
Using format() to Print Multiple Variables to the Console in Python
You can also use the string format() function to print more than one variable to the console.
With the format() function, we just need to put curly brackets in a string we want to insert variables. The downside of using format() is that we need to be precise with the order of the variables we pass.
Below is a simple example of how to use format() with print() to print more than one variable in Python.
fruit = "apple"
num = 3
print("We have {} {}s.".format(num, fruit))
#Output:
We have 3 fruits
Printing More than One Variable to Console with Concatenation
The final way to print more than one variable to the console in Python is with concatenation. If you have all string variables, this is very straightforward.
Below is an example in Python of using string concatenation to output more than one variable to the console in Python.
fruit = "apple"
print("We have " + fruit + "s.")
#Output:
We have apples.
If you have numeric variables, then you need to convert those variables to strings to use with concatenation.
Below is an example in Python of using concatenation to print multiple numeric variables in Python.
fruit = "apple"
num = 3
print("We have " + str(num) + " " + fruit + "s.")
#Output:
We have 3 fruits
Hopefully this article has been useful for you to understand how to print multiple variables using Python.