Practice Function 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 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.

Like a recipe: you name it, write it once, and call it whenever you need it.

Showing a random 20 of 50 problems.

Example 1

medium
Trace: `def f(d, k): return d.get(k, 0)`. What is `f({'a':5}, 'b')`?

Example 2

medium
Trace: `def f(x, y): return x if x > y else y`. What is `f(3, 7)`?

Example 3

medium
Trace: `def f(x): return x.split(',')`. What is `f('a,b,c')`?

Example 4

easy
Trace: `def f(x): return x*x`. What is `f(4)`?

Example 5

medium
Trace closure: `def make_adder(k): def add(x): return x+k; return add; f=make_adder(10)`. What is `f(5)`?

Example 6

medium
Trace: `def f(a, b, c): return max(a, b, c)`. What is `f(3, 9, 5)`?

Example 7

challenge
Trace aliasing: `def f(d): d['x'] = 1; data = {}; f(data); print(data)`. What is printed and why?

Example 8

medium
Trace: `def f(): return 1; print('after')`. What does `f()` return, and does 'after' print?

Example 9

medium
Trace: `def f(x): x=x+1; return x` with `y=5; z=f(y)`. After the call, what are y and z?

Example 10

easy
Trace: `def f(a, b=10): return a+b`. What is `f(5, 2)`?

Example 11

easy
Fill in: a value passed at the call site of a function is called an ____.

Example 12

hard
Trace: `def f(lst): return sum(x for x in lst if x % 2 == 0)`. What is `f([1, 2, 3, 4, 5, 6])`?

Example 13

medium
Trace: `def f(lst): return [x*2 for x in lst]`. What is `f([1, 2, 3])`?

Example 14

easy
Trace: `def cube(x): return x*x*x`. What is `cube(3)`?

Example 15

easy
In `def greet(name): ...`, is `name` a parameter or an argument?

Example 16

challenge
Trace recursion with two base cases: `def f(n): return n if n<2 else f(n-1)+f(n-2)`. What is `f(6)`?

Example 17

easy
Fill in: a function with no explicit `return` statement in Python returns ____.

Example 18

hard
Trace scope and side-effects: `count = 0; def bump(): global count; count += 1; bump(); bump(); bump()`. What is `count`?

Example 19

easy
Trace: `def first(lst): return lst[0]`. What is `first([7, 8, 9])`?

Example 20

medium
Trace: `def f(n): return n*(n+1)//2`. What is `f(10)`?