0% found this document useful (0 votes)
8 views4 pages

Assignment Ops

Uploaded by

Veera
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views4 pages

Assignment Ops

Uploaded by

Veera
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Assignment Ops

September 28, 2022

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

1.1 Add and assign (+=)


• Adds the right operand and left operand and reassigns the result to
left operand.

[5]: a = 10
a += 5
print(a)

15

[ ]: How many factors does 10 have?


fc = 4
10
10

[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)

[4]: a = 10 # the value of a 10


print(a)
a = 20 # # the value of a 20
a = 30 # the value of a 30
print(a * a)

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

1.2 Single line assignments


[18]: a = 10
b = 20
c = 30
print(a, b, c)

10 20 30

[19]: a, b, c = 10, 20, 30


print(a)
print(b)
print(c)

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

1.3 swapping of two values in Python


1.3.1 Using third variable

[ ]: 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}')

1.3.2 Without using third variable

[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

You might also like