A while loop repeats its body as long as a condition stays True:
n = 1
while n <= 4:
print(n)
n += 1
Output:
1
2
3
4
The condition is checked before every pass. When n reaches 5, the check fails and the loop ends.
Use for when you know what to loop over — a list, a range. Use while when you only know the stopping condition:
def divide_until_small(n):
steps = 0
while n > 1:
n = n // 2
steps += 1
return steps
How many passes this makes depends on n — a for loop cannot express that directly.
Something in the body must move the condition toward False. If nothing does, the loop never ends and the program hangs — this editor stops runaway code after 10 seconds.
An account earns 5% interest per year: each year the balance is multiplied by 1.05.
years_to_reach with two parameters: balance and target.balance to reach or pass target. Use a while loop.balance already meets the target, return 0.years_to_reach(1000, 1100) returns 2 — after one year the balance is 1050.0, after two 1102.5.
Run your code to see the output, then press Submit.
import unittest
class TestYearsToReach(unittest.TestCase):
def test_1000_to_1100_takes_2_years(self):
self.assertEqual(years_to_reach(1000, 1100), 2)
def test_already_at_target_takes_0_years(self):
self.assertEqual(years_to_reach(500, 500), 0)
def test_1000_to_2000_takes_15_years(self):
self.assertEqual(years_to_reach(1000, 2000), 15)
def years_to_reach(balance, target):
years = 0
while balance < target:
balance = balance * 1.05
years += 1
return years
print(years_to_reach(1000, 1100))
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.