Menu
CoddyTech

Elif and Else

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

else gives an if a second branch, for when the condition is false. elif, short for "else if", adds more conditions in between:

if moon_x < 200:
    colour = (255, 170, 90)
elif moon_x < 440:
    colour = (240, 230, 160)
else:
    colour = (160, 190, 255)

Python tests the conditions from the top, runs the first branch whose condition is true, and skips the rest. At x 100 the first two conditions are both true, but only the first branch runs. else has no condition: it runs when none above was true.

Separate ifs work differently: each one is tested. With three ifs, a moon at x 100 would turn orange, then the second would turn it yellow again.

Here colour is a variable that holds a tuple. Draw with it: pygame.draw.circle(screen, colour, (moon_x, moon_y), 50).

challenge icon

Challenge

Medium

Colour the moon by where it is. In the change part, after the keys:

  1. If moon_x < 200, set colour to orange (255, 170, 90).
  2. Elif moon_x < 440, set it to the usual (240, 230, 160).
  3. Else set it to blue (160, 190, 255).
  4. Draw the moon with colour.

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.
moon_x = 320
moon_y = 240

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

    # Change things here, once a frame.
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        moon_x = moon_x - 4
    if keys[pygame.K_RIGHT]:
        moon_x = moon_x + 4

    screen.fill((20, 24, 48))
    # Draw here, after the fill.
    pygame.draw.circle(screen, (240, 230, 160), (moon_x, moon_y), 50)

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

pygame.quit()

All lessons in Python in a Game Window

Practice on your own: Pygame playground