Editor

Power of 2 Finder

Beginner · Write the code · from Python While Loops: When For Loops Aren't Enough

From the lesson: Python While Loops: When For Loops Aren't Enough

A vending machine doesn't know how many coins you'll insert. It just keeps waiting: "while the total is less than the price, keep accepting coins." It can't use a for loop because it doesn't know the number of iterations in advance. It needs a while loop.

Read the lesson

Starting from 1, keep doubling a number until it exceeds 500. Print each value as you go (including the first value that exceeds 500). Then print the final result.

Expected output:

1
2
4
8
16
32
64
128
256
512
First power of 2 over 500: 512

Hint: use a while True loop with a break after the value exceeds 500.

value = 1
# Keep doubling and printing until value exceeds 500

More While Loops exercises

All Python exercises · 50 practice problems · Control Flow quiz