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)
  1. 5
  2. 7
  3. 4
  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

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