Python: Assignment Operator

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
Python

Assignment 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
Python

Assignment 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
Python

Augmented 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-

OperatorDescriptionExampleEquivalent Normal Operation
+=Add and assignx += 10x = x + 10
-=Subtract and assignx -= 10x = x – 10
*=Multiply and assignx *= 10x = x * 10
/=Divide and assignx /= 10x = x / 10
//=Floor divide and assignx //= 10x = x // 10
**=Exponenatiate and assignx **= 10x = x ** 10
%=Modulo and assignx %= 10x = x % 10

Leave a Comment


The reCAPTCHA verification period has expired. Please reload the page.