#!/usr/bin/env python # coding: utf-8 # # Week 1 Day 3 and Part 1 Exercise # # ## While-loops! # # The syntax for while loops is: # ```python # while : # # ``` # # As with `if` statements, the `` can be anything that evaluates to a boolean. The `` can be complex. # The body of the loop is repeated over and over again, as long as the `` is `True`. Once the condition is false, the loop stops, and whatever comes after the body is executed next. # --- # ### A1 Exercise # Look at the following code: # # ```python # i = 0 # while i < 5: # print("Hello World") # i += 1 # ``` # # How often is the loop body executed? Think about it before running the code. # In[ ]: # Try it out and put your answer here. # Look at the following code: # # ```python # 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. # In[ ]: # Try it out and put your answer here. # Look at the following code: # # ```python # 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. # In[ ]: # Try it out and put your answer here. # Look at the following code: # # ```python # 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. # In[ ]: # Try it out and put your answer here. # --- # ---### A2 Exercise # If we have a loop # ```python # while True: # # ``` # # How often is the loop body executed? # **Your answer here** # If we have a loop # ```python # while False: # # ``` # # 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. # In[ ]: 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[ ]: # --- # ### A3 Exercise: FIX THE CODE # 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. # In[ ]: # I want to print Hello World 5 times, then Goodbye i = 0 while i < 5 i += 1 print("Hello World") print("Goodbye") # In[ ]: # I want to print Hello World 5 times, then Goodbye i = 0 while i < 5: print("Hello World") i += 1 print("Goodbye") # In[ ]: # I want to print Hello World 5 times, then Goodbye i = 0 while i < 5: print("Hello World") i += 1 print("Goodbye") # In[ ]: # 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") # In[ ]: # I want to print Hello World 5 times, then Goodbye i = 0 while i > 5: i += 1 print("Hello World") print("Goodbye") # In[ ]: # I want to print Hello World 5 times, then Goodbye i = 0 while i < 5: i += 1 print("Hello World") print("Goodbye") # --- # ### A4 Exercise # Use a while loop to print the numbers between `0` to `10` (including both 0 and 10). # In[ ]: # 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! # In[ ]: # Use a while loop to print all powers of 2 less than 100. # In[ ]: # 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]` # In[ ]: # ### Example: More complicated while loop logic # # 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: # In[ ]: lst = [41, 2, 89, 50, 12, 13] i = 0 while i < len(lst): if lst[i] > 20: print(lst[i]) i += 1 # --- # ### A5 Exercise: # # 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 # In[ ]: # 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. # In[ ]: # --- # ### A6 Exercise # # 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[ ]: # --- # ### A7 Exercise: FIX THE CODE # 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. # In[ ]: # 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) # In[ ]: # 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) # In[ ]: # 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) # In[ ]: # --- # ### A8 Exercise # 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 # ``` # In[ ]: lst = [1, 7, 4, 5, 15, 2, 3, 6, 9, 12] # Your answer here # # Functions # ## Recap: Syntax for functions # # The general syntax for functions is: # ```python # def function_name(): # # return # ``` # # There are several things to note about the syntax (we will go through examples): # - You can have zero, one, or more arguments. # - You need the `:` after the function # - The body can be complex! # - You technically don't need a return statement at the end, but we will almost alway have a return at the end # --- # ### B9 Exercise # The 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. # In[ ]: 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. # In[ ]: 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. # In[ ]: 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. # In[ ]: print(area_square(2)) print(area_square(4)) print(area_square(12)) # You can also assign the returned value to a variable, for example: # In[ ]: x = area_square(4) # What is the value of `x`? # In[ ]: # --- # ### B10 Exercise # 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. # In[ ]: def perimeter_square(side_length): # INSERT YOUR CODE HERE print(perimeter_square(1)) print(perimeter_square(2)) print(perimeter_square(10)) # --- # ### B11 Exercise # 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. # In[ ]: # Define your function here! print(area_equilateral_triangle(1)) print(area_equilateral_triangle(2)) print(area_equilateral_triangle(10)) # --- # ### B12 Exercise # 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! # In[ ]: # 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: # In[ ]: area_circle(2) + area_circle(3) # Can you use your function to compute the area of the grey shape below? # # ![](disks.png) # In[ ]: # --- # ### B13 Exercise # 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! # # ![](shape.png) # In[ ]: # --- # ### B14 Exercise # 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! # In[ ]: # --- # ### B15 Exercise # 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! # In[ ]: 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! # In[ ]: # --- # ### B16 Exercise # 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! # In[ ]: # Use your function to compute the area of the following shape! # # ![](rect_shape.png) # In[ ]: # --- # ### B17 Example: More complicated functions # # 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`. # # ![](donut.png) # # Test this function for at least 5 different donuts! # In[ ]: 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! # --- # ### B18 Exercise # 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: # - a = 3, b = 4, c = 5 --> (You should get 6) # - a = 1, b = 1, c = $\sqrt{2}$ --> (You should get 0.5) # - a = 5, b = 6, c = 8 # - Test your code for a few more triangles! # In[ ]: # --- # ### B19 Example: Turning previous code into functions # Remember the code you wrote to round a number to the nearest integer: # # ```python # 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. # In[ ]: 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! # In[ ]: # --- # ### B20 Exercise # Remember the code you wrote to extract the last digit of a number: # # ```python # n = 3027184629834 # print(n % 10) # ``` # # Turn it into a function and test it on at least 10 numbers! # In[ ]: def last_digit(n): # Your code goes here! # --- # ### B21 Exercise # Remember the code from class that turns a numerical grade into a letter grade: # # ```python # 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! # In[ ]: # --- # In[ ]: # ### B22 Exercise # # 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 and a = 5 should give True # - n = 14 and a = 3 should give False # - n = 1 and a = 3 should give False # In[ ]: 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`. # In[ ]: 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. # In[ ]: # --- # ### Exercise (Hard 1) # 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. # In[ ]: # ### Exercise (Hard 2) # # The Collatz sequence of a number $n$ is defined as follows:
# - It starts with the number $a_0 = n$ itself # - If the $i$th number $a_i$ is even, then the next number $a_{i+1}$ is $\frac{a_i}{2}$ # - If the $i$th number $a_i$ is odd, then the next number $a_{i+1}$ is $3\cdot a_i + 1$ # - The sequence ends once you reach the number 1. # # 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! # In[ ]: