Pygame error video not initialized

I was on research and came around this code, tried it but not getting the right output. I have scanned through many online codes examples to get an answer but to avail. below is my error code

Traceback (most recent call last):
File “c:\Users\myhobby\Desktop\rect.py”, line 12, in
for event in pygame.event.get():
pygame.error: video system not initialized

zed

import pygame
from pygame.locals import *
from sys import exit
pygame.init()
screen = pygame.display.set_mode((400, 300))

rect1 = Rect(50, 60, 200, 80)
rect2=rect1.copy()
running = True
x=0
y=0
while running:
   for event in pygame.event.get():
      if event.type == QUIT:
         running = False
         exit()
      if event.type == KEYDOWN:
         if event.key==K_LEFT:
            x= -5
            y=0
         if event.key == K_RIGHT:
            x=5
            y=0
         if event.key == K_UP:
            x = 0
            y = -5
         if event.key == K_DOWN:
            x = 0
            y = 5
   rect2.move_ip(x,y)
   screen.fill((127,127,127))
   pygame.draw.rect(screen, (255,0,0), rect1, 1)
   pygame.draw.rect(screen, (0,0,255), rect2, 5)
   pygame.display.update()
   pygame.quit()

Check the indentation. You have pygame.quit() inside the while loop, so it’ll quit pygame at the end of the first iteration.

Another point: you’re calling exit() in the for loop when it receives a QUIT event, which will exit the program, so pygame.quit() wouldn’t be called anyway when that event is received. I’d probably suggest changing that to break.