Conditions & Loops · Question 15 · Medium
A while loop halves even numbers and applies 3n + 1 to odd numbers until n becomes 1. How many steps does it count for 10?
n = 10
steps = 0
while n != 1:
n = n // 2 if n % 2 == 0 else 3 * n + 1
steps += 1
print(steps)
- 5
- 7
- 4
- 6
Answer and explanation
Answer: D. 6
Explanation: The values go 10, 5, 16, 8, 4, 2, 1. That is six changes before n reaches 1, so steps is 6.
Previous: When does the else block attached to a for loop run? · Next: break appears inside the inner of two nested loops. Which pairs are collected?
Practise conditions & loops
Try a fresh set of conditions & loops questions with an explanation after every answer, free and without signing up: Conditions & Loops practice. Or sit a full placement mock test.
More conditions & loops questions
- The inner loop's range depends on the outer loop variable. How many times does…
- A helper function prints its argument each time it is called inside and / or…
- When does the else block attached to a for loop run?
- break appears inside the inner of two nested loops. Which pairs are collected?
- A while loop with an else clause tests whether 91 has a small divisor. What…
- The loop variable is changed inside the body of a for loop. What does this…
- Both conditions of this if-elif contain a division by x, and x is 0. What is…
- continue comes after the increment inside a while loop. What list is built?
More python practice
Functions & Scope · Comprehensions & Generators · Classes & Objects · Exceptions & Files · Built-ins & Standard Library · Variables, Types & Operators · Python Strings · Lists & Tuples
LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge