Lesson 8 of 10

Writing functions

Goal

def, return and parameters

01

Explanation

A function is a set of steps you give a name because you need them more than once: you define it once with def, then call it wherever you like. A function takes its inputs through parameters and hands back its result with return, and return ends the function immediately.

You can give a parameter a default value. If you define def clamp(value, low=0, high=100), you can call it as just clamp(150) and the other parameters take their defaults. To change one particular parameter, name it: clamp(150, high=120), without writing low and without memorizing the parameter order.

The most common function mistake is printing the result instead of returning it. It looks right on the screen, but x = clamp(150) makes x equal None, because every function without a return returns None. Remember: print shows the result to you, and return hands it to the code that called the function.

02

Your task

Write the function clamp(value, low=0, high=100) so it returns value kept between the two bounds, the way a volume level or a progress percentage is held between a minimum and a maximum: anything below low becomes low, anything above high becomes high, and anything in between comes back unchanged.

Checks

5 checks
  1. Returns the value unchanged when it's between the bounds
  2. Anything below the lower bound becomes 0
  3. Anything above the upper bound becomes 100
  4. high can be passed by name
  5. low can be passed by name
03

Hints

0/3
Track lessons0 of 10 done

Start with the most beginner-friendly language there is, and use it to learn variables, strings, lists, conditions, loops and functions.

Beginner level, 10 lessons, 2 hours in total.

main.py
OutputPython (Pyodide)

Loading Python. This only happens once. Your browser keeps it after that.

–/5

Checks start once the environment is ready.

5 checks listed under “Your task”.

Track lessons0 of 10 done

Start with the most beginner-friendly language there is, and use it to learn variables, strings, lists, conditions, loops and functions.

Beginner level, 10 lessons, 2 hours in total.