PYTHON

Python print() Function: Logging in Python

The print() function outputs data to the console for debugging and displaying information in command-line applications.

How to Use the print() Function in Python

Python’s print() function takes several arguments, including objects to output and various optional arguments.

print(*objects, sep=' ', end='\\n', file=sys.stdout, flush=False)
  • objects: One or more expressions or objects to output to the console.
  • sep: The optional sep parameter specifies the separator between objects (default is a space).
  • end: An optional parameter to specify what to output at the end of the line (default is a newline).
  • file: The optional file parameter specifies the output stream (default is sys.stdout).
  • flush: An optional parameter to speficy whether to flush the output buffer (default is False).

Basic Usage

print("Hello, world!")

When to Use the print() Function in Python

The print() function is useful in command line applications and for debugging purposes.

Python Printing Exceptions

You can use print() within try-except blocks to output error messages. In Python, printing error messages can help diagnose and fix errors during development.

try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"Error occurred: {e}")

Python Printing Formatted Strings

You can also use print() to display the results of operations, computations, or function outputs to the user. This is essential for providing feedback in command-line applications.

result = 2 + 2
print(f"The result is {result}")

Examples of Using print() in Python

Web Development Processes

Most web applications use print() to test components quickly and effectively during development.

user_data = {"username": "john_doe", "email": "john@example.com"}
print("User data:", user_data)

Errors and Exceptions

Web applications log errors to the console when catching exceptions, aiding in monitoring and troubleshooting.

try:
    # Simulated risky operation
    risky_operation()
except Exception as error:
    print("Error occurred:", error)

Data Processing Pipelines

Data processing tools might use print() to output interim results. This helps in verifying each step of the data transformation process.

def process_data(data):
    print("Raw data:", data)
    processed_data = [d * 2 for d in data]
    print("Processed data:", processed_data)
    return processed_data

data = [1, 2, 3, 4, 5]
process_data(data)

Machine Learning Training

Machine learning workflows often use print() to log training progress and performance metrics. This makes monitoring the model's training process easy.

for epoch in range(10):
    train_loss = 0.1 * epoch  # Simulated training loss
    print(f"Epoch {epoch+1}: Training loss = {train_loss}")

Learn More About the Python print() Function

Printing Different Data Types in Python

The print() function in Python can handle various data types, including strings, integers, floats, and lists. To output a string, simply pass it as an argument to the print() function.

name = "Alice"
print(name)  # Outputs: Alice

You can also use print() with integers, floats, and lists individually or combine them with strings using f-strings.

age = 25
height = 5.9
fruits = ["apple", "banana", "cherry"]
print(age)  # Outputs: 25
print(height)  # Outputs: 5.9
print(fruits)  # Outputs: ['apple', 'banana', 'cherry']
print(f"Age: {age}, Height: {height}")  # Outputs: Age: 25, Height: 5.9

Python Printing a Newline

You can print a newline in Python using the print() function. By default, print() ends with a newline character, so each call to print() will output the text on a new line. To print a single line without content, simply call print() without any arguments.

print("First line")
print()
print("Third line")
# Outputs:
# First line
#
# Third line

You can also use the escape character \n within a string to create multiple lines of output from a single print() statement.

print("First line\nSecond line\nThird line")
# Outputs:
# First line
# Second line
# Third line

Python Printing Without a Newline

By default, the print() function's console output ends with a new line. To print to the console without adding a newline, you can set the end parameter to an empty string. By printing without a newline in Python, you can create continuous console output on the same line.

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

Python Printing the Current Directory

You can print the current directory in the Python programming language using the os module. This is useful for confirming the directory of your script, especially when dealing with directory-related issues.

import os
current_directory = os.getcwd()
print(f"Current Directory: {current_directory}")

Python Pretty-Printing Dictionaries

The pprint (pretty-print) module in Python provides a way to format complex data structures in a readable way. Pretty-printing is useful with dictionaries or other data structures that are difficult to read in their raw form.

To pretty-print a dictionary in Python, use pprint.pprint() with the dictionary.

import pprint

example_dict = {
    'name': 'Alice',
    'age': 25,
    'city': 'Wonderland',
    'hobbies': ['reading', 'gardening', 'painting'],
    'education': {
        'degree': 'Bachelor of Arts',
        'university': 'Wonderland University',
        'year': 2018
    }
}

pprint.pprint(example_dict)

Python Pretty-Printing JSON

Pretty-printing JSON objects helps in debugging and data visualization. Printing “pretty” JSON in Python is particularly useful when dealing with API responses or configuration files.

import json
data = {"widget": {"debug": "on", "window": {"title": "Sample Widget"}}}
print(json.dumps(data, indent=4))

Python Formatting Print

Python offers versatile formatting options for print() with format strings or f-strings. This makes it easy to create well-structured and readable output.

name = "Alice"
age = 25
print("Name: {}, Age: {}".format(name, age))
print(f"Name: {name}, Age: {age}")

Python Printing to a File

You can also direct output to a text file by changing the file parameter. This is useful for logging purposes or when you need to save output data.

with open('output.txt', 'w') as f:
    print("This is written to a file.", file=f)
Learn to Code in Python for Free
Start learning now
button icon
To advance beyond this tutorial and learn Python by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2024 Mimo GmbH