How to print a variable in Python

Printing variables in Python helps developers inspect and debug their code by displaying values during program execution. The print() function serves as a fundamental tool for outputting data to the console, making it essential for both beginners and experienced programmers.

This guide covers essential printing techniques, best practices, and real-world applications, with code examples created using Claude, an AI assistant built by Anthropic. You'll learn everything needed for effective variable printing.

Using the print() function

name = "John"
age = 30
print(name)
print(age)
John
30

The print() function outputs variables directly to the console, displaying their current values during program execution. In this example, it prints both string and integer variables without requiring any type conversion or special formatting.

Python's print() function offers several advantages for debugging and monitoring code:

  • Automatically handles different data types without explicit conversion
  • Creates a new line after each print statement by default
  • Maintains readable output formatting regardless of the variable type

The code demonstrates basic variable printing by declaring two variables (name and age) and outputting them separately. This straightforward approach works well for simple debugging needs. Each value appears on its own line due to the default behavior of print().

Basic printing techniques

Beyond basic print() statements, Python provides powerful string formatting options like f-strings, the + operator, and str.format() to create more sophisticated output.

Using f-strings for formatted output

name = "John"
age = 30
print(f"Name: {name}, Age: {age}")
print(f"In 5 years, {name} will be {age + 5} years old.")
Name: John, Age: 30
In 5 years, John will be 35 years old.

F-strings (formatted string literals) provide a clean, readable way to embed expressions inside string literals. The f prefix before quotes enables you to insert variables and expressions directly using curly braces {}.

  • Variables inside curly braces get replaced with their actual values during printing
  • You can perform calculations inside the braces, like {age + 5}
  • The syntax eliminates the need for complex string concatenation or multiple print() statements

F-strings make your code more maintainable and easier to read. They work with any Python expression that returns a value, allowing you to format strings dynamically without breaking the natural flow of your code.

Concatenating strings with the + operator

name = "John"
age = 30
print("Name: " + name + ", Age: " + str(age))
Name: John, Age: 30

The + operator concatenates strings in Python, joining them into a single output. When combining strings with other data types like integers, you must convert them to strings using str() first. This explains why we use str(age) in the example.

  • The + operator requires all operands to be strings. Attempting to concatenate a string with a non-string value will raise a TypeError
  • String concatenation creates a new string object in memory. This can impact performance when joining many strings
  • While functional, this method often produces less readable code compared to f-strings, especially with multiple variables

The code demonstrates a common pattern where text labels ("Name: " and ", Age: ") combine with variable values to create formatted output. This approach works well for simple cases but becomes unwieldy with complex formatting needs.

Formatting with the str.format() method

name = "John"
age = 30
print("Name: {}, Age: {}".format(name, age))
print("In {1} years, {0} will be {2} years old.".format(name, 5, age + 5))
Name: John, Age: 30
In 5 years, John will be 35 years old.

The str.format() method offers a flexible way to insert values into strings. It uses curly braces as placeholders that get replaced with the values provided in the format() call.

  • Empty braces {} fill with values in order. The first example shows this basic usage, matching name and age sequentially
  • Numbers inside braces {0}, {1}, {2} specify positions. This lets you reuse or reorder values as shown in the second example
  • The method accepts any number of arguments. You can perform calculations like age + 5 directly within the format() call

While str.format() provides more control than basic string concatenation, modern Python code often favors f-strings for their improved readability and simpler syntax.

Advanced printing techniques

Beyond basic string formatting, Python provides specialized functions and methods that give developers granular control over how variables appear in program output.

Using repr() for debugging representation

name = "John"
data = {"name": name, "age": 30}
print(repr(name))
print(repr(data))
'John'
{'name': 'John', 'age': 30}

The repr() function displays a string representation of objects that includes all special characters and formatting. This makes it invaluable for debugging since it shows exactly how Python stores the data internally.

  • When used with strings, repr() adds quotes and escapes special characters. This helps distinguish between similar-looking values like spaces and tabs
  • For complex data structures like dictionaries, repr() preserves the exact syntax you would need to recreate that object in code

In the example, repr(name) shows the quotes around "John" while repr(data) displays the complete dictionary structure with proper Python syntax. This level of detail helps developers spot subtle issues that might not be visible with regular print() statements.

Customizing output with __str__ and __repr__

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def __str__(self):
        return f"{self.name}, {self.age} years old"

person = Person("John", 30)
print(person)
John, 30 years old

