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.
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
Where,
sys.stdout
will be used.False
.>>> 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
>>> 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.
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.
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.