Python print() Function

Uncover the inner workings of your Python programs with the print function. It’s a powerful tool for debugging code, inspecting variable values at any point during execution, and providing informative messages to users. Whether you’re a seasoned Python developer or just starting, the Python print() function is a fundamental building block for effective programming.

Python-print()-Function
Table of Contents

Python print() Function

Think of the Python print() function as your program’s way of communicating with you, the user. It’s like a versatile display window where you can show text messages, the current value of variables, or the results of calculations. The Print function takes what you tell it and sends it directly to the screen, making it useful for understanding how your program works and sharing information as it runs. Here’s the syntax:

Python print() Syntax (Python 3)

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

  • objects (required): The data to print (strings, numbers, variables, etc.). Separate multiple objects with commas.
  • sep=’ ‘ (optional): Separator between objects (defaults to space).
  • end=’\n’ (optional): String printed at the end (defaults to newline).
  • file=sys.stdout (optional): Output destination (defaults to console).
  • flush=False (optional): Controls output buffering (defaults to not flushing immediately).

Python print() Example (Python 3)

# Print a greeting
print("Hello, Python!")  

# Print a variable's value with a label
name = "Mark"
print(f"His name is: {name}")

Explanation

  • Line 2: Prints the message “Hello, Python!”.
  • Line 5: Assigns the string “Mark” to the variable name.
  • Line 6: Uses an f-string to print a label “His name is:” followed by the value stored in the variable name.

Output

Hello, Python!
His name is: Mark


Print Was a Statement in Python 2

In Python 2, print was a statement that didn’t return a value. While similar in functionality, it lacked the flexibility of a function.

Syntax (Python 2)

print *objects, sep=’ ‘, end=’\n’

Example (Python 2)

# Print with a custom separator (notice quotes around print)
print "Hello", "world!", sep="--"  

# Print a variable's value with a label (comma needed)
name = "Bob"
print "His name is:", name

Explanation

  • Line 2: Prints “Hello–world!” using sep="--" to replace the default space separator.
  • Line 5: Assigns the string “Bob” to the variable name.
  • Line 6: Prints “His name is:” followed by the value in name (comma needed to separate print statements).

Key Points for Python 2

Here are the key points regarding the print statement in Python 2:

  • Statement, Not Function: print was a statement, limiting its flexibility compared to functions.
  • Commas for Separation: You needed commas to separate items being printed (e.g., print “Hello”, “world”).
  • No f-strings: Python 2 lacked f-strings, requiring older string formatting methods.

Single Quotes

