How to print a variable in Python
Learn how to print a variable in Python. This guide covers various methods, tips, real-world uses, and how to debug common errors.

The ability to print variables in Python is a core skill for any developer. It helps you display output, check values, and debug your code. The built-in print() function makes this simple.
In this article, we'll explore techniques to use the print() function effectively. We will cover formatting tips, discuss real-world applications, and share common debugging advice to help you master this essential tool.
Using the print() function
name = "John"
age = 30
print(name)
print(age)--OUTPUT--John
30
The example demonstrates the most direct way to inspect a variable's state. By passing a variable like name directly to the print() function, you get its raw value sent to the console. This is fundamental for debugging and verifying your logic as you build.
Notice how each print() call results in a new line in the output. This default behavior is useful for separating distinct pieces of information, making the output easy to read without extra formatting code.
Basic printing techniques
While printing a variable on its own is a great start, you'll often want to combine it with other text to create more descriptive messages.
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.")--OUTPUT--Name: John, Age: 30
In 5 years, John will be 35 years old.
F-strings, or formatted string literals, let you embed Python expressions directly inside a string. You just need to prefix the string with an f and wrap your variables or expressions in curly braces {}. This makes your code cleaner and easier to read than older formatting methods, especially when adding variables to strings.
- The expression
f"Name: {name}, Age: {age}"shows how variables are seamlessly integrated into the text. - You can also evaluate expressions on the fly, like
age + 5, right within the string itself.
Concatenating strings with the + operator
name = "John"
age = 30
print("Name: " + name + ", Age: " + str(age))--OUTPUT--Name: John, Age: 30
Another way to build strings is by using the + operator to join them together. This method, known as concatenation, lets you chain multiple strings and variables into a single output. It's a straightforward approach, but it requires careful handling of data types. For more details on string concatenation techniques, you can explore different methods available.
- Notice that the integer
agemust be converted to a string withstr(age). The+operator will raise aTypeErrorif you try to combine a string with a non-string type directly.
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))--OUTPUT--Name: John, Age: 30
In 5 years, John will be 35 years old.
The str.format() method is a versatile way to construct strings. It works by placing placeholder curly braces {} in your string and then calling the .format() method with the values you want to insert. Unlike string concatenation, it automatically handles type conversions for you.
- By default, the placeholders are filled in the order the arguments are provided.
- You can also specify the order by putting numbers inside the braces, like
{0}and{1}. This gives you more control, allowing you to reuse or reorder variables without changing the argument list.
Advanced printing techniques
While the basic methods cover everyday needs, Python provides powerful tools for clearer debugging output and displaying complex objects.
Using repr() for debugging representation
name = "John"
data = {"name": name, "age": 30}
print(repr(name))
print(repr(data))--OUTPUT--'John'
{'name': 'John', 'age': 30}
The repr() function gives you an unambiguous, developer-focused representation of a variable. It's designed to be explicit, showing you the object's literal structure—which is perfect for debugging. You can see how it differs from a simple print() call, as it aims to be as informative as possible.
- Notice that
repr(name)includes quotes ('John'), clearly identifying the variable as a string. - For the dictionary
data, it prints the full structure, making it easy to verify keys and values at a glance.
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)--OUTPUT--John, 30 years old
You can control how your custom objects are displayed by defining special "dunder" methods. When you use print() on an object, Python automatically calls its __str__ method to get a user-friendly string. This is why printing the person object gives a clean, readable output instead of a generic object description. To understand the fundamentals of creating custom classes, you can learn more about class structure and methods.
- The
__str__method's goal is to provide a nice, readable string for end-users. - If
__str__isn't defined, Python falls back to using the__repr__method for a developer-focused output.
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)--OUTPUT--{'address': {'city': 'New York', 'country': 'USA'},
'age': 30,
'name': 'John',
'skills': ['Python', 'JavaScript']}
The pprint module is essential for inspecting complex data structures. When a standard print() would output a long, jumbled line, pprint.pprint() organizes the data so it's easy to understand. This is especially useful for debugging nested dictionaries or long lists, particularly when accessing dictionary data within complex structures.
- It automatically sorts dictionary keys and formats the output across multiple lines for clarity.
- Indentation clearly shows nested structures, making it simple to trace relationships within your data.
Move faster with Replit
Replit is an AI-powered development platform that comes with all Python dependencies pre-installed, so you can skip setup and start coding instantly. Instead of piecing together techniques, you can use Agent 4 to go from an idea to a working product—it handles the code, databases, APIs, and deployment directly from your description.
For example, you could ask the Agent to build practical tools that use the formatting methods from this article:
- A log file analyzer that reads complex data structures and uses pretty printing to generate a readable summary for debugging.
- A dynamic report generator that pulls variables like
name,age, andskillsinto a formatted, user-friendly string. - A data migration tool that converts custom objects into a standardized string format for exporting to other systems.
Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.
Common errors and challenges
Even with a simple function like print(), you can run into a few common pitfalls that are easy to solve once you know how.
A frequent hurdle is the TypeError that appears when you try to join a string and a number with the + operator. This happens because Python can't guess whether you want to add numbers or combine strings. To fix this, you must explicitly convert numbers to strings using the str() function before concatenating. Alternatively, using f-strings or the .format() method avoids this issue entirely, as they handle the conversion for you.
By default, every print() call adds a line break, which isn't always what you want. You can control this behavior with the end parameter, which tells print() what to add at the end of the output.
- To print multiple items on the same line separated by a space, you can set
end=' '. - If you want to join outputs without any separation, use an empty string:
end=''.
While print() is invaluable for debugging, relying on it inside your functions can make your code less flexible. A function that prints a result directly has a side effect—it does something other than just returning a value. This makes it harder to reuse, since the function is locked into one action: printing to the console.
A better practice is to have your functions return the result. The code that calls the function can then decide what to do with that value, whether it's printing it, saving it, or using it in another calculation. This separates your logic from your output and makes your code more modular and testable.
Avoiding TypeError when mixing strings and numbers in print()
One of the most common errors you'll encounter is a TypeError. This happens when you try to join a string and a number with the + operator, because Python doesn't know whether to add numbers or combine strings. The code below triggers this exact error.
age = 30
print("I am " + age + " years old")
This error happens because the + operator is attempting to join a string with the integer age. Python doesn't automatically convert types during concatenation. The corrected code below shows how to fix this.
age = 30
print("I am " + str(age) + " years old")
# Or better with f-strings
print(f"I am {age} years old")
The fix is to explicitly convert the age variable to a string with str(age). This resolves the ambiguity, telling Python you intend to concatenate strings, not perform addition. For cleaner and more modern code, you can use an f-string like f"I am {age} years old", which handles the conversion automatically.
- Keep an eye out for this error whenever you build strings using the
+operator with mixed data types.
Controlling line breaks with the end parameter
By default, each print() call adds a newline, which isn't always what you want for things like a progress indicator. This can clutter your output. The code below demonstrates how this default behavior can be problematic in practice.
# Progress indicator that outputs too many lines
for i in range(3):
print("Loading")
print(f"{(i+1)*33}% complete")
The loop contains two separate print() calls, so each one adds its own newline, resulting in fragmented output. The corrected code below shows how to combine them onto a single, updating line for a cleaner progress indicator.
# Improved progress indicator with controlled formatting
for i in range(3):
print("Loading", end=": ")
print(f"{(i+1)*33}% complete")
The corrected code uses the end parameter to change the default newline behavior. By setting end=": ", the first print() call no longer adds a line break but instead appends a colon and a space. The subsequent print() statement then continues on the same line, creating a single, clean output.
- This technique is perfect for building dynamic status updates or progress indicators where you need to control output on a single line.
Avoiding print side-effects in functions
While print() is great for quick checks, using it inside a function creates a side-effect that makes your code less reusable. A function that prints a value can't pass that value to other parts of your program for further processing.
The code below demonstrates this problem. The get_formatted_name function prints the name directly instead of returning it, which leads to an unexpected None value when you try to use its output.
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"
Because the get_formatted_name function only prints, it returns None by default. The name variable captures this, leading to the unwanted output. See how a small change in the function fixes this issue in the code 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 function uses return full_name instead of printing. This change is crucial because it allows the function to pass its result back to the code that called it. The name variable now correctly captures the string "John Doe", preventing the unexpected None from appearing in your final output.
- This makes your functions more modular and reusable.
- It separates the core logic from the output, which is a best practice in software development.
Real-world applications
Beyond debugging, the print() function is a powerful tool for creating command-line reports and logging application data in real-world projects.
Logging data to files with print() and file redirection
You can easily redirect the output of the print() function to a file using its file parameter, turning it into a simple yet effective tool for creating log files.
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 example shows how to create a simple log file. The code first opens app_log.txt in write mode ('w'), which creates the file if it doesn't exist. Inside the with block, each print() statement writes a line of text directly to the file object, including a timestamp from the time module. For more comprehensive approaches to creating log files, you can explore additional logging techniques and best practices.
- The
withstatement ensures the file is automatically closed, even if errors occur. - Finally, the code reopens the file in read mode (
'r') to print its contents, confirming the log was written successfully.
Building a simple CLI report with print() and formatted output
You can combine print() with f-string formatting to build well-structured command-line reports, complete with aligned columns and neatly formatted numbers.
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 example builds a command-line sales report by leveraging advanced f-string formatting. The code first calculates total sales and prints a centered title. A loop then processes each product, using f-strings to create neatly aligned columns for text and numbers.
- The product name is left-aligned, while sales figures are right-aligned and formatted as currency.
- It also calculates and displays each product's sales percentage, formatted to one decimal place.
This shows how print() can produce polished, readable output for data analysis.
Get started with Replit
Put these techniques into practice with Replit Agent. Just describe a tool, like “a currency converter that prints formatted output” or “a log file analyzer that pretty-prints a summary,” to get started.
The Agent writes the code, tests for errors, and deploys your app. You just provide the instructions. Start building with Replit.
Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.
Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.