Python classes can define special methods __str__ and __repr__ to control how objects appear when printed. The __str__ method creates a human-readable string representation that print() uses by default.

  • The Person class implements __str__ to format its data into a clear string showing name and age
  • When you call print(person), Python automatically invokes the __str__ method
  • Without a custom __str__, Python would print a less useful default representation showing the object's memory location

This customization gives developers precise control over their objects' string output. It's particularly valuable when debugging or logging complex data structures that need clear, readable representations.

Pretty printing complex structures with pprint

import pprint
data = {"name": "John", "age": 30, "skills": ["Python", "JavaScript"], 
        "address": {"city": "New York", "country": "USA"}}
pprint.pprint(data)
{'address': {'city': 'New York', 'country': 'USA'},
 'age': 30,
 'name': 'John',
 'skills': ['Python', 'JavaScript']}

The pprint module formats complex data structures like nested dictionaries and lists into a more readable vertical layout. When dealing with multilevel data, standard print() can produce cluttered, hard-to-scan output on a single line.

  • Each nested level gets proper indentation for clear visual hierarchy
  • Dictionary keys and values align vertically for easier scanning
  • Output automatically wraps long lines to prevent horizontal scrolling

In the example, pprint.pprint(data) transforms the nested dictionary into a clean, structured format. Each key-value pair appears on its own line. The nested address dictionary and skills list maintain proper alignment. This organization makes debugging and data inspection significantly more efficient.

Logging data to files with print() and file redirection

Python's print() function can write output directly to files by using the file parameter, enabling developers to create detailed application logs and track program execution over time.

import time

with open('app_log.txt', 'w') as log_file:
    print("Starting application...", file=log_file)
    print(f"Timestamp: {time.ctime()}", file=log_file)
    print("Application initialized successfully", file=log_file)

with open('app_log.txt', 'r') as log_file:
    print(log_file.read())

This code demonstrates file handling and output redirection in Python. The first with block opens app_log.txt in write mode and redirects print() output to the file instead of the console using the file parameter. Each print() statement writes a new line to the log file.

The second with block opens the same file in read mode and displays its contents. The time.ctime() function adds a timestamp to track when the log entry was created.

  • The with statement automatically closes the file when operations complete
  • Writing 'w' creates a new file or overwrites an existing one
  • Reading 'r' retrieves the file's contents as a string

Building a simple CLI report with print() and formatted output

The print() function enables developers to create organized command-line reports by combining string formatting techniques with alignment operators to display structured data in a visually appealing tabular format.

sales_data = [("Widget A", 1234.56), ("Widget B", 5678.90), ("Widget C", 2468.13)]
total = sum(amount for _, amount in sales_data)

print("\n" + "="*40)
print(f"{'SALES REPORT':^40}")
print("="*40)

for product, amount in sales_data:
    percentage = (amount / total) * 100
    print(f"{product:<15} ${amount:>8.2f} {percentage:>6.1f}%")

print("-"*40)
print(f"{'TOTAL':<15} ${total:>8.2f}")

This code generates a formatted sales report using Python's string formatting capabilities. The program starts by calculating the total sales from a list of tuples containing product names and amounts. It then creates a visually appealing header with = characters and centers the title "SALES REPORT" using the :^40 alignment specifier.

The main loop processes each product's data and calculates its percentage of total sales. The :<15 and :>8.2f format specifiers ensure consistent column alignment. Left alignment (<) creates space after text while right alignment (>) adds space before numbers.

  • The *40 operator repeats characters to create divider lines
  • The f in .2f formats numbers as fixed-point decimals
  • The _ in the total calculation ignores the product names

Common errors and challenges

Python's print() function can trigger unexpected errors and behaviors when developers mix data types, manage line breaks, or use it within functions.

Avoiding TypeError when mixing strings and numbers in print()

Mixing strings and numbers in print() statements often leads to a TypeError. This common mistake occurs when developers attempt to combine different data types using the + operator without proper type conversion. The code below demonstrates this error in action.

age = 30
print("I am " + age + " years old")

The code fails because Python can't directly combine text and numbers with +. The interpreter expects all values to be strings when concatenating with +. Let's examine the corrected version below.

age = 30
print("I am " + str(age) + " years old")
# Or better with f-strings
print(f"I am {age} years old")

The solution demonstrates two approaches to fix the TypeError that occurs when combining strings and numbers. Converting the number to a string with str() works but creates verbose code. Using f-strings provides a cleaner, more readable solution by automatically handling type conversion.

  • Watch for this error when concatenating strings with any non-string data type (int, float, bool)
  • The error commonly appears when working with user input or data from external sources
  • Modern Python code favors f-strings over explicit type conversion for better maintainability

