Python print() Method

The print() method prints the given object to the console or to the text stream file.

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

Parameters:

  1. objects: One or more objects to be printed, seperated by a space ' ' by default.
  2. Sep: (Optional) If multiple objects passed, they are separated by the specified separator. Default is ' '.
  3. end: (Optional) The last value to print. Default is '\n'.
  4. file: (Optional) Must be an object with write(string) method. Default is sys.stdout.
  5. flush: (Optional) The stream is forcibly flushed if buffered. Default is False.

Return Value:

None.

The following example demonstrates the print() function.

Example:
print("Learning Python")
name = 'John'
print("My name is",name)
Output
Learning Python
My name is John

We can pass various parameters to alter the output.

Example:
name = 'John'
print("My name is",name,sep='---',end = "\n\n\n\n")
print("I am 18 years old")
Output
My name is---John
I am 18 years old

The following prints the object to the file.

Example:
printtofile = open('debug.txt', 'w')
print('printing to file', file = printtofile)
printtofile.close()
>>> name="Ram"                     
>>> age=21                          
>>> print(name, age, sep=",")
Ram,21

The output of the print() function always ends by the NEWLINE character. The print() function has another optional parameter end, whose default value is \n, which can be substituted by any other character such as a single space (' ') to display the output of the subsequent print() statement in the same line, as shown below.

>>> name="Bill"                  
>>> age=21                     
>>> print(name, end=" "); print(age)
Bill 21

Note that the output is displayed in a single line even if there are two print() statements.

It is possible to format the output using C style format specifier symbols such as %d, %f, %s, etc. Learn about it in the Python String.

Want to check how much you know Python?