We can use the equal (=) sign to assign a value to some variable.
Simple Assignment
The value or expression on the right side will be assigned to the variable that is on the left side, when we use the assignment expression-
simple_data = 100
name = "Big Box Code"
mass = 7
gravity = 9.81
height = 6.55
acceleration = 5
radius = 3.5
PythonAssignment after Calculation
We can also assign some value after calculating it, in the same line-
calculated_data = simple_data * 5 + 139
full_info = "name: " + name + " | url: https://bigboxcode.com"
force = mass * acceleration
gpe = mass * gravity * height
area = 3.1416 * radius * radius
PythonAssignment Multiple Times
Assigning value to the same variable multiple times can be done. In that case, the last assignment will be the value when we access it-
height = 6.55
radius = 3.5
# height is 6.55 and radius is 3.5 if accessed here
# Reassign the value of height and radius
height = 1.4
radius = 10
# height is 1.4 and radius is 10 if acccessed here
PythonAugmented Assignment Operators
Every numeric operator has an augmented assignment operator. This way we can perform the operation and assign the new value to the variable, at the same time-
Operator | Description | Example | Equivalent Normal Operation |
---|---|---|---|
+= | Add and assign | x += 10 | x = x + 10 |
-= | Subtract and assign | x -= 10 | x = x – 10 |
*= | Multiply and assign | x *= 10 | x = x * 10 |
/= | Divide and assign | x /= 10 | x = x / 10 |
//= | Floor divide and assign | x //= 10 | x = x // 10 |
**= | Exponenatiate and assign | x **= 10 | x = x ** 10 |
%= | Modulo and assign | x %= 10 | x = x % 10 |