How to use the Print() function

Posted in Python by Dirk - last update: Jan 09, 2024

The print() function in Python is a built-in function used to display output on the screen. It is commonly used for debugging, testing, and general information display.

print(value1, value2, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
  • value1, value2, …: These are the values or expressions you want to print. You can print multiple values by separating them with commas.
  • sep: Specifies the separator between the values. The default is a single space. end: Specifies the string that will be printed at the end. The default is a newline character (\n).
  • file: Specifies the file-like object where the values will be printed. The default is sys.stdout (standard output).
  • flush: If True, the output is flushed (forcefully written) to the stream. The default is False.

Most basic form

In the most basic form, you can pass a string literal directly to the print() function:

>>> print('Please wait ...')

Please wait ...

This will print the string on the screen.

You don’t have to limit yourself to one string, you can print multiple strings, separated by a comma:

>>> print('Please wait ...','time is passing')

Please wait ... time is passing

By default, the seperator between the two strings is a space, but you can modify that to any separator you like.

Printing Variable and Constants

You can print the values or variables and constants, and mix them with strings:


name = "John"
age = 25

print("This is ", name, " , he is ", age, " years old")

Output:

This is John , he is  25 years old

The variables do not have to be strings, you can type any variables. The previous example showed printing strings and integers.

Printing Floating-Point Numbers


pi = 3.14159
print("The value of pi is:", pi)

Ouput:

The value of pi is: 3.14159

Printing Booleans


is_student = True
print("Is a student?", is_student)

Output:

Is a student? True

Printing lists


numbers = [1, 2, 3, 4, 5]
print("List of numbers:", numbers)

Output:

List of numbers: [1, 2, 3, 4, 5]

Printing tuples


coordinates = (2, 3)
print("Coordinates:", coordinates)

Output:

Coordinates: (2, 3)

Printing dictionaries


person = {"name": "Bob", "age": 25, "city": "New York"}
print("Person:", person)

Output:

Person: {'name': 'Bob', 'age': 25, 'city': 'New York'}

Formatting output

The print() function in Python provides several formatting options to control how the output is displayed

Formatting with format() Method:

Use the format() method for more advanced string formatting. This method is a versatile way to format strings by replacing placeholders {} with values.

Example:


x = 10
y = 20
print("The sum of {} and {} is {}".format(x, y, x + y))

In this example, {} is a placeholder that gets replaced by the corresponding values in the format() method.

The values provided in format(x, y, x + y ) are substituted in order. The first {} is replaced by x, the second by y and the final by x+y

Output:

The sum of 10 and 20 is 30

To make the code easier to read, you can also use named arguments:

name = "Bob"
age = 25
print("Name: {n}, Age: {a}".format(a=age, n=name))

The names inside {} correspond to the argument names in format(). If you use named arguments, the arguments no longer need to be positional, you can list the arguments in any order you like.

Output:

Name: Bob, Age: 25

You can also control how you want variables to be formatted. Example:


pi = 3.14159
print("Value of pi: {:.2f}".format(pi))

The format specification :.2f indicates that the floating-point number pi should be displayed with two decimal places

Output:


Value of pi: 3.14

Formatting using String Literals (f-strings)

String literals, introduced in Python 3.6, provide a precise and readable way to embed expressions inside string literals.

Basic Usage:

  • Place expressions inside {} within the string.
  • The variables inside {} are evaluated and their values are inserted into the string.

Same example as before:


x = 5
y = 10
print(f"The sum of {x} and {y} is {x + y}")

The result is the same, but the code is much easier to understand.

Similar to the format() method, you can use format specifications within f-strings.


pi = 3.14159
print(f"Value of pi: {pi:.2f}")

Old style string formatting

The % operator, often referred to as the “old-style” string formatting, is an alternative way to format strings in Python. While the % operator is still valid and functional, the more modern and preferred approaches include the format() method and f-strings.

An example of formatting with the % operator:

name = "John"
age = 25
height = 1.75

formatted_string = "Name: %s, Age: %d, Height: %.2f" % (name, age, height)
print(formatted_string)

In this example:

  • %s is a placeholder for a string.
  • %d is a placeholder for an integer.
  • %.2f is a placeholder for a floating-point number with two decimal places.

You use the % operator to replace these placeholders with the actual values from the tuple (name, age, height).

However, it’s essential to note that while % formatting is still supported, it is considered somewhat outdated and less flexible compared to the format() method and f-strings. The newer approaches offer more features, improved readability, and better support for complex formatting scenarios.

In practice, unless you are working with legacy code or have a specific reason to use % formatting, it’s generally recommended to use format() or f-strings for string formatting in modern Python code.

Special characters

Separator (sep)

The sep parameter allows you to specify the separator between the printed values. The default is a single space.


x = 5
y = 10
print(x, y, sep=' | ')

Output:


5 | 10

End string (end)

The end parameter defines the string that will be printed at the end. The default is a newline character (\n).

In the example below, the default newline is replaced by a space


print("This is the end.", end=' ')
print("Not a new line.")

Output:


This is the end. Not a new line.

Escape Characters

Use escape characters for special formatting, such as newline (\\n) and tab (\\t).


print("This is a line.\nThis is a new line.")
print("This is a sentence\t with a tab")

Output:

This is a line.
This is a new line.
This is a sentence	with a tab

Special functions

Printing to a file

You can print the output directly to a file, using the file parameter


with open("output.txt", "w") as f:
    print("Hello, file!", file=f)

Flushing output

In the context of the print() function in Python, flushing output involves making sure that the printed information is written to the output destination (e.g., the console or a file) without delay.

By default, the output is often buffered, meaning that the program collects a certain amount of data before actually writing it to the output. This buffering is an optimization to improve the efficiency of I/O operations by reducing the number of write operations.

When you use the flush=True parameter with the print() function, you are instructing the program to bypass the usual buffering behavior and write the data immediately to the output stream. This can be useful in situations where you want to ensure that the output is visible or saved promptly, especially in interactive or real-time scenarios.

Example

import time

print("This will be flushed immediately.", flush=True)
time.sleep(2)  # Simulating some time-consuming operation
print("This will appear right after the previous line.")

In this example, the flush=True ensures that the first line is immediately written to the output, even before the time.sleep(2) delay. Without flushing, you might not see the first line until the entire buffered output is written, after the sleep period.

Flushing is particularly useful when you want to provide timely feedback or update the user interface in real-time, and you don’t want to wait for the entire buffer to fill before displaying the information.

Other articles