Skip to content

Latest commit

 

History

History
76 lines (54 loc) · 2.28 KB

File metadata and controls

76 lines (54 loc) · 2.28 KB

Pass Statement

The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action. For example:

while True:
    pass

That was an infinite loop!

pass is commonly used for creating minimal classes:

class MyEmptyClass:
    pass

Another place pass can be used is as a place-holder for a function or conditional body when you are working on new code, allowing you to keep thinking at a more abstract level. The pass is silently ignored:

def isPlayerAlive(*args):
    pass   # you'll program this later

Break Statement

Normally, a loop exits when its condition becomes false. But we can force the exit at any time using the special break statement.

def execute(c):
  pass

while (True):
  cmd = input("Enter a command? ")
  if (cmd == "exit"):
    break
  execute(cmd)

print("Exiting.")

Here, you are asking the user to type in a command. If the command is "exit", then quit the loop and output "Exiting", and end the program. Otherwise, execute the command and go around to the top of the loop and ask for another command.

Continue Statement

The continue statement doesn’t stop the whole loop. Instead, it stops the current iteration and forces the loop to start a new one (if the condition allows).

We can use it if we’re done with the current iteration and would like to move on to the next one. This loops prints odd number less than 10.

for i in range(1,10):
  # if true, skip the remaining part of the body
  # will only be true if the number is even
  if (i % 2 == 0):
    continue
  print(i) # prints 1, 3, 5, 7, 9

What’s interesting here is the use of the remainder operator (%) to see if a number is odd. The expression (i % 2) is zero if the number is even, if not, the number must be odd. You want to remember this trick of how to find odd or even numbers. It’s a common programming problem that you will get asked. The continue statement starts the loop over, not letting the print to print out the number when it’s even.

But you, being a newbie pythonista might say: 'yeah, but why not just use range(1,10,2) instead of all the IF and Modulo and continue??'

And me, being the crusty old instructor might say, 'Bah, Humbug!'