Loops

Loops let you execute code over and over.

Basic Loops

Predict

What will this code do?


In [ ]:
for i in range(10):
    print(i)

In [ ]:
for i in range(15):
    print(i)

Summarize

What does the range function do?

Modify

Change the cell below so it prints all $i$ between 0 and 20.


In [ ]:
for i in range(11):
    print(i)

Implement

Write a loop that calculates the sum:

$$ 1 + 2 + 3 + ... + 1001$$

In [ ]:

Loops with conditionals

Predict

What will this code do?


In [ ]:
for i in range(10):
    if i > 5:
        print(i)

Modify

Change the code below so it goes from 0 to 20 and prints all i less than 8.


In [ ]:
for i in range(10):
    if i > 5:
        print(i)

Predict

What will this code do?


In [ ]:
for i in range(10):
    if i > 5:
        break
    print(i)

Summarize

What does the break keyword do?

Predict

What will this code do?


In [ ]:
for i in range(10):
    print("HERE")
    if i > 5:
        continue
    print(i)

Summarize

What does the continue keyword do?

Implement

Write a program that starts calculating the sum:

$$1 + 2 + 3 + ... 100,000$$

but stops if the sum is greater than 30,000.


In [ ]:
x = 0
for i in range(1,100001):
    x = x + i
    if x > 30000:
        break

While loops

Predict

What will this code do?


In [ ]:
x = 1
while x < 10:
    print(x)
    x = x + 1

Predict

What will this code do?


In [ ]:
x = 1000
while x > 100:
    print(x)
    x = x - 10

Summarize

How does while work?

Modify

Change the following code so it will print all values of $x^2$ for $x$ between 5 and 11.


In [ ]:
x = 0
while x < 20:
    print(x*x)
    x = x + 1

Implement

Use a while loop to print sin(x) for x $\in$ [$0$, $\pi/4$, $\pi /2$, $3 \pi /4$... $2 \pi$].


In [ ]:

Summary

There are two basic types of loops in python:

for i in range(10):
    print(i)
i = 0
while i < 10:
    print(i)
    i = i + 1

Extra Exercises

  • Write a loop that calculates a Riemann sum for $x^2$ for $x \in [-5,5]$.
  • Write a loop that prints every 5th number between 1 and 2000.
  • What will the following program print out?
for i in range(100):
    if i < 10:
        print(i)

    if not (i < 10):
        print(-1*i)

In [ ]: