Why does it ignore my continue in the for-loop? [closed]

Tags: , , , ,



import pygame
import player

play = player.player()
pygame.init()
time = pygame.time.Clock()
key = 0
move = ""
List =[]
pygame.display.set_mode((100, 100))
while True:
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            time_down = pygame.time.get_ticks()
            if event.key == pygame.K_LEFT:
                move = "l"
            if event.key == pygame.K_RIGHT:
                move = "r"
            if event.key == pygame.K_DOWN:
                move = "d"
                print('UNTEN')
            if event.key == pygame.K_UP:
                move = "u"
            if event.key == pygame.K_ESCAPE:
                break
            else:
                continue
        key += 1
        play.handlerevent(event)
        if event.type == pygame.KEYUP:
            time_elapsed = (pygame.time.get_ticks() - time_down) / 1000.0
            print("Nummer: ", key, "Zeit: ", time_elapsed)
            tmp = (move, key)
            List.extend(tmp)

Hello I’m new here and would like to know, why my for-loop doesn’t react to the continue. It goes into the else branch. But just ignores the continue.

Answer

I suspect you have it backwards: continue is being executed when it shouldn’t be.

You need to use elif for your sequence of conditions. Your else: block is only associated with the last if condition. So if the key is K_LEFT it will go into the else: block and continue, instead of executing the rest of the loop.

            if event.key == pygame.K_LEFT:
                move = "l"
            elif event.key == pygame.K_RIGHT:
                move = "r"
            elif event.key == pygame.K_DOWN:
                move = "d"
                print('UNTEN')
            elif event.key == pygame.K_UP:
                move = "u"
            elif event.key == pygame.K_ESCAPE:
                break
            else:
                continue

This way, the else: block will be executed only when none of the if conditions succeeded.



Source: stackoverflow