Understanding Python print() Function: Beyond Hello World

You might be wondering, “Why a whole tutorial on a simple print function?” But don’t be deceived. The humble print() function, although straightforward to use, is an indispensable tool in your Python arsenal.

This tutorial will walk you through the basics of using the print() function, explore its syntax and parameters, and then dive into more advanced topics.

You will learn about string concatenation, formatted strings, escape characters, and more.

You will discover how to control the separator between printed items, specify the end character, and even how to print to a file instead of the console.

Regardless of whether you’re a beginner just starting your Python journey or an experienced programmer looking to brush up your skills, this tutorial is designed to provide valuable insights for everyone.

 

 

Differences between print in Python 2 and Python 3

Python 3 introduced several changes to the language, one of which was a new syntax and extended functionality for the print() function.

Python 2: print as a Statement

In Python 2, print was treated as a statement, not as a function. The syntax was quite simple:

print "Hello, World!"

To print multiple items, you could separate them with commas, which would insert a space between them:

print "Hello,", "World!"

However, this old print statement lacked the flexibility of a full-fledged function and had limited capabilities.

Python 3: print() as a Function

In Python 3, print() became a built-in function, with its own parameters, making it far more powerful and flexible.

print("Hello, World!")

Transitioning from Python 2 to Python 3

For those transitioning from Python 2 to Python 3, it’s essential to note this change. Using Python 2 style print statements in Python 3 will result in a SyntaxError.

If you’re using Python 2 but want to take advantage of the new print() function’s capabilities, you can import it from the __future__ module:

from __future__ import print_function
print("Hello, World!")

The __future__ module in Python 2 allows you to use features that will become standard in future versions of Python.

 

Syntax and keyword arguments

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

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

This special syntax might look complex, but let’s break it down:

  • *objects: This represents the variable number of positional arguments you can pass to the print() function. They can be a string, numeric values, boolean, or complex data types like lists, tuples, and dictionaries.
  • sep=' ': This is an optional keyword argument, and its default value is a whitespace. It specifies the character or sequence of characters used to separate multiple objects.
  • end='\n': Also an optional keyword argument, end specifies what the print() function should append after printing all the positional arguments. By default, this is a newline character (\n), which is why subsequent print() calls output on a new line.
  • file=sys.stdout: This keyword argument, by default, specifies that the standard output stream should be used for the print operation. You can change this to point to other streams such as files.
  • flush=False: By default, the print() function buffers the output and only flushes (or sends it to the desired output stream) when it deems necessary. However, if flush is set to True, the output is flushed immediately after the print() call.

 

Python print() return value

The print() function returns None. To ensure that, you can use the nested print trick.

When you nest print() calls, the inner print() will send its output first, followed by the outer print().

Since the print() function returns None, the outer print() will print None.
Here’s an example:

print(print("Hello, World!"))

Output:

Hello, World!
None

In the code above, print("Hello, World!") sends “Hello, World!” to the console and returns None. The outer print() then prints this return value, which is why None appears in the output.

 

Controlling the Separator Between Printed Items

You can control this separator using the sep keyword argument.

This feature is particularly handy when you need more explicit control over your output format.
Consider the following code:

print("Hello", "world!", sep=" - ")

Output:

Hello - world!

Here, we use the sep keyword argument to specify a separator, in this case, a hyphen with surrounding spaces.

 

Specifying the End Character

The print() function in Python, by default, appends a newline character (\n) to its output.

In some cases, you want to suppress this behavior or replace the newline character with something else. This can be achieved using the end keyword argument.
Here’s an example:

print("Hello, world!", end="")
print(" Welcome to Python.")

Output:

Hello, world! Welcome to Python.

In this code, we’ve set the end keyword argument to an empty string (""). This means that after the first print() function executes, it doesn’t append a newline character, but nothing at all.

Thus, the next print() function continues printing on the same line, resulting in a single-line output without newline.
Instead of appending an empty string, you can print text with another trailing character:

print("Loading...", end=" ")

