import pygame
from pygame.locals import *
from sys import exit

pygame.init()

screen = pygame.display.set_mode((640, 480), 0, 32)

font = pygame.font.SysFont('arial', 32)
font_height = font.get_linesize()

while True:
    
    for event in pygame.event.get():
        if event.type == QUIT:
            exit()
            
    screen.fill((255, 255, 255))
    
    pressed_key_text = []
    pressed_keys = pygame.key.get_pressed()
    y = font_height
    
    for key_constant, pressed in enumerate(pressed_keys):
        if pressed:
            key_name = pygame.key.name(key_constant)
            text_surface = font.render(key_name + " pressed", True, (0,0,0))
            screen.blit(text_surface, (8, y))
            y += font_height
            
    pygame.display.update()

In the code above, how does a for loop use two variables? I know this is probably really simples but I've always just used one so I'M not sure how it works.

Recommended Answers

All 3 Replies

You can assign tuple of values to tuple of variables in Python

>>> a,b = 0,1
>>> print(a,b)
(0, 1)

You can also do this:

>>> yes, no = 'YN'
>>> print(yes)
Y
>>> print(no)
N

Here is an more complete example

>>> L = [ (1, (2, 3)), (4, (5, 6)), (7, (8, 9))]

>>> for item in L:
...     print  item
(1, (2, 3))
(4, (5, 6))
(7, (8, 9))
    
>>> for x, y in L:
...     print x, y
1 (2, 3)
4 (5, 6)
7 (8, 9)
    
>>> for x, (y, z) in L:
...     print x, y, z
1 2 3
4 5 6
7 8 9

(examples obtained with the recent reinteract python shell. Try it, it looks promising).

for key_constant, pressed in enumerate(pressed_keys):

If you are asking about this line (you didn't say), enumerate returns a counter and the original variable, with the counter incremented by one for each item in the list. It is similiar to this, as printing the variables will show

ctr = 0
for pressed in pressed_keys:
   print ctr, pressed
   ctr += 1
##
##
## you can also try
for test_it in enumerate(pressed_keys):     ## don't split into two variables
    print test_it, type(test_it)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.