Pass Statement

Pass in If

  1. # placeholder for empty block
  2. if True:
  3. pass
  4. #ans: nothing happens

Pass in Function

  1. # empty function
  2. def my_function():
  3. pass
  4. #ans: function does nothing

Pass in Class

  1. # empty class
  2. class MyClass:
  3. pass
  4. #ans: empty class definition

Pass in Loop

  1. # pass in loop
  2. for i in range(3):
  3. pass
  4. #ans: loop runs 3 times, does nothing

Multiple Pass

  1. # multiple pass statements
  2. if True:
  3. pass
  4. pass
  5. #ans: both do nothing

Exercises - Part 1

  1. # what happens?
  2. x = 5
  3. if x > 3:
  4. pass
  5. #ans: nothing (pass is a no-op)

Exercises - Part 2

  1. # can you have empty if?
  2. if True:
  3. #ans: SyntaxError (needs at least pass)

Exercises - Part 3

  1. # pass in loop?
  2. for i in range(3):
  3. pass
  4. #ans: loop runs 3 times, does nothing

Exercises - Part 4

  1. # multiple pass?
  2. if True:
  3. pass
  4. pass
  5. #ans: valid, both do nothing

Exercises - Part 5

  1. # pass vs continue?
  2. for i in range(3):
  3. pass
  4. print(i)
  5. #ans: 0, 1, 2 (pass doesn't skip)

Exercises - Part 6

  1. # pass with else?
  2. if False:
  3. pass
  4. else:
  5. print("Else")
  6. #ans: Else

Exercises - Part 7

  1. # what is x?
  2. x = 5
  3. if x > 10:
  4. x = 10
  5. else:
  6. pass
  7. #ans: x is still 5

Exercises - Part 8

  1. # pass in try?
  2. try:
  3. x = 5
  4. except:
  5. pass
  6. #ans: valid, x is 5

Exercises - Part 9

  1. # pass after return?
  2. def func():
  3. return 5
  4. pass
  5. #ans: valid but pass is unreachable

Exercises - Part 10

  1. # empty except with pass?
  2. try:
  3. x = 1 / 0
  4. except:
  5. pass
  6. #ans: error is silently caught

Google tag (gtag.js)