Skip to content
Python for Quantitative Finance / Control Flow and Simple Numerical Programs

Iteration: while and for Loops

Branching Programs and Boolean Logic closed on a genuine limitation: a program built only from conditionals runs in constant time and cannot process a portfolio, return series, or simulation whose size is not known until the program runs. Iteration removes that ceiling — with if and a loop, Python is Turing complete, meaning nothing this vault ever needs is beyond this pair of constructs; everything else is convenience. This note covers the two loop forms, while and for, the discipline of arguing a loop terminates (the decrementing function), and break as an early exit. Every algorithm in the rest of this topic — exhaustive enumeration, bisection search, Newton–Raphson — is a while loop with a carefully chosen termination test.
Learning objectives. By the end of this note you should be able to:
  • write a correct while loop and hand-simulate it to predict its output;
  • construct a decrementing function for a loop and use it to argue the loop terminates;
  • write a correct for loop over range and over a string, and explain when range's arguments are evaluated;
  • use break to exit a loop early, and explain why it only affects the innermost enclosing loop.

In this lesson

  1. The while loop
  2. Termination and the decrementing function
  3. The for loop
  4. Exiting early with break

Before you start

The full lesson, with worked examples and exercise solutions, is for members.

Read the full lesson

New to SelfMadeQuant.com? See membership options or browse the Python for Quantitative Finance syllabus.