Start free

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

  1. Prime checkWrite a function is_prime(n) that returns True when n is a prime number (it hasIntermediate
  2. Greatest common divisorWrite gcd(a, b) with Euclid's method: while b is not 0, replace (a, b) withIntermediate
  3. Least common multipleWrite lcm(a, b), the smallest number both a and b divide into.Intermediate
  4. Primes up to nPrint all prime numbers up to and including n, on one line.Intermediate
  5. Perfect numberA number is perfect if it equals the sum of its divisors smaller than itself, likeIntermediate
  6. Fibonacci numberThe Fibonacci numbers start 0, 1 and each next one is the sum of the previous two:Intermediate
  7. Digital rootAdd up the digits of a number, then the digits of the result, and so on until oneIntermediate
  8. Temperature converterWrite two functions, c_to_f and f_to_c, and convert a temperature that comes withIntermediate
Start with “Prime check”