Print Function

An introduction to Python’s print() function, explaining its syntax, parameters, and usage with practical examples for outputting text and other data to the console or files.

Loading...
Print Function

In Python, the print() function is used to display output on the console. It is one of the most commonly used functions in Python for debugging and outputting information.

For example:

print("Hello World!")
# Output: Hello World!

In this example, the print() function displays the string "Hello, World!" on the console.

Syntax

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

Let’s break down the parameters of the print() function:

  1. object(s):

The object(s) to be printed. You can pass any number of objects (strings, integers, lists, etc.), and they will be converted to strings before being printed.

For example:

print("Hello", 42)
# Output: Hello 42
  1. sep='separator':

Specifies how to separate the objects, if there is more than one. The default separator is a space ' '. You can change this to any string. (This is optional)

For example:

print("Hello", "World", sep=", ")
# Output: Hello, World
  1. end='end':

Specifies what to print at the end. By default, it is a newline character (\n), meaning the next output will be printed on a new line. You can change this to any string. (This is optional)

For example:

print("Hello", "World", end="!")
# Output: Hello World!
  1. file:

An object with a write() method (such as a file object). The default is sys.stdout, meaning output will be printed to the console. (This is optional)

For example:

# writing to a file
with open("output.txt", "w") as file:
    print("Hello, World!", file=file)
  1. flush:

A Boolean value, specifying if the output is flushed (True) or buffered (False). Default is False. (This is optional)

For example:

print("Hello", flush=True)

This will flush the output buffer, meaning that it will be printed to the console immediately.

Now, let’s take a look at the example using sep and end parameters.

print("Hello", "World", sep=", ", end="!\n")
# Output: Hello, World!

In this example:

  • The sep parameter places a comma and a space between "Hello" and "World".
  • The end parameter changes the default newline to an exclamation mark followed by a newline.

Support my work!