Exercises
While Loops
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
Print 0, 1 and 2 with a while loop.
Python
count = 0
# loop while count is under 3
Remember to change count inside the body.
count = 0
while count < 3:
print(count)
count += 1Exercise 2Passed
How many years at 10% growth does it take for 100 to pass 150? Print the number of years.
Python
balance = 100
years = 0
# grow until balance is at least 150
print(years)You cannot write this as a for loop without knowing the answer first.
balance = 100
years = 0
while balance < 150:
balance *= 1.1
years += 1
print(years)Exercise 3Passed
This loop never ends. Fix it so it prints 1, 2 and 4 and stops.
Python
n = 0
while n < 5:
if n == 3:
continue
n += 1
print(n)continue jumps straight back to the condition, so the increment must come before it.
n = 0
while n < 5:
n += 1
if n == 3:
continue
print(n)