Menu
CoddyTech

Count with While

Part of the Python in a Game Window section of Coddy's Pygame journey. Lesson 19 of 32.

A while loop repeats as long as its condition is true. Use it when you do not know in advance how many times to go round:

radius = 200
rings = 0
while radius > 10:
    pygame.draw.circle(screen, (150, 190, 255), (320, 240), radius, 2)
    radius = radius // 2
    rings = rings + 1

The radius halves each time: 200, 100, 50, 25, 12. // divides and drops what is after the point, so 25 // 2 is 12. Then it is 6, the condition is false, and the loop ends after 5 rings. rings counts them. The fifth number in the circle call, 2, draws an outline 2 pixels wide instead of a filled circle.

The game loop is a while loop too, one that runs until you close the window. A while loop inside a frame must end quickly, or the frame never ends. Leave out the line that halves the radius and the condition stays true forever: the game freezes, and Check says the game never reached its first frame.

challenge icon

Challenge

Medium

In the draw part, replace the single ring with a while loop:

  1. Start with radius = 200 and rings = 0.
  2. While radius > 10: draw an outline ring of colour (150, 190, 255), width 2, centred at (320, 240); halve the radius with //; add 1 to rings.
  3. After the loop, show f"Rings: {rings}" at (20, 20). It reads Rings: 5.

Try it yourself

import pygame

pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Night Sky")
clock = pygame.time.Clock()

# Set things up here, before the game loop.
font = pygame.font.Font(None, 36)

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Change things here, once a frame.

    screen.fill((20, 24, 48))
    # Draw here, after the fill.
    pygame.draw.circle(screen, (150, 190, 255), (320, 240), 200, 2)
    text = font.render("Rings: 1", True, (230, 230, 240))
    screen.blit(text, (20, 20))

    pygame.display.flip()
    clock.tick(60)

pygame.quit()
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python in a Game Window

Practice on your own: Pygame playground