0
import pygame

def main():
    while True:
        print(window_size)  # works for some reason
        print(window_flag)  # works for some reason
        print(color_flag)   # nope python says no
        print(current_fps)  # python says no
        print(previous_fps) # python says no

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()

            if color_flag:
              ...   # s.o format issue

if __name__ == "__main__":
    window_size = (500, 500)
    window_flag = pygame.RESIZABLE

    # the rejected trio
    color_flag = 0
    current_fps = 0.0
    previous_fps = 0.0
    # :(

    window = pygame.display.set_mode(window_size, window_flag)
    clock  = pygame.time.Clock()
    main()

When I attempt to print the color_key and subsequent variables I encounter an UnboundLocalError which confuses me, since window_size and window_flag are output without issue. Could someone provide insight into why this is the case?

Koz
  • 28
  • 5
  • 1
    Probably you assign to those names in the parts of the code you have omitted here. – mkrieger1 May 23 '22 at 23:51
  • If that is the case, why am I does the script allow `the variables ```window_size``` and and ```window_flag``` to be output to the terminal, but throws an error once I attempt to print ```color_flag```? Shouldn't the script throw the exception as soon as I attempt to output the very first variable? – Koz May 24 '22 at 00:08
  • Have you tried searching for the name of the exception you get? I find [this](https://stackoverflow.com/questions/9264763/why-does-this-unboundlocalerror-occur-closure) and [this](https://stackoverflow.com/questions/10851906/python-3-unboundlocalerror-local-variable-referenced-before-assignment). – mkrieger1 May 24 '22 at 00:09
  • Yes I have. But I am still confused as to why two variables work, and the remaining three throw an exception when just attempting to output them with ```print```. – Koz May 24 '22 at 00:14
  • Because you assign to them in the function, and not to the others. Why this results in an error is explained in the two other posts I've mentioned. – mkrieger1 May 24 '22 at 00:15

0 Answers0