Skip to content

Print Statements

Python's print() function prints output to the Python REPL. The general format of the print() function is:

print(expression)

Where `expression is the value, variable, string or object to be printed.

Printing Strings

In order to print a string, the following syntax is used. Note how the word string is enclosed quotes ' ' and surrounded by parenthesis ( ):

In [1]:
>>> print('string')

string

Any character that can be part of a string can be printed. This includes printing spaces and punctuation.
In [2]:
>>> print('A complex string with spaces, and punctuation!?!')

A complex string with spaces, and punctuation!?!

Printing Variables

In order to print a variable, the following syntax is used. Before a variable is printed, the variable needs to be assigned a value. Note that the variable a was not surrounded by quotes.

In [3]:
>>> a = 5
>>> print(a)

5

In the example below, the variable a is assigned the value 5. Then the value assigned to a is printed. Note how the output is different when quotes ' ' enclose 'a' compared to when quotes ' ' don't enclose a.
In [4]:
>>> a = 5
>>> print(a)
>>> print('a')

5
a

Printing Expressions

Expressions, such as mathematical opperations like 2+2 can be included in print() statments. The results of the expression will be printed out.

In [5]:
>>> print(2+2)

4

Line Endings

The print() function as an optional second input argument which controls line endings. By default, the print() function will print each print line on a seperate line.

In [6]:
>>> print('line 1')
>>> print('line 2')

line 1
line 2

By supplying an optional second input argument end=, multiple print lines will output on the same line. If end = ' ', instead of a new line for each print output, the following print output will appear on the same line separated by a space.
In [7]:
>>> print('line 1', end=' ')
>>> print('line 2', end=' ')

line 1 line 2