The print() method in Python

The print() method is a built-in method offered by Python that allows a user to display output to the console.

Let’s output a simple string that says “Hello from Educative!” to the console.

print("Hello from Educative!")

We can also output variables of any datatype to the console simply using the print() method. Let’s print a few data types, including integers, floats, booleans, strings, lists, dictionaries, and tuples.

print(12)
print(3.1415)
print(False)
print("This is a sample output")
print([7, 12, 19, 51, 9 ])
print({"movie":"The Lion King", "city": "Tokyo", "anime": "Death Note"})
print((True, False, True, True))

Parameters

The print() method consists of various parameters that we can customize according to our needs.

print(object= , separator=, end=, file=, flush=)
Syntax of print() method

Parameters

Explanation

object

Value to print

sep

Specify the separating character between printed strings (defaults to “ “)

end

Append characters to the end of the printed value (defaults to newline char (“\n”)).

file

Location of printed values (defaults to the screen)

flush

If output is to be flushed (defaults to False)

Run the code below to see this in action!

print("Hello", "Ash", sep = ", ", end = "\n", file = None, flush = False)

Formatted strings

Formatted strings, or f-strings, are a recent addition by Python, and they provide a highly concise way to embed expressions inside string literals. This makes the output formatting quite straightforward for use and more readable for readers as well.

name = "X12"
print(f"Welcome to Educative , {name}!")

We can also format more than one variable with varying data types. This is achieved using the format() method.

The format() method is applied to a string and receives the variables to format as parameters. Let’s output a user’s name and age together.

name = "Ash"
age = 21
message_for_user = "Hi {}! You are {} years old!".format(name, age)
print(message_for_user)

Formatting numeric output

Python allows its users to specify the number of decimal places to output, as well as other formatting options combined with the print statement.

PI = 3.14159
print(f"The value of PI to 2 decimal places is : {PI:.2f}")

Error handling in the output

It’s crucial to handle potential errors in the code, or else the program can crash or cause unexpected behavior. The ‘try’ and ‘except’ blocks can be used to catch such errors, and ‘print’ can be used alongside them to output the error.

try:
answer = 198 / 0
except ZeroDivisionError:
print("Zero division error!")