How to print a variable in Python
Learn how to print a variable in Python. This guide covers various methods, tips, real-world applications, and common error debugging.

To print a variable in Python is a fundamental skill for any developer. The print() function is your primary tool to display output, check values, and debug your code effectively.
You will learn several techniques to format output with f-strings and other methods. You'll also get practical tips, see real-world applications, and receive advice to debug common print-related issues.
Using the print() function
name = "John"
age = 30
print(name)
print(age)--OUTPUT--John
30
The print() function is straightforward yet powerful. It takes any Python object, like the string variable name or the integer age, and displays its string representation. You don't need to manually convert data types; print() handles that for you.
Notice how each output appears on a new line. This is because every call to print() automatically appends a newline character at the end. This default behavior helps keep your output organized and easy to read, especially when debugging multiple values in sequence.
Basic printing techniques
Beyond printing single variables, you can format more complex messages using f-strings, string concatenation with the + operator, or the str.format() method.
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, are a modern and highly readable way to embed expressions inside string literals. You just need to prefix your string with an f and wrap your variables or expressions in curly braces {}.
- They let you directly insert variable values, like
{name}and{age}. - You can also evaluate expressions right inside the string, such as
{age + 5}, making your code cleaner.
Concatenating strings with the + operator
name = "John"
age = 30
print("Name: " + name + ", Age: " + str(age))--OUTPUT--Name: John, Age: 30
Using the + operator is a classic way to join—or concatenate—strings. It links multiple string pieces together to form a single output. Unlike f-strings, this method requires careful handling of data types.
- It requires all parts to be strings; you can't mix strings with numbers directly.
- You must explicitly convert other data types, like the integer
age, usingstr(). If you don't, Python will raise aTypeError.
While this works well for simple cases, it can become less readable than f-strings as the number of variables grows.
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 offers another flexible way to construct strings. You place curly brace {} placeholders in a string and then pass the variables you want to insert into the .format() method.
- By default, the placeholders are filled sequentially with the arguments you provide.
- You can also use numbered placeholders like
{0}and{1}to control the order or reuse values, giving you more precise control over the output.
Advanced printing techniques
Beyond basic string formatting, you can gain more control over your output, especially for creating clear debugging representations and printing complex or custom 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 string representation of an object, which is great for debugging. It’s designed to be explicit, showing you exactly what the object is—type and all.
- Notice how
repr(name)returns'John'with quotes, making it clear it's a string, not a variable. - Similarly,
repr(data)displays the full dictionary structure, so you can instantly verify its contents during a debugging session.
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
By defining the __str__ method within your class, you can create a custom, user-friendly string representation for your objects. When you call print(person), Python automatically uses the string returned by __str__, which is why you see a clean, formatted output instead of a generic memory address.
- The
__str__method is for creating a readable output for end-users. - The
__repr__method is for an unambiguous developer-facing representation, ideal for debugging.
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']}
When you're working with complex data like nested dictionaries, the standard print() function can produce messy output on a single line that's hard to decipher. The pprint module, which stands for pretty print, solves this by formatting complex data structures in a much more readable way.
- It automatically adds line breaks and indentation to clarify the structure.
- It also sorts dictionary keys alphabetically, making the output consistent and predictable for easier debugging.
Move faster with Replit
Replit is an AI-powered development platform that transforms natural language into working applications. It's designed to help developers turn concepts into code much faster.
You can use Replit Agent to build complete apps—with databases, APIs, and deployment—directly from a description. It can take the printing techniques from this article and turn them into production tools. For example, you could:
- Build a log analyzer that uses
pprintto generate clean, readable reports from complex system data. - Create a data formatting utility that uses f-strings to produce structured text for invoices or summaries.
- Deploy a simple status dashboard that prints real-time updates for a background process.
Describe your app idea, and the agent writes the code, tests it, and fixes issues automatically. Get started and turn your concept into a working application with Replit Agent.
Common errors and challenges
Even with a simple function like print(), you can run into a few common pitfalls, from type errors to unexpected line breaks and side-effects.
- Avoiding
TypeError: When using the+operator, you can't directly combine strings with numbers. Python will raise aTypeErrorbecause it doesn't automatically convert data types during concatenation. You must manually convert numbers to strings withstr()to ensure all parts are compatible. - Controlling line breaks: The
print()function defaults to adding a newline after each output. To print multiple items on the same line, you can use theendparameter. For example,print(item, end=' ')will separate items with a space instead of a line break. - Limiting side-effects: Functions that only
print()a result have limited use, as their output can't be stored or passed to other functions. It's better practice for functions toreturna value. This makes your code more modular and reusable, allowing the part of the code that calls the function to decide how to use the result.
Avoiding TypeError when mixing strings and numbers in print()
A common stumbling block is the TypeError, which appears when you try to join a string and a number with the + operator. Python doesn't automatically convert numbers to strings in this context, leading to an error. The following code demonstrates this exact issue.
age = 30
print("I am " + age + " years old")
The + operator attempts to add the integer age to a string, an operation Python doesn't allow. This conflict causes the TypeError. See how to properly structure the statement in the code below.
age = 30
print("I am " + str(age) + " years old")
# Or better with f-strings
print(f"I am {age} years old")
The solution is to explicitly convert non-string types using str() before joining them with the + operator. This prevents the TypeError by making all elements compatible for concatenation. For cleaner code, you can use an f-string like f"I am {age} years old". It automatically handles the conversion, making it a more robust choice when mixing types in your output.
Controlling line breaks with the end parameter
The print() function's default behavior of adding a newline can be disruptive, especially when you want to display status updates on a single line. Instead of a clean progress indicator, you get a long, broken trail. The code below shows this in action.
# Progress indicator that outputs too many lines
for i in range(3):
print("Loading")
print(f"{(i+1)*33}% complete")
Each print() call inside the loop adds its own newline, creating six separate lines of output instead of a single updating message. The code below shows how to correct this 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 solution uses the end parameter to override the default newline. By specifying end=": ", the first print() statement now ends with a colon and space instead of a line break. This makes the subsequent print() call append its output to the same line. You'll find this technique useful for building clean progress bars or status updates within loops, where you want to avoid cluttering the console with new lines for each iteration.
Avoiding print side-effects in functions
When a function uses print() instead of return, it creates a side-effect but doesn't actually send back a value you can use. This makes the function less reusable since you can't store its output. The code below shows this mistake.
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"
Since the get_formatted_name function only prints the name, it returns None by default. The name variable is assigned this None value, which is why the final output is unexpected. The code below shows how to implement this correctly.
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 solution is to use return instead of print(), making the function more powerful and reusable. By returning the full_name value, you can store it in a variable and decide how to use it later—like printing it in a different message. Keep an eye on this when a function's output is needed for subsequent steps. This practice separates data creation from data display, leading to cleaner, more modular code.
Real-world applications
With a firm handle on printing techniques and their pitfalls, you can build practical tools like log files and simple command-line reports.
Logging data to files with print() and file redirection
By using the file parameter, you can direct the print() function’s output to a file, turning it into a straightforward tool for creating application logs.
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 how to channel print() output directly into a file. It opens app_log.txt in write mode using a with statement, which ensures the file is closed automatically after use.
- The key is the
file=log_fileargument within eachprint()call. This redirects the output from the console to the specified file object. - After writing the log entries, the script reopens the file in read mode and prints its contents, confirming the data was written successfully.
Building a simple CLI report with print() and formatted output
By combining the print() function with f-string format specifiers, you can turn raw data into a clean, structured report right in your command-line interface.
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 script generates a neatly aligned sales report using advanced f-string formatting. It leverages format specifiers to control the layout of text and numbers, creating a clean, table-like structure directly in the console.
- Specifiers like
:<15left-align the product name within a 15-character column. - The
:^40specifier centers the report title within a 40-character width. - Formats such as
:>8.2fright-align a number in an 8-character space and limit it to two decimal places.
This technique gives you precise control over your CLI output's appearance.
Get started with Replit
Put your skills to work with Replit Agent. Describe an app like "a CLI tool that uses pprint to format JSON data" or "a unit converter that prints formatted results to the console."
The agent writes the code, tests for errors, and deploys your app. Start building with Replit and turn your ideas into working software.
Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.
Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.



%2520in%2520Python.png)