The syntax for while loops is:
while <condition>:
<body>
As with if
statements, the <condition>
can be anything that evaluates to a boolean. The <body>
can be complex.
The body of the loop is repeated over and over again, as long as the <condition>
is True
. Once the condition is false, the loop stops, and whatever comes after the body is executed next.
Look at the following code:
i = 0
while i < 5:
print("Hello World")
i += 1
How often is the loop body executed? Think about it before running the code.
# Try it out and put your answer here.
Look at the following code:
i = 0
while i < 10:
print("Hello World")
i += 1
How often is the loop body executed now? Think about it before running the code.
# Try it out and put your answer here.
Look at the following code:
i = 6
while i < 10:
print("Hello World")
i += 1
How often is the loop body executed now? Think about it before running the code.
# Try it out and put your answer here.
Look at the following code:
i = 0
while i < 10:
print("Hello World")
i += 3
How often is the loop body executed now? Think about it before running the code.
# Try it out and put your answer here.
---### A2 Exercise
If we have a loop
while True:
<body>
How often is the loop body executed?
Your answer here
If we have a loop
while False:
<body>
How often is the loop body executed?
Your answer here
Try running the code below and see what happens.
IMPORTANT: If your code does not stop running and has an [*]
on the left, it is in an infinite loop. To get out of this loop, in the top menu, select Kernel -> Interrupt, or press the black square button in the top menu bar.
i = 0
while True: # Line 2
i += 1
print(i)
How often is the body (i += 1
) executed?
You answer here.
What would the output be if you change Line 2 to while False:
? How often is the body (i += 1
) executed now?
You answer here.
In each of the following code snippets, there is a mistake. Find it and fix it!
Suggestion: First run the code and look at the error message. Fix it and run it again.
# I want to print Hello World 5 times, then Goodbye
i = 0
while i < 5
i += 1
print("Hello World")
print("Goodbye")
# I want to print Hello World 5 times, then Goodbye
i = 0
while i < 5:
print("Hello World")
i += 1
print("Goodbye")
# I want to print Hello World 5 times, then Goodbye
i = 0
while i < 5:
print("Hello World")
i += 1
print("Goodbye")
# I want to print Hello World 5 times, then Goodbye
# CAREFUL: This will print a lot of stuff, so kill it quickly with the black square square button!
i = 0
while i < 5:
print("Hello World")
i + 1
print("Goodbye")
# I want to print Hello World 5 times, then Goodbye
i = 0
while i > 5:
i += 1
print("Hello World")
print("Goodbye")
# I want to print Hello World 5 times, then Goodbye
i = 0
while i < 5:
i += 1
print("Hello World")
print("Goodbye")
Use a while loop to print the numbers between 0
to 10
(including both 0 and 10).
Use a while loop to print the even numbers between 0
to 10
(including both 0 and 10).
Hint: you do this by changing only one symbol from the previous answer!
Use a while loop to print all powers of 2 less than 100.
Print all the numbers in this list using a while
loop: [41, 2, 89, 50, 12, 13]
Hint: Use a number i
that goes from 0 to 5, and get the list elements like myList[i]
We can have more complicated logic inside the loop, like if
statements.
The following code prints all numbers from the list which are greater than 20:
lst = [41, 2, 89, 50, 12, 13]
i = 0
while i < len(lst):
if lst[i] > 20:
print(lst[i])
i += 1
Print all the even numbers in this list using a while
loop: [41, 2, 89, 50, 12, 13]
Hint: Use an if
statement inside your while
loop
Use a while loop to print all numbers from 1 to 99 where the last digit is 3 or 7 (e.g. 23 will be printed but not 24).
Hint: Remember how to get the last digit of a number?
Hint: Use an if
statement inside your while
loop, and or
inside your condition.
When computing 1+2+3+4+..., how many numbers do you need to sum up so that the sum exceeds 1000?
Hint: Use a while loop.
In each of the following code snippets, there is a mistake. Find it and fix it!
Suggestion: First run the code and look at the error message. Fix it and run it again.
# I want to sum up the first 10 square numbers,
# but the loop just runs infinitely.
i = 1
summ = 0
while i <= 10:
summ += i**2
print(summ)
# I want to add (and print) the first few numbers until their sum exceeds 100.
# but nothing is being printed
total = 0
i = 1
while total >= 100:
total += i
i += 1
print(i)
# I want to print the first number in my list that's bigger than 10.
# But the answer I get, 5, is certainly not bigger than 10.
myList = [1,3,9,5,-1,13,5,11,2]
number = 0
while myList[number] <= 10:
number += 1
print(number)
Use a while loop to keep printing numbers in a list until you find a number greater than 10
.
For example, given this list
lst = [1, 7, 4, 5, 15, 2, 3, 6, 9, 12]
Your program should print
1
7
4
5
lst = [1, 7, 4, 5, 15, 2, 3, 6, 9, 12]
# Your answer here
The general syntax for functions is:
def function_name(<arguments>):
<body>
return <expression>
There are several things to note about the syntax (we will go through examples):
:
after the functionThe following function computes the area of a square. Its argument is the side_length of the square, and it returns the area of the square.
def area_square(side_length):
return side_length**2
The cell above only defines the function. If you run the cell, nothing happens yet.
We can call the function by giving it a side length as an argument, and it will return (give back) the area.
In the example below, we compute the area of a square of side length 3.
def area_square(side_length):
return side_length**2
area_square(3)
You can use this function and compute the areas of squares of any side length. We use the print
function to print the outputs.
def area_square(side_length):
return side_length**2
print(area_square(3))
print(area_square(5))
print(area_square(10))
Jupyter remembers the definition of a function, so you don't need to do def area_square(...)
each time.
print(area_square(2))
print(area_square(4))
print(area_square(12))
You can also assign the returned value to a variable, for example:
x = area_square(4)
What is the value of x
?
The perimeter of a squares of side length $a$ is $4a$. Fill in the code below to define a function that takes a side length as argument and returns the perimeter of a square of that side length. Then use this function to compute the perimeters for side length 1, 2 and 10.
def perimeter_square(side_length):
# INSERT YOUR CODE HERE
print(perimeter_square(1))
print(perimeter_square(2))
print(perimeter_square(10))
The area of an equilateral triangle of side length $a$ is $3^{0.5}/4*a^2$. Write a function called area_equilateral_triangle
that takes a side length as argument and returns the area of an equilateral triangle of that side length. Use it to compute the areas for side length 1, 2 and 10.
# Define your function here!
print(area_equilateral_triangle(1))
print(area_equilateral_triangle(2))
print(area_equilateral_triangle(10))
Write a function named area_circle
that computes the area of a circle with a given radius. It should take a radius
as argument and return the area.
Use your function to compute the areas of circles of radius 1, 3 and 9!
You can also take the function output and do computations with it. For example, if you want to compute the sum of the area of two circles, you can do:
area_circle(2) + area_circle(3)
Can you use your function to compute the area of the grey shape below?
Use the function area_circle
, area_equilateral_triangle
and area_square
to compute the area of the shape below, assuming all the straight lines have length 5!
Write a function that computes the circumference of a circle with a given radius. It should take a radius
as argument and return the circumference.
Use your function to compute the circumference of circles of radius 1 and 5! Compute the area of at least 3 more circles!
Functions can take multiple arguments. Let's define a function that computes the perimeter of a rectangle, given its height and length. Fill in the code below.
Then use your function to compute the perimeters of a 2x3 and 3x5 rectangle!
def perimeter_rectangle(length, height):
# INSERT YOUR CODE HERE
print(perimeter_rectangle(2, 3))
print(perimeter_rectangle(3, 5))
Use your function to compute the perimeters of a 6x8, 4x1 and 5x3 rectangle!
Define a function area_rectangle
that computes the area of a rectangle, given its height and length.
Then use your function to compute the areas of a 2x3 and 4x1 rectangle! Compute the area of at least 3 more rectangles!
Use your function to compute the area of the following shape!
The computations inside of functions can be more complicated, and the body can consist of multiple lines. You only need one return statement. Consider the function below computing the area of a donut with inner radius r_inner
and outer radius r_outer
.
Test this function for at least 5 different donuts!
def area_donut(r_inner, r_outer):
area_outer = 3.14*r_outer**2
area_inner = 3.14*r_inner**2
return area_outer - area_inner
# Try it out for at least 5 different donuts!
Write a function area_triangle
that computes the area of a triangle with side lengths a
, b
and c
. You can use the Heron formula.
First compute the half-perimeter $$s = \frac{a+b+c}{2}$$
Then compute the area as $$\sqrt{s(s-a)(s-b)(s-c)}$$
Compute the area for:
Remember the code you wrote to round a number to the nearest integer:
n = 12.6
decimals = n - int(n)
if decimals >= 0.5:
print(int(n)+1)
else:
print(int(n))
Functions are really useful to test such code on many numbers at once!
Let's turn this into a function. Note how all of the code gets indented (pushed to the right), and how it is possible to have multiple return
statements.
def round(n):
# We remove the n = 12.6 here, because n is now a function argument
decimals = n - int(n)
if decimals >= 0.5:
return int(n)+1 # return instead of print
else:
return int(n) # return instead of print
# Let's test our function!
print(round(1.2))
print(round(12.6))
print(round(0.5))
Test this function on at least 5 more numbers!
Remember the code you wrote to extract the last digit of a number:
n = 3027184629834
print(n % 10)
Turn it into a function and test it on at least 10 numbers!
def last_digit(n):
# Your code goes here!
Remember the code from class that turns a numerical grade into a letter grade:
numeric_grade = 75
if numeric_grade > 90:
letter_grade = 'A'
elif numeric_grade > 80:
letter_grade = 'B'
elif numeric_grade > 70:
letter_grade = 'C'
elif numeric_grade > 60:
letter_grade = 'D'
else:
letter_grade = 'F'
Write a function which does this, and test it on 10 different grades!
We want to define a function that checks if a number is prime.
What is the definition of a prime? In your own words, how would you check if a number is a prime?
Your answer here
In python, how do you check if a number n
is divisible by another one (%
operator)?
n = 10
a = 5
# Write an expression here that is True if a divides n and False otherwise!
Write a function that checks if a number is prime!
Hint: To test if a number n
is prime, you can check if n
is divisible by any the number smaller than itself. You use a while
loop to go through all the numbers smaller than n
. If you find a number that divides n
then n
is not prime.
Hint: Whenever you find a number that divides n
, return False
. If you finish the while loop, return True
.
def is_prime(n):
# Your code here
print(is_prime(7)) # Should print True
print(is_prime(4)) # Should print False
print(is_prime(27)) # Should print False
print(is_prime(997)) # Should print True
print(is_prime(2)) # Should this print True or False?
Write a program to print all prime numbers smaller than 100. You should use is_prime()
defined above.
The Fibonnaci sequence is defined as follows: The first two elements in the sequence f(0)
and f(1)
are equal to 1
. For every n>1
, the n
-th element in the sequence is $$f(n)=f(n-1)+f(n-2).$$
Use a while loop to write a code that prints out all the Fibonnaci numbers less than 10000.
The Collatz sequence of a number $n$ is defined as follows:
Example: for the number 12, the sequence is: 12, 6, 3, 10, 5, 16, 8, 4, 2, 1.
The Collatz conjecture says that whichever number you start with, you'll always reach 1 at some point.
Define an integer variable n
and then use a while
loop to print out its Collatz sequence!