Python print() function prints the message to the screen or any other standard output device.
Syntax: print(value(s), sep= ‘ ‘, end = ‘\n’, file=file, flush=flush)
Parameters:
Returns: It returns output to the screen.
Though it is not necessary to pass arguments in the print() function, it requires an empty parenthesis at the end that tells python to execute the function rather calling it by name. Now, let’s explore the optional arguments that can be used with the print() function.
Example:
print("GeeksforGeeks \n is best for DSA Content.")
Output:
GeeksforGeeks
is best for DSA Content.
# This line will automatically add a new line before the
# next print statement
print ("GeeksForGeeks is the best platform for DSA content")
# This print() function ends with "**" as set in the end argument.
print ("GeeksForGeeks is the best platform for DSA content", end= "**")
print("Welcome to GFG")
Output:
GeeksForGeeks is the best platform for DSA content
GeeksForGeeks is the best platform for DSA content**Welcome to GFG
3>>>2>>>1>>>Start
The initial code for this would look something like below;
import time
count_seconds = 3
for i in reversed(range(count_seconds + 1)):
if i > 0:
print(i, end='>>>')
time.sleep(1)
else:
print('Start')
So, the above code adds text without a trailing newline and then sleeps for one second after each text addition. At the end of the countdown, it prints Start and terminates the line. If you run the code as it is, it waits for 3 seconds and abruptly prints the entire text at once. This is a waste of 3 seconds caused due to buffering of the text chunk as shown below:
Though buffering serves a purpose, it can result in undesired effects as shown above. To counter the same issue, the flush argument is used with the print() function. Now, set the flush argument as true and again see the results.
import time
count_seconds = 3
for i in reversed(range(count_seconds + 1)):
if i > 0:
print(i, end='>>>', flush = True)
time.sleep(1)
else:
print('Start')
Output:
b = "for"
print("Geeks", b , "Geeks")
Output:
Geeks for Geeks
import io
# declare a dummy file
dummy_file = io.StringIO()
# add message to the dummy file
print('Hello Geeks!!', file=dummy_file)
# get the value from dummy file
dummy_file.getvalue()
Output:
'Hello Geeks!!\n'
Example : Using print() function in Python
# Python 3.x program showing
# how to print data on
# a screen
# One object is passed
print("GeeksForGeeks")
x = 5
# Two objects are passed
print("x =", x)
# code for disabling the softspace feature
print('G', 'F', 'G', sep='')
# using end argument
print("Python", end='@')
print("GeeksforGeeks")
Output:
GeeksForGeeks
x = 5
GFG
Python@GeeksforGeeks