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
whileloop 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
forloop overrangeand over a string, and explain whenrange's arguments are evaluated; - use
breakto exit a loop early, and explain why it only affects the innermost enclosing loop.
In this lesson
- The while loop
- Termination and the decrementing function
- The for loop
- Exiting early with break
Before you start
The full lesson, with worked examples and exercise solutions, is for members.
Read the full lessonNew to SelfMadeQuant.com? See membership options or browse the Python for Quantitative Finance syllabus.