Assignment Ops
Assignment Ops
1 Assignment Operators
1. Used to assign values to variables
2. =, +=, -=, *=, /=, //=, %=, **=
3. += –> Add and assign –> Adds right operand to left operand and reassigns the result to
left operand
4. a += b –> Reassigns a with a+b
5. y *= x –> Reassigns y with y*x
[5]: a = 10
a += 5
print(a)
15
[6]: a = 100
a -= 50
print(a)
50
[7]: a = 10
b = 5
a *= b
print(a)
print(b)
50
5
1
[8]: a = 10
b = 5
b *= a
print(a)
print(b)
10
50
[9]: x = 100
x /= 25
print(x)
4.0
[11]: y = 51
y //= 16
print(y)
[12]: g = 2
g **= 3
print(g)
[13]: z = 100
z %= 20
print(z)
[ ]: # Assignment Operators
= -->
+= --> Add and assign
-= --> Subtract and assign
*= --> Multiply and assign
/= --> Divide and assign (the actual quotient)
//= --> Floor divide and assign (the floored quotien)
%= --> Modulo divide and assign (remainder)
**= --> power and assign (a**b)
2
10
900
[15]: a = 3
b = 4
c = 5
a += b # a b c = 7 4 5
b += a # a b c = 7 11 5
c += b # a b c = 7 11 16
c += a # a b c = 7 11 23
a *= b # a b c = 77 11 23
c -= b # a b c = 77 11 12
print(b, c, a) # 77 11 12 #
11 12 77
[17]: x = 3
y = 2
z = 4
x *= y # x y z = 6 2 4
y *= z # x y z = 6 8 4
z += x # x y z = 6 8 10
x += z # x y z = 16 8 10
x //= y # x y z = 2 8 10
z += x # x y z = 2 8 12
print(x, y, z) # 5 8 12 # 2 8 12 #
2 8 12
10 20 30
10
20
30
[20]: a = 10
b = 10
3
c = 10
print(a, b, c)
10 10 10
[21]: a = b = c = 10
print(a, b, c)
10 10 10
[ ]: a = 10
b = 20
print(f'Before swapping\na: {a}\nb: {b}')
c = a
a = b
b = c
print(f'\nAfter swapping\na: {a}\nb: {b}')
[5]: a = 10
b = 20
print(f'Before swapping\na: {a}\nb: {b}')
a, b = b, a
print(f'\nAfter swapping\na: {a}\nb: {b}')
Before swapping
a: 10
b: 20
After swapping
a: 20
b: 10