Output:

Loading... 

The print() function prints the string “Loading…”, and instead of a newline character, it appends a single whitespace, allowing subsequent print() calls to continue on the same line with a space in between.

 

Use Flush for immediate printing

Python’s print() function has a flush keyword argument that you can use to control when the output is flushed to the underlying stream.

This can be useful in situations where you want to ensure that the output is immediately visible, such as when printing progress updates or status messages.

By default, the print() function operates in a buffered mode, which means that it collects output in a buffer and writes it to the lower-level layers of code all at once.

This is more efficient than writing each character as soon as it’s printed, because writing to the screen or a file is relatively slow compared to Python’s execution speed.

However, buffering can mean that your output doesn’t appear immediately. If Python exits or crashes before the buffer is flushed, your output may be incomplete.

To prevent this, you have 2 options:

  • Use the newline (\n) as end keyword argument which flushes the buffer automatically.
  • Use the flush keyword argument to force print() to flush the output buffer:
import time
for i in range(5):
    time.sleep(1)  # Simulating some processing time
    print(f"Processing chunk {i+1}", end="...")
print("Process finished.")

The print() function does not include flush=True, so the output won’t appear until the processing ends.

Let’s use the flush keyword argument:

import time
for i in range(5):
    time.sleep(1)  # Simulating some processing time
    print(f"Processing chunk {i+1}", end="...", flush=True)
print("Process finished.")

The output this time is printed as soon as it happens.

 

Using Escape Characters

