Lecture 11 – Iteration, Part III (while)

Data 6, Summer 2021

Motivating demos

Let's try something cool!

While loop fundamentals

Example: sum_first_n

Example: sum_first_n_no_threes

Quick Check 1

More Examples

Fibonacci sequence

$$0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...$$

It turns out there's a formula that we can use to compute the $n$-th Fibonacci number, without iteration:

$$F_n = \frac{\phi^{n} - (1 - \phi)^{n}}{\sqrt{5}}$$

where $\phi = \frac{1 + \sqrt{5}}{2}$ is the "Golden Ratio".

Prime factorization

Let's first define smallest_factor, a function that takes in a positive integer n and returns the smallest factor of n. (This number is prime!)

Now, let's define prime_factors, a function that takes in a positive integer n and prints all of the prime factors of n.

While vs. for

Dictionary Demo

User Input