Python print() is a built-in function that prints the given object to the standard output console or a device. Unlike other programming languages like C, in Python print is a function, not a statement.

python print() function

Python print() Syntax

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Where,

  • *objects (required) – the objects that are to be printed. It can be multiple comma-separated objects or a single object.
  • sep – objects in output are separated by sep.
  • end – printed at last.
  • file – must be an object with a write(string) method; if it is not present or None, sys.stdout will be used.
  • flush – decides whether to flush the stream or not. If yes, the stream is forcibly flushed. Default value is False.

Python print() Example

>>> print('a','b')
a b
>>> print('a','b',sep='-')
a-b

Notice that when sep is used, the output is separated by whatever value we assign sep to.

sep, end, file and flush are keyword arguments, so their direct values can’t be used as arguments inside print() function. Instead, sep='some value' must be used.

>>> a = 7
>>> print('a =',a)
a = 7
>>> print('a =','b =',a)
a = b = 7

>>> print('Python Programming')
Python Programming

Python print() and For Loop

>>> for i in range(4):
      print(i, end=" : ")

0 : 1 : 2 : 3 :

As you can see in above example, the value of keyword argument end is appended at the end of every object in output screen.

Python print() and File Parameter

With print() function, the objects can also be printed in a file stream.

The print() function sends the object to the standard output stream which is sys.stdout by default. By redefining the keyword parameter “file” we can send the object or output to a different stream like a file.

Recommended reading: Python File Stream IO

Here is an example.

>>> fp = open("file.txt","w")
>>> print("Append me to the file", file=fp)
>>> fp.close()

Here we can see that no output is prompted on output console because the object has been printed to file stream file.txt. If we check the content of file.txt, we will see the object printed or appended in that file.

Once the operation is done, the file is closed using fp.close() function.