Single quotes (') are similar to double quotes in Python, letting you create text strings. They’re particularly useful when your text contains double quotes you want to display or if you need to include a single quote character within the string. 

Syntax

‘text here’ (replace ‘ with ‘)

Example

# Print a message containing double quotes using single quotes
message = 'This string says "Hello, world!"'
print(message)

Explanation

  • Line 2: Assigns the text ‘This string says “Hello, world!”‘ (including the double quotes within single quotes) to the variable message. Here, the single quotes allow the double quotes within the message to be displayed literally.
  • Line 3: Prints the contents of the message variable using print().

Output

This string says “Hello, world!”


Double Quotes

Double quotes (") are the most common way to wrap text you want to display in Python. They allow you to include various characters, spaces, and even special symbols within your string. 

Syntax

‘text here’ (replace ‘ with “)

Example

# Print a greeting with double quotes
message = "Hello, world! This is a string with double quotes."
print(message)

Explanation

  • Line 2: Assigns the text “Hello, world! This is a string with double quotes.” (including the quotes themselves) to the variable message.
  • Line 3: Prints the contents of the message variable using print().

Output

Hello, world! This is a string with double quotes.


Triple Quotes (Multiline Strings)

Triple quotes (""" or ''') are for multi-line strings or including code snippets within your Python code. They offer more flexibility compared to single or double quotes. 

Syntax

”’text here”’ or text here (you can use either triple single quotes or triple double quotes)

Example

# Print a multi-line poem using triple quotes
poem = """Twinkle, twinkle, little star,
How I wonder what you are!
Up above the world so high,
Like a diamond in the sky."""
print(poem)

Explanation

  • Line 2: Assigns a poem using triple-double quotes ("") to the variable poem. Notice how the newlines and formatting are preserved within the string.
  • Line 6: Prints the contents of the poem variable using print(). The poem will be displayed with its original line breaks.

Output

Twinkle, twinkle, little star,
How I wonder what you are!
Up above the world so high,
Like a diamond in the sky.


Printing Strings

In Python, displaying text on the screen is a breeze using the print() function. You can use it to print simple strings or even combine them with variables.

Example

# Print a string and a variable's value
greeting = "Hi there!"
name = "Mark"
print(greeting, name)  # You can separate objects with commas

Explanation

  • Line 2: Assigns the string “Hi there!” to the variable greeting.
  • Line 3: Assigns the string “Mark” to the variable name.
  • Line 4: Uses print() to display both the greeting and the value stored in name separated by a space (the default separator).

Output

Hi there! Mark


String Concatenation

Imagine you have messages or bits of text you want to combine. String concatenation in Python allows you to combine multiple strings into one. 

Syntax

string1 + string2

Explanation

  • string1: The first string you want to connect.
  • string2: The second string you want to connect.

The + operator acts like glue, merging the strings.

Example

# Create a full name by combining strings
first_name = "Bob"
last_name = "Smith"
full_name = first_name + " " + last_name  # Add a space in between
print(full_name)

Explanation

  • Line 2: Assigns the string “Bob” to the variable first_name.
  • Line 3: Assigns the string “Smith” to the variable last_name.
  • Line 4: Creates a new string full_name by concatenating first_name, a space, and last_name using the + operator.
  • Line 5: Prints the value of full_name, which is “Bob Smith”.

Output

Bob Smith


Printing Variables

In Python, variables act like containers containing information you can use throughout your program. The print() function is your bridge to displaying the values stored in these variables. 

Example

# Print the value stored in a variable
age = 30
print(age)  # Print the variable directly

Explanation

  • Line 2: Assigns the number 30 to the variable age.
  • Line 3: Uses print() to display the value stored in the variable age.

Formatted Output with f-strings

F-strings (formatted string literals) are a modern and convenient way to create formatted output in Python. They’re like magic boxes where you can embed variables and expressions directly within a string. 

Syntax

f’text {expression} more text’

The ‘f‘ before the quote tells Python it’s a formatted string.

expression: The variable or calculation you want to include in the formatted string.

Example

# Use an f-string to format a greeting
name = "Charlie"
age = 37
print(f"Hello, {name}! You are {age} years old.")

Explanation

  • Line 2: Assigns the string “Charlie” to the variable name.
  • Line 3: Assigns the number 37 to the variable age.
  • Line 4: Uses an f-string to create a formatted message. The curly braces {} act as placeholders where the values of name and age are inserted directly into the string.

Output

Hello, Charlie! You are 37 years old.


Printing Integers

Printing integers in Python is straightforward. Integers are whole numbers (like 1, -10, or 42). You use the familiar print() function to display an integer’s value.

Example

# Print an integer
age = 25
print(age)

Explanation

  • Line 2: Assigns the integer 25 to the variable age.
  • Line 3: Uses print() to display the value stored in the variable age.

Printing Exponentials

Exponentials represent very large or small numbers in Python. You can use the pow() function or the asterisk operator (*) to raise a number to a power. To print these exponential values, you can leverage the print() function. 

Using pow() function

print(pow(base, exponent))

Explanation

  • base: The number you want to raise to a power.
  • exponent: The power to which you want to raise the base.

Using asterisk operator (*)

print(base * exponent)

Technically not exponentiation, but suitable for small exponents.

  • base: The number you want to raise to a power.
  • exponent: The power to which you want to raise the base. (Note: This method works for small integer exponents due to repeated multiplication).

Example: pow() function

# Print the value of 2 raised to the power of 3 (2^3)
base = 2
exponent = 3
print(pow(base, exponent))  # Alternatively, 2**3 (for small exponents)

Explanation

  • Line 2: Assigns the number 2 to the variable base.
  • Line 3: Assigns the number 3 to the variable exponent, representing the power.
  • Line 4: Uses print(pow(base, exponent)) to calculate and display 2 raised to the power of 3 (which is 8). You can also replace this with print(2**3) for small exponents, but it’s not recommended for larger values due to potential overflow errors.

Printing Floats

Python makes printing float values (numbers with decimals) just as easy as printing whole numbers. Floats are useful for representing quantities that aren’t whole, such as distances, temperatures, or prices. You use the friendly print() function to display them. 

Example

# Print a float 
height = 175.3  # A floating-point number with a decimal
print(height) 

Explanation

  • Line 2: Assigns the floating-point value 175.3 to the variable height.
  • Line 3: Uses print() to display the value stored in the variable height.

Printing Multiple Objects

Imagine you want to display more than one piece of information at a time in Python. The print() function is handy for printing multiple objects, like strings, variables, or calculations. 

Example

# Print a name, age, and greeting
name = "David"
age = 40
greeting = "Hello!"
print(name, age, greeting)  # Notice commas separate each object

Explanation

  • Line 2: Assigns the string “David” to the variable name.
  • Line 3: Assigns the integer 40 to the variable age.
  • Line 4: Assigns the string “Hello!” to the variable greeting.
  • Line 5: Uses print() to display the values of name, age, and greeting separated by spaces (the default separator).

Output

David 40 Hello!


Custom Separators

By default, Python’s print() function uses spaces to separate multiple objects you’re printing. But you can customize this separation using a separator.

Syntax

print(*objects, sep=’your_separator_here’, end=’\n’) (focus on sep)

sep (optional): A separator (like a space) inserted between objects (replace ‘your_separator_here‘ with your desired separator).

Example

# Print a list with a custom separator (dash)
fruits = ["apple", "banana", "orange"]
print("Available fruits:", *fruits, sep="-")  # Notice * unpacks the list

Explanation

  • Line 2: Creates a list fruits containing some fruit names.
  • Line 3: Uses print() with sep='-' to display “Available fruits:” followed by each fruit in the fruits list, separated by dashes (-) instead of spaces. The asterisk (*) unpacks the list so its elements are printed individually.

Output

Available fruits:-apple-banana-orange


Preventing Line Breaks

In Python, the print() function usually adds a newline character at the end, moving the cursor to the next line. But what if you want to print things on the same line? You can prevent this line break using the end argument within print()

Syntax

print(*objects, sep=’ ‘, end=”) (focus on end part)

end (optional): A string printed at the very end (defaults to newline, set it to an empty string to prevent it).

Example

# Print a message without a newline at the end
message = "Printing on the same line"
print(message, end='')  # Notice end='' to suppress newline
print(" done.")  # This will print on a new line (default behavior)

Explanation

  • Line 2: Assigns the string “Printing on the same line” to the variable message.
  • Line 3: Uses print(message, end='') to display the contents of message and set end to an empty string , preventing the automatic newline.
  • Line 4: Prints ” done.” with the default newline behavior, moving the cursor to the next line.

Output

Printing on the same line done.


Printing to a File

By default, the print() function displays output on the console screen. But Python allows you to redirect this output to a file, creating a permanent record of your information. Here’s a simplified way to think about it:

  • You’re opening a file for writing (like opening a notebook to write in).
  • You’re using print() to write the data to the opened file (like writing your message in the notebook).
  • You’re closing the file (like closing your notebook to save your work).

Example

# Write a message to a file
with open("my_message.txt", "w") as file:  # Open for writing ("w")
     print("This message is written to a file.", file=file)
     
print("This message is still printed to the console.")  # Default behavior

Explanation

  • Line 2: Opens a file named “my_message.txt” in write mode (“w”) and assigns it to the variable file. The with statement ensures the file is closed properly.
  • Line 3: Uses print() with file=file to write the message “This message is written to a file.” to the opened file file.
  • Line 4: Prints “This message is still printed to the console.” using the default behavior, which displays output on the screen.

Buffering print() Output

In Python, by default, the print() function flushes output immediately, meaning the message appears on the console right after the print statement is executed. However, for large amounts of data or performance-critical situations, buffering print calls can be beneficial. Buffering temporarily stores the data to be printed and flushes it all at once later. While Python doesn’t have a built-in buffering mechanism for print(), you can achieve a similar effect using custom functions. Here’s the idea:

  • Create a function that accumulates data passed to it using append() within a list.
  • You can manually flush the data using another function that empties the list when needed.

Example

def accumulate_data(data):
  """
  Accumulates data passed to it by appending it to a list.

  Args:
      data: The data to be accumulated.
  """
  global data_list  # Declare data_list as global
  data_list.append(data)

def flush_data():
  """Clears the accumulated data list."""
  del data_list[:]  # Clear the list using slicing

# Initialize an empty list to store data
data_list = []

# Accumulate some data
accumulate_data("hello")
accumulate_data(5)
accumulate_data([1, 2, 3])

# Print the accumulated data
print("Data before flushing:", data_list)

# Flush the data
flush_data()

# Print the data list after flushing
print("Data after flushing:", data_list)

Explanation

  • Line 1: This function takes some data and appends it to the data_list. This list acts as a storage space for the accumulated data.
  • Line 27: This function empties the data_list, effectively clearing out all the accumulated data.
  • The rest of the code shows how to use these functions:
    • An empty list data_list is initialized to store accumulated data.
    • Different data types are added to data_list using the accumulate_data function.
    • The data is printed, the flush_data function is called, and the list is printed again to show it’s empty.

Printing Custom Data Types

Python’s print() function works wonders with built-in data types like numbers and strings. But what about your custom data types (like classes you create)? By defining a special method called __str__() within your class, you can customize how your objects are displayed with print().

  • The __str__() method defines how your object should be represented as a string.
  • When you use print() with your custom object, Python calls this __str__() method to get a string representation for printing.

Example

class Person:
  # Class to represent a person
  def __init__(self, name, age):  # Constructor to initialize attributes
    self.name = name
    self.age = age

  # Define a __str__() method to control how the object is printed
  def __str__(self):
    return f"Person(name='{self.name}', age={self.age})"

# Create a Person object
person1 = Person("Alice", 30)

# Print the person object using print()
print(person1)

Explanation

  • Lines 1-5: Define a class Person with attributes name and age, and a constructor __init__() to initialize them.
  • Lines 8-9: Define a special method __str__() that returns a formatted string representation of the Person object using f-strings.
  • Line 12: Create an instance person1 of the Person class.
  • Line 15: Use print(person1) to print the person1 object. Since __str__() is defined, the formatted string representation from __str__() will be printed.

Output

Person(name=’Alice’, age=30)


Pretty-Printing Nested Structures (pprint)

Nested data structures like dictionaries with lists within them can get visually messy when printed. The pprint module in Python comes to the rescue with its pprint() function for pretty-printing. It automatically indents and arranges your data for better readability.

Syntax

pprint.pprint(data)

data: The nested data structure you want to prettify (e.g., a dictionary).

Example

# Sample nested data structure
data = {
     "name": "Alice",
     "age": 30,
     "hobbies": ["reading", "coding", "music"],
     "address": {
         "street": "123 Main St",
         "city": "Anytown",
         "state": "CA"
     }
 }

# Pretty-print the data structure
import pprint
pprint.pprint(data)

Explanation

  • Lines 2-11: Create a nested dictionary data containing information about a person.
  • Line 14: Imports the pprint module.
  • Line 15: Uses pprint.pprint(data) to prettify the data dictionary. The output will be indented, displaying the nested structure.

Output

{'address': {'city': 'Anytown', 'state': 'CA', 'street': '123 Main St'},
 'age': 30,
 'hobbies': ['reading', 'coding', 'music'],
 'name': 'Alice'}

Adding Colors with ANSI Escape Sequences

Spice up your text output in Python with ANSI escape sequences! These special codes control formatting on the console, allowing you to add splashes of color to your text. While not all consoles support them perfectly, they can enhance the visual appeal of your output.

Escape Sequence Syntax

\033[codem

Explanation

  • \033 (octal notation for the escape character)
  • [: Introduces the code
  • code: A numeric code defining the formatting (e.g., 31 for red text)
  • m: Marks the end of the code

Example: Printing red text

# Print red text using ANSI escape sequence
print("\033[31mThis text is printed in red.\033[0m")  # 0 resets formatting

Line 2: Prints a string with ANSI escape sequences.

  • \033[31m: Sets the text color to red (code 31).
  • “This text is printed in red.” : The text to be displayed in red.
  • \033[0m: Resets all formatting back to defaults (code 0).