Variables & Assignment

Basic Assignment

  1. #variable assignment
  2. x = 5
  3. #ans: x is 5
  4. name = "Alice"
  5. #ans: name is "Alice"
  6. pi = 3.14
  7. #ans: pi is 3.14

Multiple Assignment

  1. #assign multiple variables
  2. a, b, c = 1, 2, 3
  3. #ans: a=1, b=2, c=3
  4. # what are the values?
  5. x, y = 10, 20
  6. #ans: x=10, y=20

Swapping Values

  1. # traditional swap needs temp variable
  2. x, y = 5, 10
  3. temp = x
  4. x = y
  5. y = temp
  6. #ans: x=10, y=5
  7. #ans: python swap
  8. x, y = 5, 10
  9. x, y = y, x
  10. #ans: x=10, y=5

Chained Assignment

  1. # assign same value to multiple variables
  2. x = y = z = 0
  3. #ans: x=0, y=0, z=0
  4. a = b = c = "same"
  5. #ans: all are "same"

Exercises - Part 1

  1. # what is the value of x?
  2. x = 10
  3. #ans: 10
  4. # what happens after this swap?
  5. a, b = 5, 15
  6. a, b = b, a
  7. #ans: a=15, b=5
  8. # what is z after this?
  9. x, y, z = 1, 2, 3
  10. z = x + y
  11. #ans: 3
  12. # can you assign like this?
  13. x = y = z = 0
  14. #ans: yes, all are 0

Exercises - Part 2

  1. # what is the value of b?
  2. a = 5
  3. b = a
  4. a = 10
  5. #ans: 5
  6. # what does this produce?
  7. x, y = 1, 2, 3
  8. #ans: Error: too many values to unpack
  9. # what is y?
  10. x = y = 5
  11. x = x + 1
  12. #ans: 5

Exercises - Part 3

  1. # multiple assignment with calculation?
  2. a, b = 10, 20
  3. a, b = a+b, a-b
  4. #ans: a=30, b=-10
  5. # what happens here?
  6. x = 1
  7. x = x
  8. #ans: x is still 1
  9. #ans: tricky swap
  10. x, y = 5, 10
  11. x, y = y, x+y
  12. #ans: x=10, y=15

Exercises - Part 4

  1. # assignment from right to left?
  2. a = b = 3
  3. b = 5
  4. #ans: a=3, b=5
  5. # what is x?
  6. x = 10
  7. #ans: 10
  8. # unpacking with extra values?
  9. x, y = [1, 2, 3]
  10. #ans: Error: too many values

Exercises - Part 5

  1. # what about this?
  2. a, b, c = "abc"
  3. #ans: a='a', b='b', c='c'
  4. # swap three variables?
  5. x, y, z = 1, 2, 3
  6. x, y, z = z, x, y
  7. #ans: x=3, y=1, z=2
  8. # empty assignment?
  9. x, y = [], []
  10. #ans: x=[], y=[]

Google tag (gtag.js)