Python Output Variables
In Python, variables are displayed using the
print() function.
You can output single variables, multiple variables, or combine variables with text.Output a Variable
You can print the value of a variable directly using
print().python
x = 10
print(x)
python
name = "John"
print(name)
python
price = 99.99
print(price)
Output Multiple Variables (Using Comma)
The recommended way to output multiple variables is by separating them with commas.
This works even when variables have different data types.
python
x = 5
y = "John"
print(x, y)
python
a = 10
b = 20
c = 30
print(a, b, c)
python
name = "Python"
version = 3
print(name, version)
Using + Operator with Variables
The
+ operator works only when variables are of the same type.String + String (Allowed)
python
x = "Hello "
y = "Python"
print(x + y)
python
first = "Code"
second = "Marathi"
print(first + second)
python
a = "AWS "
b = "Cloud"
print(a + b)
Number + Number (Allowed)
python
x = 5
y = 10
print(x + y)
python
a = 100
b = 200
print(a + b)
python
num1 = 3
num2 = 7
print(num1 + num2)
String + Number (Not Allowed)
Combining a string and a number using
+ causes an error.python
x = 5
y = "John"
print(x + y)
Correct Way to Mix Text and Numbers
Using Comma (Best and Simple)
python
x = 5
y = "John"
print(x, y)
python
age = 25
print("Age:", age)
python
marks = 90
print("Marks obtained", marks)
Using str() Conversion
python
x = 5
print("Value is " + str(x))
python
price = 100
print("Price is " + str(price))
python
count = 3
print("Count = " + str(count))
Using f-strings (Modern & Recommended)
python
x = 5
y = "John"
print(f"{y} is {x} years old")
python
a = 10
b = 20
print(f"Sum is {a + b}")
python
language = "Python"
version = 3
print(f"{language} version is {version}")
Summary (Quick)
- Use
print(variable)to output a variable - Use commas to print multiple variables
+works only with same data types- Use commas,
str(), or f-strings to mix text and numbers
Practice
python
x = 10
y = "Python"
# Try printing both without error
python
a = 5
b = 15
# Print their sum
python
name = "Student"
marks = 80
# Print using f-string