0
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.

4
Contributors
3
Replies
13
Views
6 Years
Discussion Span
Last Post by woooee
Featured Replies
  • 1

    You can assign tuple of values to tuple of variables in Python [CODE]>>> a,b = 0,1 >>> print(a,b) (0, 1)[/CODE] You can also do this: [CODE]>>> yes, no = 'YN' >>> print(yes) Y >>> print(no) N [/CODE] Read More

  • Here is an more complete example [code=python] >>> 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) … Read More

1

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
2

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).

Edited by Gribouillis: n/a

0
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)

Edited by woooee: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.