Remember this pattern when building dynamic strings that include calculated values or variables of different types. F-strings eliminate the need to track type conversions while making your code more intuitive.

Controlling line breaks with the end parameter

The print() function automatically adds a newline after each statement. This default behavior can create unwanted line breaks and cluttered output when printing multiple related items. The code below demonstrates how excessive line breaks affect a simple progress indicator's readability.

# Progress indicator that outputs too many lines
for i in range(3):
    print("Loading")
    print(f"{(i+1)*33}% complete")

The code outputs each percentage on a new line, creating a disjointed progress display that's hard to follow. Each print() statement forces an unwanted line break. The solution below demonstrates a more effective approach to building a continuous progress indicator.

# Improved progress indicator with controlled formatting
for i in range(3):
    print("Loading", end=": ")
    print(f"{(i+1)*33}% complete")

The improved code uses the end parameter to control line breaks in the progress indicator output. Setting end=": " replaces the default newline with a colon and space, creating a more compact and readable display that connects "Loading" with its percentage.

  • Watch for unintended line breaks when building status messages, data tables, or any output that should appear on the same line
  • The end parameter accepts any string, making it versatile for custom formatting needs
  • Common values include empty strings (""), spaces (" "), and punctuation (", ")

Avoiding print side-effects in functions

Using print() statements inside functions instead of proper return values creates unexpected behavior in Python programs. This common mistake occurs when developers output values directly rather than passing them back to the calling code.

def get_formatted_name(first, last):
    full_name = f"{first} {last}"
    print(full_name)  # Side-effect instead of returning
    
name = get_formatted_name("John", "Doe")
print(f"Hello, {name}")  # Will print "Hello, None"

The function get_formatted_name() prints its output instead of returning it. When the code tries to use the function's result in Hello, {name}, name contains None because the function has no return statement. Let's examine the corrected version below.

def get_formatted_name(first, last):
    full_name = f"{first} {last}"
    return full_name  # Return instead of print
    
name = get_formatted_name("John", "Doe")
print(f"Hello, {name}")  # Now prints "Hello, John Doe"

The corrected code returns the formatted name instead of printing it directly. This enables other parts of the program to use the function's output. Functions should return values rather than print them. This makes the code more flexible and reusable.

  • Watch for missing return statements in functions that process data
  • Remember that print() statements inside functions create side effects
  • Functions without explicit return statements automatically return None

When building data processing functions, focus on returning processed values. Save printing for when you need to display the final results. This approach creates more maintainable and testable code.

FAQs

How do you print multiple variables on the same line?

Python offers multiple ways to print variables on the same line. The print() function accepts multiple arguments separated by commas, automatically adding spaces between them. You can also use string formatting with + for concatenation or f-strings for cleaner syntax.

  • Use end="" parameter to prevent line breaks
  • Format strings with .format() for precise control
  • Combine sep="" to customize spacing between elements

These approaches give you flexibility to display data exactly as needed while keeping your code readable and maintainable.

What happens if you try to print a variable that doesn't exist?

When you try to print an undefined variable, Python raises a NameError exception. This error occurs because Python can't find the variable name in its namespace—the dictionary-like structure that maps names to objects in memory.

The interpreter first searches the local scope, then moves outward through enclosing scopes until it reaches the global scope. If it still can't find the variable, Python tells you exactly what's missing with an error message like NameError: name 'x' is not defined.

Can you print variables of different data types together?

Yes, you can print variables of different data types together using string concatenation or string formatting. The + operator joins strings, while the str() function converts other data types to strings. Modern string formatting with f-strings offers the cleanest approach.

  • String concatenation requires explicit type conversion: str(number) + text
  • String formatting handles conversions automatically: f"{number} {text}"

This flexibility lets you combine text, numbers, and other data types in a single output while maintaining readable code.

How do you print a variable without adding a new line at the end?

To print without a newline, use print() with the end parameter. By default, Python adds a newline character (\n) after each print statement. Setting end="" overrides this behavior.

  • The end parameter controls what appears after the printed content. An empty string means nothing gets appended.
  • This technique proves especially useful when creating progress bars, status updates, or concatenating multiple prints on a single line.

What's the difference between printing a variable and printing its value as a string?

When you print a variable directly, Python displays its internal representation, including the data type and memory location. Printing with str() converts the variable to a string representation first, showing just its value in a human-readable format.

This distinction matters most with complex data types. For example, printing a list object shows brackets and formatting, while converting it to a string first creates a cleaner output focused on the content. The str() function essentially calls the object's __str__ method, which developers can customize for better readability.

šŸ