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
mediumTrace: `def f(d, k): return d.get(k, 0)`. What is `f({'a':5}, 'b')`?
Example 2
mediumTrace: `def f(x, y): return x if x > y else y`. What is `f(3, 7)`?
Example 3
mediumTrace: `def f(x): return x.split(',')`. What is `f('a,b,c')`?
Example 4
easyTrace: `def f(x): return x*x`. What is `f(4)`?
Example 5
mediumTrace closure: `def make_adder(k): def add(x): return x+k; return add; f=make_adder(10)`. What is `f(5)`?
Example 6
mediumTrace: `def f(a, b, c): return max(a, b, c)`. What is `f(3, 9, 5)`?
Example 7
challengeTrace aliasing: `def f(d): d['x'] = 1; data = {}; f(data); print(data)`. What is printed and why?
Example 8
mediumTrace: `def f(): return 1; print('after')`. What does `f()` return, and does 'after' print?
Example 9
mediumTrace: `def f(x): x=x+1; return x` with `y=5; z=f(y)`. After the call, what are y and z?
Example 10
easyTrace: `def f(a, b=10): return a+b`. What is `f(5, 2)`?
Example 11
easyFill in: a value passed at the call site of a function is called an ____.
Example 12
hardTrace: `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
mediumTrace: `def f(lst): return [x*2 for x in lst]`. What is `f([1, 2, 3])`?
Example 14
easyTrace: `def cube(x): return x*x*x`. What is `cube(3)`?
Example 15
easyIn `def greet(name): ...`, is `name` a parameter or an argument?
Example 16
challengeTrace 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
easyFill in: a function with no explicit `return` statement in Python returns ____.
Example 18
hardTrace scope and side-effects: `count = 0; def bump(): global count; count += 1; bump(); bump(); bump()`. What is `count`?
Example 19
easyTrace: `def first(lst): return lst[0]`. What is `first([7, 8, 9])`?
Example 20
mediumTrace: `def f(n): return n*(n+1)//2`. What is `f(10)`?