Skip to main content

Print function with different examples in detail

Print statement in python is not reserved word nor a statement. Print is built in function call which run as expression statement.

The interactive session automatically prints the results of expressions you type, you don’t usually need to
say “print” explicitly at this prompt:

>>>ethosspace = 'Testing Services'
>>>ethosspace  
' Testing Services '

So print function used in files not on interactive prompt.

Syntax
print([object, …][, sep=’ ‘][, end=’\n’][, file=sys.stdout])

print(object(s), sep=separator, end=end, file=file, flush=flush)

Items in square brackets are optional and may be omitted in a given call, and values after = give argument defaults.
In English, this built-in function prints the textual representation of one or more objects separated by the string sep and followed by the string end to the stream file.

SEP is a string inserted between each object’s text, which defaults to a single space if not passed; passing an empty string suppresses separators altogether.

END is a string added at the end of the printed text, which defaults to a \n newline character if not passed. Passing an empty string avoids dropping down to the next output line.

FILE specifies the file, standard stream, or other file-like object to which the text will be sent; it defaults to the sys.stdout standard output stream if not passed.

Here are the real time example of print function.

print function with no parameter print the empty line

>>>print()

To print blank line no need to pass any parameter by default print without any parameter prints blank line.


>>> a=9
 >>> b='Testing'
 >>> c=['Prog']
 >>> print(a,b,c)
         9 Testing ['Prog']

So while printing 3 objects print function added empty space between those three objects. So in place of empty space if we want different separator then we can use below syntax.

 >>> print(a,b,c,sep=' => ')
          9 => Testing => ['Prog']

Output is now separated with separator => which we provided.


By default, print adds an end-of-line character to terminate the output line.

>>>print ('ethosspace'); print('leading software testing provider')
        ethosspace
        leading software testing provider

So if we don’t need new line then we will use end parameter here

>>>print (‘ethosspace’,end=”); print(‘ leading software testing provider’)

ethosspace leading software testing provider

Example of variable, %d and % in print statement. Use of variable in between sentence in print statement.

>>>x=5
>>>y=8
>>>z=2 * (x+y)
>>>print('A rectangle %d by %d has a perimeter of %d units.'%(x,y,z))
A rectangle 5 by 8 has a perimeter of 26 units.

Use online free python compiler to run program from anywhere.