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”.
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. Ifn % iis \(0\),nis divisible byi.
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.
"""
...
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}')
"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())
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)