Lecture 4

Last time: We talked about if-else. I forgot to tell you about the in-line if-else:

In [1]:
x = 0 if True else 1
print(x)
0
In [2]:
x = 0 if True else 1
print(x)
0

Today:

  • While loops. While loops. While loops. While loops. While loops. While loops. While loops. While loops. While loops. While loops. While loops. While loops. While loops. ...


While loops

Very clever way to repeat actions. Syntax:

`while CONDITION FOR DOING THE NEXT ITERATION OF THE LOOP: STUFF THAT WILL BE REPEATED IN EVERY ITERATION

In [3]:
x = 0
while x<10:
    print(x)
    x = x + 1
0
1
2
3
4
5
6
7
8
9

Shortcut: Instead of writing x = x + 1, we can write x += 1. So cool.

In [4]:
# Let's use the cool shortcut while doing something a little more nice
# sum of first 100 numbers:
x = 1
total = 0
while x<=100:
    total += x
    x = x + 1
    
print(total)
5050

What you need to do is to read the code and run it yourself, step by step, in your head and/or paper.

The condition must be True for the loop to run the first time

In [5]:
# there will be no output from this
while False:
    print("This line will never print")

If the condition is always true, then you get an infinite loop!

In [ ]:
# DON'T RUN (or be ready to press stop)
x = 0
while x == 0:
    print("All work and no play makes Jack a dull boy.")

Indentation is important to see what is in the loop:

In [ ]:
# Don't run this or be ready to press stop. Why does it do an infinite loop?
x = 0
while x<10:
    print(x)
x = x + 1

The unindented part is not within the loop, so x is never icreased during the loop. So x<10 is always True, and the loop never ends.

Checking for primeness

We want to write a function called isprime that checks if a number is prime. Returns True if number is prime, False otherwise.

Again, either try to write it yourself, or look through the code and run it in your head/on-paper.

In [6]:
def isprime(n):
    if n <= 1:
        return False
    d = 2
    while d<n:
        if n % d  == 0:
            return False
        d += 1
    return True
In [7]:
isprime(5)
Out[7]:
True
In [8]:
isprime(7)
Out[8]:
True
In [9]:
isprime(57)    # it's 3x19
Out[9]:
False

Can we make this more efficient? Yes, we don't need to check all the way up to n-1, we could actually check up to $\sqrt{n}$ because if there is a factor larger than $\sqrt{n}$, then there is also a factor smaller than $\sqrt{n}$, namely $\frac{n}{\sqrt{n}}$.

In [10]:
def isprime(n):
    if n <= 1:
        return False
    d = 2
    while d*d<=n:    # so clever!!!
        if n % d  == 0:
            return False
        d += 1
    return True



Good exercises:

  • Using while loops, implement the integer division function // as division(a,b). Make sure you are doing the negative number examples correctly.
  • Write a loop to print the first 100 prime numbers.
  • Estimate pi by adding the first 1000 terms in the formula: $$\pi/4 = 1 - 1/3 + 1/5 - 1/7 + ...$$ compare the answer to the built-in math.pi. (by the way, this comes from the Taylor expansion of arctan)