Home      |       Contents       |       About

Prev: - 'if' control       |       Next: 'for' loop

break, continue & pass

break

  • The 'break' command is used to unconditionally exit a loop.
  • A typical use of 'break' is to call it and exit a loop when a condition is True. In its general form this code might be as follows:

      while condition-1:  
          block-1     
          if condition-2:  
              break      
      else:    
          block-2
  • In the above example when condition-2 is True the 'break' command transfers the flow outside the 'while' command (the 'else' branch is NOT executed in this case)

  • Although break carries a bit of 'go to' taste, however it fits well to structured programming as it tranfers the flow specifically to the end of the loop and nowhere else.

Example: break a 'while' loop

In [6]:
# 'break' exits the endless while loop when i equals x
x = int(input('Enter an integer in [1,10]:'))
asum = i = 0

while True:
    i += 1
    asum += i
    if i == x:
        break

print(asum)
    
Enter an integer in [1,10]:11
66

continue

  • The 'continue' command transfers flow unconditionally to the beginning of a loop bypassing all following code.
  • A typical use of 'continue' is to check whether a condition is True and transfer the flow to the beginning of the loop.
  • In its general form this code might be as follows:

      while condition-1:  
          block-1     
          if condition-2:  
              continue  
          block-2     
      else:    
          block-else
  • In the above example code when condition-2 is True the 'continue' command transfers the flow to the beginning of the 'while' loop: the 'block-2' code is NOT executed in this case

Example: continue in a 'while' loop

In [11]:
# calculating sums of integers

num = int(input('Please enter an integer number in [1,100]:'))
totsum = oddsum = i = 0

while True:
    i += 1 
    if i > num: break
    totsum += i
    if i%2 == 0: continue
    oddsum += i

print('Max number added:',i-1,
      'Sum of all numbers:',totsum,
      'Sum of odd numbers:',oddsum)
    
Please enter an integer number in [1,100]:10
Max number added: 10 Sum of all numbers: 55 Sum of odd numbers: 25

pass

  • The 'pass' command is a 'nothing to worry about' command
  • You simply put 'pass' in places where you don't really know what the final code will be, BUT you want it to be syntactically correct in order to check other parts of your code
  • See the example that follows:
In [12]:
# 'pass' your code!

key = -2

if key > 0:
    print('key is positive!')
else:
    pass    # I don't know what the 'else' branch will finally do but the code runs smoothly

. Free learning material
. See full copyright and disclaimer notice