This article gives you five code puzzles to help you master basic looping in Python.
- If you are a Python expert, you solve all of them without even the slightest mistake.
- If you are a Python intermediate, you make one or two mistakes.
- If you are a Python beginner, you should get at least one right.
Have a look at your clock: 5-minutes starting now… Go, go, go!
Puzzle 1: While Loop Changing Values Dynamically
The while loop can be used to repeat a certain behavior until a variable meets a certain condition.
n = 16 x = 0 while x < 3: n /= 2 x += 1 print(n)
What’s the output of this code snippet?
Solve the puzzle on the interactive puzzle app (Finxter.com website).
Puzzle 2: Lambda Function and Range
This puzzle tests your understanding of two concepts: the lambda function and the built-in range()
function.
inc = lambda x: x + 1 for i in range(2, 3): print(inc(2))
What’s the output of this code snippet?
Solve the puzzle on the interactive puzzle app (Finxter.com website).
Puzzle 3: While … Else Branch
Next, you’ll explore a strange Python feature: the else branch … of a while loop!
index = 5 string = 'g' while index > 3: index -= 1 string += 'o' else: string += 'd' print(string)
What’s the output of this code snippet?
Solve the puzzle on the interactive puzzle app (Finxter.com website).
Puzzle 4: While … Else Branch 2
index = 5 string = 'g' while index > 3: index -= 1 string += 'o' if index == 3: break else: string += 'd' print(string)
What’s the output of this code snippet?
Solve the puzzle on the interactive puzzle app (Finxter.com website).
Puzzle 5: While … Else Branch 3
index = 5 string = 'g' while index > 3: index -= 1 if index == 3: continue string += 'o' else: string += 'd' print(string)
What’s the output of this code snippet?
Solve the puzzle on the interactive puzzle app (Finxter.com website).
Solutions
How many puzzles have you solved correctly? Here are the correct solutions:
- Puzzle 1: 2.0
- Puzzle 2: 3
- Puzzle 3: good
- Puzzle 4: goo
- Puzzle 5: god
If you have solved at least four puzzles correctly, you belong to the top 20% of Python coders.
Related Video: Loop … Else
Do you want to master even advanced concepts of Python loops? Watch my short explainer video on the meaning of the else branch of a Python loop.
You can solve more puzzles and download your Python cheat sheets in my free email academy: