1.
Declaring Variables
name = "Alice"
age = 25
height = 5.6
is_student = True
print(name)
print(age)
print(height)
print(is_student)
2. Multiple Assignments
x, y, z = 10, 20, 30
print(x, y, z)
# Assigning the same value to multiple variables
a = b = c = 100
print(a, b, c)
3. Variable Types
name = "John" # String
age = 22 # Integer
pi = 3.14 # Float
is_active = False # Boolean
print(type(name))
print(type(age))
print(type(pi))
print(type(is_active))
4. Changing Variable Type
value = "123" # string
value = int(value) # converted to integer
print(value)
print(type(value))
5. Using Variables in Expressions
a = 5
b = 3
sum_result = a + b
product = a * b
print("Sum:", sum_result)
print("Product:", product)
6. Swapping Variables
x = 10
y = 20
x, y = y, x
print("x:", x)
print("y:", y)
1. Using Variables with Functions
def calculate_area(length, width):
area = length * width
return area
l = 10
w = 5
result = calculate_area(l, w)
print("Area:", result)
2. Using Variables in Loops and Conditions
numbers = [1, 2, 3, 4, 5]
total = 0
for num in numbers:
if num % 2 == 0:
total += num # Add even numbers only
print("Sum of even numbers:", total)
3. Variables with Dictionaries (Key-Value Pairs)
student = {
"name": "Ravi",
"age": 20,
"marks": 85.5
}
# Accessing and modifying values
student["marks"] += 5
print("Updated Marks:", student["marks"])
4. Global and Local Variables
x = 100 # Global variable
def update():
global x
x = x + 50 # Modifying global variable
update()
print("Global x:", x)
5. Variable Unpacking with Lists and Tuples
# List unpacking
data = [10, 20, 30]
a, b, c = data
print(a, b, c)
# Tuple unpacking with ignore
person = ("John", 25, "Engineer")
name, _, profession = person
print(name, profession)
6. Using Variables in List Comprehension
squares = [x*x for x in range(1, 6)]
print("Squares:", squares)
7. Type Hinting ( 3.5+)
def greet(name: str, age: int) -> str:
return f"Hello {name}, you are {age} years old."
message = greet("Anjali", 23)
print(message)
8. Dynamic Variable Creation Using globals() (Rare Use Case)
for i in range(3):
globals()[f"var{i}"] = i * 10
print(var0, var1, var2)