Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Print Single and Multiple variable in Python?
To display single and multiple variables in Python, use the print() function. For multiple variables, separate them with commas or use formatting methods.
Variables are reserved memory locations to store values. When you create a variable, you reserve space in memory. Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory.
Print Single Variable in Python
To display a single variable, pass it directly to the print() function ?
Example
# Printing single values print(5) print(10) # Printing variables name = "Alice" age = 25 print(name) print(age)
5 10 Alice 25
Print Multiple Variables in Python
To display multiple variables in one print() statement, separate them with commas ?
Using Comma Separator
# Multiple values with comma print(5, 10, 15) # Multiple variables with comma name = "Bob" age = 30 city = "New York" print(name, age, city)
5 10 15 Bob 30 New York
Using String Formatting
name = "Charlie"
age = 28
salary = 50000
# Using f-strings (Python 3.6+)
print(f"Name: {name}, Age: {age}, Salary: ${salary}")
# Using format() method
print("Name: {}, Age: {}, Salary: ${}".format(name, age, salary))
# Using % formatting
print("Name: %s, Age: %d, Salary: $%d" % (name, age, salary))
Name: Charlie, Age: 28, Salary: $50000 Name: Charlie, Age: 28, Salary: $50000 Name: Charlie, Age: 28, Salary: $50000
Controlling Output Format
Using the end Parameter
By default, print() adds a newline. Use the end parameter to change this behavior ?
# Print on same line with space
print("Hello", end=" ")
print("World")
# Print multiple statements on same line
print(1, 2, 3, end=" | ")
print(4, 5, 6)
Hello World 1 2 3 | 4 5 6
Using the sep Parameter
The sep parameter controls how multiple values are separated ?
# Custom separator
print("apple", "banana", "cherry", sep=", ")
print(2023, 12, 25, sep="-")
print("A", "B", "C", sep=" | ")
apple, banana, cherry 2023-12-25 A | B | C
Comparison of Methods
| Method | Syntax | Best For |
|---|---|---|
| Comma Separator | print(a, b, c) |
Simple variable display |
| f-strings | f"Value: {variable}" |
Modern, readable formatting |
| format() | "Value: {}".format(var) |
Python 2.7+ compatibility |
| % formatting | "Value: %s" % var |
Legacy code |
Conclusion
Use commas to print multiple variables simply, f-strings for modern formatted output, and end/sep parameters to control formatting. Choose the method that best fits your Python version and formatting needs.
