15-112 Fundamentals of Programming

Notes - Lecture 1.4


break and continue

The break statement breaks out of a loop. In the example below, once counter reaches n (counter == n), the break statement is executed, which then makes the program go to line 8.

def countToN(n):
    counter = 1       
    while(True):
        print(counter)
        if(counter == n):
            break
        counter += 1
    print("bye!")

The continue statement breaks out of the current iteration and skips to the next iteration. In the example above, in iterations where x is even (x % 2 == 0), the continue statement is executed, which makes the program go to the next iteration, i.e. it skips line 6.

def sumOfOddsToN(n):
    total = 0
    for x in range(1, n+1):
        if(x % 2 == 0):
            continue
        total += x
    return total

Optional parameters

# Below y is an optional parameter.
# When calling the function, if a second argument is given, that value
# will be assigned to y. If a second argument is not given, by default,
# y will be assigned the value 10.  
def f(x, y=10): 
    return x+y

print(f(5))   # prints 15
print(f(5,6)) # prints 11

Examples covered in class

  • Computing square root using Newton's method.
  • Approximating the prime-counting function.
  • walkThroughDigits
  • digitCount
  • largestDigit
  • countOfMostFreqDigit
  • mostFreqDigit
  • isSubnumber
  • longestDigitRun
  • isRotation
  • nthPalindromicPrime


  • Valid CSS! Valid XHTML 1.0 Strict