Functions & Scope · Question 18 · Hard
The recursive function below counts how many moves a number needs to reach 1 (halve if even, otherwise 3n + 1). What is printed for 6?
def steps(n):
if n == 1:
return 0
if n % 2 == 0:
return 1 + steps(n // 2)
return 1 + steps(3 * n + 1)
print(steps(6))
- 7
- 9
- 6
- 8
Answer and explanation
Answer: D. 8
Explanation: The chain is 6 → 3 → 10 → 5 → 16 → 8 → 4 → 2 → 1. That is 8 moves, and each recursive call adds 1 for one move.
Previous: A default parameter value refers to a module-level variable that is changed… · Next: Which statement about the nonlocal keyword in Python is correct?
Practise functions & scope
Try a fresh set of functions & scope questions with an explanation after every answer, free and without signing up: Functions & Scope practice. Or sit a full placement mock test.
More functions & scope questions
- A function signature mixes normal parameters, *rest and a keyword-only…
- The enclosing variable x is reassigned after the inner function is defined but…
- A default parameter value refers to a module-level variable that is changed…
- Which statement about the nonlocal keyword in Python is correct?
- Inside update, one list is changed with append and the other name is…
More python practice
Comprehensions & Generators · Classes & Objects · Exceptions & Files · Built-ins & Standard Library · Variables, Types & Operators · Python Strings · Lists & Tuples · Dictionaries & Sets
LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge