While loops

How to write a while loop

You need to determine two things:

  1. What’s your condition to stop the iteration
  2. What variables do you need to update the condition in each iteration (so you don’t fall into an infinite loop)

Example

Write a while loop to count how many years until you can run for president (simplistic example, for illustration purposes only):

def count_years(current_age, age_goal):
  years = 0
  age = current_age
  while age < age_goal:
    years += 1
    age += 1
  return years

def main():
  print( count_years(20, 35))
  
main()
15

.format() method

Let’s update our function so it returns a string message instead of an integer:

def count_years(current_age, age_goal):
  years = 0
  age = current_age
  while age < age_goal:
    years += 1
    age += 1
  message = "It will take {} years".format(years)
  message += " for you to be able to run for president."
  return message

def main():
  print( count_years(20, 35))
  
main()
It will take 15 years for you to be able to run for president.

Formatting numbers

Use : to specify formatting options,

amount = 10000000
print("I have ${:,} in my pocket.".format(amount))
I have $10,000,000 in my pocket.

Short Project

Instructions for Short Project of the Week