Welcome!
Join our coding community
Ā© 2024 Ace Coding Academy
Code Examples
Example 1
Simple Reassignment. Initially, score refers to the value 85. After reassignment, score refers to the new value 92. The original value 85 is no longer accessible through this variable.
score = 85
print(score) # 85
# Later in the program...
score = 92
print(score) # 92
Example 2
Changing data types. Python allows changing a variable's type through reassignment. First, value holds an integer. After reassignment, it holds a string. This flexibility is due to Python's dynamic typing.
value = 10
print(value, type(value)) # 10 <class 'int'>
value = "hello"
print(value, type(value)) # hello <class 'str'>
Example 3
Incrementing a counter. Reads the current value, applies the operation, then reassigns. The += operator is shorthand for "add and reassign". Similar shorthand exists for other operations: -=, *=, /=, etc.
counter = 0
# Increase the counter
counter = counter + 1 # counter is now 1
# Increment again using shorthand
counter += 1 # counter is now 2
Example 4
Swapping values between variables. The Python way creates a temporary tuple (b, a) and unpacks it. No need for a temporary variable. Clean and readable approach unique to Python.
# Traditional way (using a temporary variable)
x = 5
y = 10
temp = x
x = y
y = temp
print(x, y) # 10 5
# Python's elegant way
a = 15
b = 25
a, b = b, a
print(a, b) # 25 15