Practice Function (Programming) in CS Thinking

Use these practice problems to test your method after reviewing the concept explanation and worked examples.

Quick Recap

A named, reusable block of code that performs a specific task, taking input (parameters) and optionally returning output (a return value). Functions allow you to write a piece of logic once and use it many times throughout a program.

A mini-program with a name. Call it by name whenever you need that task done.

Showing a random 20 of 50 problems.

Example 1

easy
A function is defined as `def greet(): print("hi")`. The program never prints anything. Why?

Example 2

easy
In `def add(x, y): return x + y`, what are `x` and `y` called?

Example 3

easy
`def f(): pass`. What does `f()` return?

Example 4

medium
Why might using a function be safer than copying the same 6-line block 5 times across a program?

Example 5

hard
`def f(n): if n<2: return n; return f(n-1) + f(n-2)`. What is `f(6)`? (Fibonacci with f(0)=0,f(1)=1)

Example 6

medium
What prints? `def f(): return 1` then `print(f)`

Example 7

easy
What is the output of `def f(): print("A"); return; print("B")` when called?

Example 8

easy
`def triple(n): return n * 3`. What is `triple(4)`?

Example 9

easy
`def f(): print('A'); print('B')`. Calling `f()` prints what?

Example 10

medium
A function should return the larger of two numbers. `def big(a,b): if a > b: return a` is buggy. What does `big(2, 5)` return?

Example 11

medium
Define a function `double(n)` that returns n ร— 2. Then trace `double(double(3))`.

Example 12

medium
`def f(a, b=10): return a + b`. What does `f(5)` return?

Example 13

hard
`def f(lst): lst.append(99)` is called with `data=[1,2,3]; f(data)`. What is `data` afterward?

Example 14

easy
In `def area(w, h): return w * h`, what are `w` and `h` called?

Example 15

easy
Does `def f(): x = 10` make `x` usable outside the function after calling `f()`?

Example 16

medium
`def f(): x = 10; return x` and `print(x)` after the call. What happens?

Example 17

challenge
A function `f(lst)` appends to `lst` and is called with the same list 3 times. Why might results surprise you?

Example 18

easy
Why use a function instead of copying the same 5 lines of code three times?

Example 19

medium
`def f(x): return x; print('done')`. When called, what is printed by the function body?

Example 20

medium
`def f(n): return n + 1` and `def g(n): return n * 3`. What is `g(f(2))`?