Python print() Function - Scaler Topics (original) (raw)

Overview

Python's print() function outputs messages to the console, a standard output device, or a file.

Syntax of print() in Python

The syntax of the print() function is as follows:

Parameters of print() in Python

These are the parameters accepted by the print() function,

sep, end, file, and flush are keyword arguments and are optional parameters in print() in Python.

Return Value of Python print() Function

Return Type: None

print in Python doesn't return any value.

Example:

Output:

What is print in Python?

A fundamental part of programming is printing the output. Different methods exist for printing output in every programming language, whether to the console or files. In Python, the print() function is used for this purpose.

The print() function is specific to Python 3. In Python 2, the print statement is used instead, without parentheses.

Python 2 Example:

Python 3 Example:

In Python 2, print is a statement and does not require parentheses. However, in Python 3, print() is a function and requires parentheses around its arguments.

Flush Argument

The I/O in Python is generally buffered, which means they are used in chunks. Until a display device is ready, data ready to be seen is held in an output buffer in memory or cache. It means that you might see the output from your code later, which makes debugging more difficult.

A flush is handy here since it lets users decide whether they want the written content buffered. It is false by default, meaning the output will generally be buffered.

More Examples of print() in Python

Example 1: print() with Separator and End Parameters in Python

Output:

Explanation:

Example 2: print() with File Parameters

In Python, the output can be written to a file using the file parameter. If the file doesn't exist, it creates one with the same name and then writes to it.

Explanation:

Example 3: Using end Parameters

The end parameter configures the value you want to put at the end of the provided values. By default, it is '\n', i.e., a newline character.

Output:

Explanation

Conclusion