Loops

Back to main page

For loops

One way Python implements loops is through for. The syntax of for loops is:

for element in someCollection:
    STATEMENTS

That is, in Python, for loops can be (roughly) thought of transversals over ordered collections. As a concrete example, we will run the following program:

for name in ['Alice', 'Bob', 'Eve']:
    print(name)

This prints

Alice
Bob
Eve

Another classic example is to create a for loop of the following form:

for i in range(5):
    print(i)

This prints

0
1
2
3
4

While loops

Python also implements while loops via the following syntax:

while CONDITION:
    STATEMENTS

Compared to for loops, we typically use while loops when we do not know the exact number of iterations we will need. For instance, suppose we want to keep looping until the user tells the program they want it to quit:

userInput = ''
while userInput != 'quit':
    userInput = input('Type "quit" to exit the loop: ')

Back to main page

Exercises

  1. Write a function, using loops, that sums all of the elements of a list of integers.

  2. A well-known theorem of complex number theory is that \[\sum_{k=0}^{n-1} e^{2\pi i k/n} = 0\] for any positive integer \(n\). Numerically verify this theorem by writing a function roots_of_unity_sum(n) that returns this sum and ensuring that roots_of_unity_sum(n) is either 0 or very, very, very small for values \(n = 1, 2, \ldots, 100\).

  3. The Newton-Raphson method is an example of a root-finder algorithm: that is, it approximates solutions to \(f(x) = 0\). In particular, it is implemented by starting with an initial guess \(x_0\) and then computing steps \[x_{n+1} = x_n - \frac{f(x_n)}{f’(x_n)}.\] Implement the Newton-Raphson method and test it on the function \(f(x) = x^2 - 2\) with initial guess \(x_0 = 2\). Iterate until \(x_8\) is computed and print the result. If done correctly, one should obtain \(x_8 = 1.414213562373095 \approx \sqrt 2\).

  4. Write a function is_prime(n) that returns True if \(n\) is prime and False if not. (Hint: Notice that you only need to test for factors of \(n\) up to \(\sqrt n\). Why?)