Python print() function prints the given string or object to the standard output. The standard output is the screen or to the text stream file.
Example: Print an integer to Screen
print("Learning Python is Easy.")
i = 100
print("The value of i is: ", a)
Program output.
Learning Python is Easy. The value of i is: 100
Syntax of print() Method
The complete syntax of the print() function is:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
Method Parameters
The print() method parameters are:
- objects – It takes the objects to the printed in the screen. It can take more than one object as method argument.
- sep – If multiple objects are printed than the objects are separated by
sep. The default value ofsepis' '. - end – It is printed at the last of the output. The default value is new line character (
\n). This is the reason eachprint()statement displays the output in the new line. - file – It must be an object with
write(string)method. If not specified,sys.stdoutis used which prints output on the screen. flush – It specifies if the output stream has to be forcibly flushed. Default value isFalsewhich does not forcibly flush the stream.
Remember that sep, end, file and flush are the keyword arguments. A keyword argument is passed into method with its name.
Method Return Value
The print() method does not return any value. It returns None.
Example: Keyword arguments in print() Method
print("A", "B", "C", "D", sep = ' # ')
Program output.
A # B # C # D
Python print() Method Examples
Let’s look at few examples to understand how to use the print() method.
Example 1: Using print() with sep and end parameters
print("A", "B", "C", "D", sep = ' # ', end = ' Done \n')
Program output.
A # B # C # D Done
Example 2: Using print() with file parameter
- The given Python program tries to open the
demo.txtin writing mode. - If
demo.txtfile doesn’t exist, a new file is created and opened in writing mode. - The string object
'Hello, Python !'is printed todemo.txtfile into your computer. - Do not forget to close the file using
close()method.
sourceFile = open('demo.txt', 'w')
print('Hello, Python !', file = sourceFile)
sourceFile.close()
Program output.
Hello, Python !
Happy Learning !!
Comments