GCSE · 8 exercises
Python functions
A function, made with def, gives a name to a piece of code, so it can be used again: its parameters are the values it is given, return hands an answer back.
A function that returns lets the caller decide what to do with the answer: print it, compare it, use it in a sum.
def is_even(n):
return n % 2 == 0
print(is_even(4))
print(is_even(7))Watch for: print inside a function is not return: the caller gets None. And the code after return in the same block never runs.
Exercises
- Prime checkWrite a function is_prime(n) that returns True when n is a prime number (it hasIntermediate
- Greatest common divisorWrite gcd(a, b) with Euclid's method: while b is not 0, replace (a, b) withIntermediate
- Least common multipleWrite lcm(a, b), the smallest number both a and b divide into.Intermediate
- Primes up to nPrint all prime numbers up to and including n, on one line.Intermediate
- Perfect numberA number is perfect if it equals the sum of its divisors smaller than itself, likeIntermediate
- Fibonacci numberThe Fibonacci numbers start 0, 1 and each next one is the sum of the previous two:Intermediate
- Digital rootAdd up the digits of a number, then the digits of the result, and so on until oneIntermediate
- Temperature converterWrite two functions, c_to_f and f_to_c, and convert a temperature that comes withIntermediate