Exercise Notebook 4 - Debugging

Exercise Notebook 4 - Debugging#

You can download this notebook and the additional files by clicking the download button() in the top right and selecting “Exercise notebook”.

Exercise 4.1

Write a function that determines if its argument is a prime number.
  • Hint 1: an integer \(n\) is prime if \(n > 1\) and \(n\) is not divisible by any smaller integer \(> 1\)

  • Hint 2: divisibility can be tested with the % operator. If n % i is \(0\), n is divisible by i.

def is_prime(n):
    """ 
    Check if a number is prime. The input argument n must be a positive integer.
    The function returns True if n is prime, and False otherwise.
    """
    ...
Exercise 4.2

Use your is_prime() function to create a list of all primes \(< 1000\). What is the sum of all primes \(< 1000\)?

Hint: you will need a for loop to fill the list.

prime_list = ...
prime_sum = ...

print(f'List of primes: {prime_list}\n')
print(f'Sum of primes: {prime_sum}')
(Fixing) Exercise 4.3

Fix the syntax errors so it prints "EC&T" without removing the variable that holds it. You'll need to fix 2 errors.
def get_abbreviation():
    my abbreviation = "EC&T"
     return my_abbreviation
        
print(get_abbreviation())
(Fixing) Exercise 4.4

The factorial n! is defined as n! = n * (n - 1) * (n - 2) * … * 2 * 1. The function uses the fact that if n > 0, n! = n * (n - 1)!. This is an example of a recursive function, a function that calls itself.

The code below calls the function factorial with the number 4 as input. The factorial of 4 is \(4 \cdot 3 \cdot 2 \cdot 1 = 24\), but the code below prints 262144. Find and fix the error in this function. What kind of error is this (syntax, runtime, semantic)?

def factorial(x):
    "returns the factorial of x"
    if x == 0:
        return 1
    else: 
        return x ** factorial(x-1)

factorial(4)