Escape characters are special characters in Python that you can use in print function to achieve various effects, such as inserting a new line (\n), a tab (\t), or special characters like double quotes (\") that would otherwise interfere with the string syntax in Python.
Consider the following example:

print("Hello\nworld!\tWelcome to \"Python\".")

Output:

Hello
world!  Welcome to "Python".

In this example, we use \n to create a new line in the string, effectively separating “Hello” and “world!”. The \t creates a tab space after “world!”, and \" allows us to include double quotes in our string without ending the string prematurely or causing undesired effects.

In the same way, you can escape and print any special character such as “” or “””:

print("Welcome to \"\" Python")
print("Welcome to \"\"\" Python")

Output:

Welcome to "" Python
Welcome to """ Python

 

String Concatenation in print()

The + operator is used to perform concatenation in Python’s print() function, providing a way to create more complex messages from simpler string parts.
Let’s look at an example:

name = "Alice"
print("Hello " + name + "! Welcome to Python.")

Output:

Hello Alice! Welcome to Python.

In this example, we concatenate the string stored in the name variable with two other string literals.

If you try to concatenate a string with a non-string type (like a numeric or a boolean), you will receive a TypeError.
If you need to concatenate non-string types, you can convert them to strings first using the str() function, like so:

age = 25
print("Hello Alice! You are " + str(age) + " years old.")

Output:

Hello Alice! You are 25 years old.

In this case, the integer age is converted to a string using the str() function before being concatenated with the other strings.

 

Using the print() Function with Formatted Strings

The Python print() function is very useful when used in conjunction with formatted strings. Formatted strings, also known as f-strings (formatted string literals), allow you to embed expressions inside string literals, using curly braces {}.
Let’s see a simple example of using f-strings with print():

name = "Alice"
age = 20
print(f"{name} is {age} years old.")

Output:

Alice is 20 years old.

In the example above, the f-string is passed as an argument to the print() function.

The expressions within the curly braces {} are replaced with their values, resulting in a nicely formatted string.
Formatted strings are especially handy when dealing with multiple variables and complex expressions. For example:

from math import pi
radius = 5
area = pi * radius**2
print(f"The area of a circle with radius {radius} is {area:.2f}.")

Output:

The area of a circle with radius 5 is 78.54.

In this case, the f-string includes an expression area:.2f which uses a special syntax to format the area value as a floating-point number with 2 digits after the decimal point.

 

Aligning and Padding Output

When using the print() function in Python, sometimes you may want to align and pad your output for better readability, particularly when dealing with tables or columns of data. Python’s f-strings provide a flexible way to do this.
Let’s look at an example:

students = [("Alice", 92), ("Bob", 88), ("Charlie", 95)]

# print header
print(f"{'Name':<10} {'Score':<10}")

# print each student's name and score
for name, score in students:
    print(f"{name:<10} {score:<10}")

Output:

Name       Score     
Alice      92        
Bob        88        
Charlie    95        

In this example, we use the :<10 format specifier in the f-string to left-align (<) the values in a field of width 10.

This creates a columnar output where each column is 10 characters wide.
If we wanted to right-align the scores, we could use :>10 instead:

# print header
print(f"{'Name':<10} {'Score':>10}")

# print each student's name and score
for name, score in students:
    print(f"{name:<10} {score:>10}")

Output:

Name            Score
Alice             92
Bob               88
Charlie           95

The :<10 and :>10 format specifiers in the f-string expressions indicate how to align the output.

The : character starts the format specification, the < or > character specifies left or right alignment, and the 10 specifies the width of the field.

 

Using Separators in Number Printing

Python provides a convenient way to format numbers with separators for thousands, millions, and so on, which significantly enhances the readability of larger numbers.
Consider this simple example:

print(f"{1234567890:,}")

Output:

1,234,567,890

In the above example, we are using the f-strings feature available in Python 3.6 and above. Inside the f-string, we specify the format for our number using :,, which tells Python to include a comma as a thousand separator.
This technique also works for floating-point numbers:

print(f"{1234567890.123456789:,}")

Output:

1,234,567,890.123456789

Here, the integer and fractional parts of the number are separated by a period, and the integer part is separated into thousands with commas, making the number easier to read at a glance.

 

Using the Percent Symbol (%) in print()

Before the introduction of the f-strings in Python, the primary way to format strings was with the percent (%) operator, known as string formatting or interpolation.

It’s somewhat similar to the printf-style formatting in C. While it’s less common in modern Python code, it’s still useful to understand how it works, as you may encounter it in older codebases.

Syntax and Usage

The percent (%) operator takes a format string on the left (%d for integers, %f for floating-point numbers, %s for strings, etc.) and the corresponding values in a tuple on the right.

The format string can also contain special characters like \n (for newline) and %% (to print a literal %).

Here’s an example:

name = "Alice"
age = 25
print("Hello, %s. You are %d years old." % (name, age))

Output:

Hello, Alice. You are 25 years old.

The number and type of % specifiers in the format string must match the number and type of values in the tuple.

Formatting Numbers

You can also control the way numbers are displayed. For example, you can specify the number of decimal places for a floating-point number:

pi = 3.14159
print("The value of pi to 2 decimal places is %.2f" % pi)

Output:

The value of pi to 2 decimal places is 3.14

In recent versions of Python, the % operator for string formatting has largely been replaced by the str.format() method and f-strings.

 

Using print() with Custom Classes

When you print an instance of a custom class using the print() function, Python uses the class’s __str__ method to convert the object into a string that can be printed.
If you don’t define a __str__ method in your class, Python will use the default implementation, which may not be very human-readable.
Here’s an example:

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

alice = Student("Alice", 20)
print(alice)

Output:

<__main__.Student object at 0x7f72f802f490>

In this case, because we didn’t define a __str__ method, Python uses the default representation, which includes the module name, the class name, and the memory address where this object is stored.
Let’s modify the Student class to include a __str__ method:

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return f"Student Name: {self.name}, Age: {self.age}"

alice = Student("Alice", 20)
print(alice)

Output:

Student Name: Alice, Age: 20

In this version of the Student class, we’ve included a __str__ method that returns a string representation of the Student object. Now, when we print a Student object, the output is the string returned by the __str__ method.

 

Print Multiple Lines

The Python print() function allows you to print multiple lines of text with a single function call. This can be achieved in several ways.

Using newline

One way is to use the newline character (\n) in your string:

print("Hello\nWorld\nWelcome to Python!")

Output:

Hello
World
Welcome to Python!

In the example above, we insert \n into the string at the points where we want to break the line.

The \n character tells Python to insert a newline at that point in the string.

Using Triple Quotes

Another way is to use triple quotes (''' or """), which allow you to create multiline strings:

print("""
Hello
World
Welcome to Python!
""")

Output:

Hello
World
Welcome to Python!

In this example, we use triple quotes to create a multiline string, which retains the line breaks and spaces exactly as you’ve written them.

 

Printing Output to a File Instead of the Console

You can use the file keyword argument to redirect the output to a file.

Let’s see how this works:

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

In this example, we first open a file named output.txt in write mode ('w'). We then call the print() function and use the file keyword argument to specify that we want to print to the file f (which represents output.txt), instead of the console.
If you open output.txt after running this code, you will find the following text:

Hello, World!

It’s important to note that using print() to write to a file does not automatically append a newline character at the end of the file, unless specified by the end keyword argument.
Keep in mind that using the print() function to write text to files is only recommended for simple text output.

For more complex text file operations, Python provides file handling functionalities that are better suited.

 

Temporarily Disabling/Blocking Output

In some cases, you might want to temporarily disable the output of the print() function, for instance, when you are debugging your code and want to suppress non-essential messages.
One way to achieve this is by redefining the print() function to a no-operation (NOP) function that does nothing. Here’s an example:

def nop(*args, **kwargs):
    pass

original_print = print
print = nop
print("This will not be printed")

# Restore the original print function
print = original_print
print("This will be printed")

Output:

This will be printed

In the above code, we first define a function nop() that does nothing. We then store the original print() function in the variable original_print and replace print() with nop(). This effectively disables output from print().

After the output is disabled, we restore the original print() function and print a message that does appear in the output.
Note that this method disables all output from print(), not just error messages or specific types of output. Also, this is a global change affecting all uses of print(). Use this technique with caution.

 

Printing Colored Text in the Console

Python doesn’t directly provide a way to print colored text, but this can be achieved by using ANSI escape sequences, which are a standard for in-band signaling to control cursor location, color, font styling, and other options.
Here’s an example:

print("\033[91mThis will be printed in red!")
print("\033[0mThis will be printed in default color!")

Output:

This will be printed in red!    # This appears in red color in the console.
This will be printed in default color!    # This appears in default color in the console.

In the above example, \033[91m is an ANSI escape sequence that sets the text color to red. The escape sequence \033[0m resets the text color to the console’s default color.
Here’s another example where we print some text in green and then reset the color:

print("\033[92mThis will be printed in green!")
print("\033[0mBack to normal now!")

Output:

This will be printed in green!  # This appears in green color in the console.
Back to normal now!   # This appears in default color in the console.

Please note that ANSI escape sequences might not work in all environments or consoles, and their effect may vary.

 

Python Not Printing to Terminal

There could be several reasons why Python might not be printing to the terminal. Here are a few possible causes:

  1. Script error: If there’s an error in your Python script before the print statement, the script might exit before it gets to the print statement.
  2. Buffering: If your script ends before the buffer is flushed (emptied), you might not see the output. To ensure the buffer is flushed after each print statement, you can use print("text", flush=True) as we did above.
  3. Redirected output: If the output of the script is being redirected to a file as we saw, you might not see anything in the terminal. Also, check to make sure the output isn’t being redirected using the > operator.
  4. Missing print statement: This might seem obvious, but it’s worth checking to make sure that you actually have a print statement in your script!
  5. Incorrect terminal: If you are working with multiple terminals, ensure you are checking the right terminal for the output.
  6. Environment Issues: The Python environment might be improperly configured. For instance, some issue with the PATH variable might be causing problems with the execution of the script.
  7. Using a GUI-based IDE: If you’re using a GUI-based integrated development environment (IDE), the output might be directed to an internal console rather than the system terminal. Check the settings of your IDE to see where the output is being directed.
Leave a Reply

Your email address will not be published. Required fields are marked *