get consultation

While

The while statement is used to execute code many times.

while.py
count = 0

while count < 5:
    count = count + 1
    print(count)

print("Done.")

Output:

1
2
3
4
5
Done.

NOTE: Don't forget to increment count otherwise the loop will never stop. This is called an infinite loop.

The following program prints the 2 times table.

times_table.py
count = 0

while count < 5:
    count = count + 1
    print(count, "* 2 is", count * 2)

print("Done.")

Output:

1 * 2 is 2
2 * 2 is 4
3 * 2 is 6
4 * 2 is 8
5 * 2 is 10
Done.

Links

Exercises (5 mins)

  1. Take the times_table.py and do the 3 times table.

    Output:

    1 * 3 is 3
    2 * 3 is 6
    3 * 3 is 9
    4 * 3 is 12
    5 * 3 is 15
    Done.
    
  2. Take the times_table.py and do the calculation for any number.

    Output:

    Enter a number:4
    1 *  4  is 4
    2 *  4  is 8
    3 *  4  is 12
    4 *  4  is 16
    5 *  4  is 20
    Done.
    
    Enter a number:5
    1 *  5  is 5
    2 *  5  is 10
    3 *  5  is 15
    4 *  5  is 20
    5 *  5  is 25
    Done.