Count-controlled while loop

Tags
Summary

A while loop that runs a certain number of times.

Situation

You want to run some code repeatedly, a certain number of times.

Action

Typical code:

  • count = 0
  • while count < number of times - 1:
  •     Do something
  •     count += 1
Explanation

Number of times can be a constant, an input value... whatevs. For example, this code asks the user how many times to run the loop:

  • count = 0
  • num_times = input('How many times? ')
  • while count < num_times - 1:
  •     Do something
  •     count += 1

This code runs the loop for how many days there are in the current month. Run the code in January, and the loop body will run 31 times. Run it in February, and it will run either 28 or 29 times, depending on whether it's a leap year.

  • import calendar
  • import datetime
  • today_date = datetime.datetime.now()
  • num_days_this_month = calendar.monthrange(today_date.year, today_date.month)[1]
  • count = 0
  • while count < num_days_this_month - 1:
  •     Do something
  •     count += 1

You can also do this:

  • count = 1
  • while count <= num_days_this_month:
Where referenced