Function Examples: 47 Problems with Answers
Worked examples of Function to try before you open each solution, then practice problems with answers.
Worked Examples
Example 1
mediumShow solution
Answer
First step
See the full worked solution + why-it-works coaching
SetupKey insightWhy it worksCommon pitfallConnection
Example 2
mediumExample 3
hardExample 4
hardPractice Problems
Try each one, then open the solution to compare your method.
Example 1
easyExample 2
easyExample 3
easyExample 4
easyExample 5
easyExample 6
easyExample 7
easyExample 8
easyExample 9
mediumExample 10
mediumExample 11
mediumExample 12
mediumExample 13
mediumExample 14
mediumExample 15
mediumExample 16
mediumExample 17
mediumExample 18
challengeExample 19
challengeExample 20
challengeExample 21
easyExample 22
easyExample 23
easyExample 24
easyExample 25
easyExample 26
easyExample 27
easyExample 28
mediumExample 29
mediumExample 30
mediumExample 31
mediumExample 32
mediumExample 33
mediumExample 34
mediumExample 35
mediumExample 36
mediumExample 37
mediumExample 38
mediumExample 39
hardExample 40
hardExample 41
hardExample 42
challengeExample 43
challengeWhat to focus on
Core idea: Functions break programs into manageable pieces, enable reuse, and reduce repetition.
Common stuck point: Defining a function doesn't run it — you must call it. Parameters (defined) differ from arguments (passed in).
Ask yourself: Are the same steps needed in more than one place or with different inputs, so they should be written once under a name?
Concept recap
A named, reusable block of code that performs a specific task and can optionally accept inputs (parameters) and return a result. Functions allow you to organize code into logical units, write a solution once, and invoke it from anywhere in the program.
A vending machine with a name on the front works like a function. You press a button with your choice (the argument), the same machinery inside does the work every time, and an item drops out (the return value); you never need to see inside to use it. The comparison stops at functions that only do a job, such as drawing a shape, and hand back nothing useful.
Read the full lesson on FunctionCommon mistakes to watch for
Background knowledge
These ideas may be useful before you work through the harder examples.