Python Print Variable
In this tutorial, we will learn how to use the Python print statement in various ways to output variables and strings.
Print Variable Basic Example
If you are using Python 3.* the print
statement must contain parentheses. Let's try a basic example of printing a variable.
var_1 = 'hello.'
print(var_1)
hello.
For Python 2.* and below, print
statements can be written without parentheses like this:
print var_1
You can choose whether to use parenthesis in Python 2, but in Python 3 you will get a SyntaxError
without parentheses.
Multiple Variables in One Print Statement
To print multiple variables in one print()
statement, concatenate them with , (commas) like this:
var_1 = 'hello. '
var_2 = 'goodbye.'
print(var_1, var_2)
hello. goodbye.
Print Variables Inside a String
To print variables anywhere inside a string, use Python f-strings. Formatted string literals are a new feature of Python 3 and make it much easier to add variables inside strings.
To start a new f-string, use f''
. Within the single quotation marks, you can add variables inside {}
(curly braces).
var_1 = 'a'
var_2 = 'b'
print(f'First data: {var_1} \nSecond Data: {var_2}')
First data: a
Second Data: b