0

I am trying out some stuff in python using the pygame module. this is my code:

import pygame, sys
direction = " "
pygame.init()
try:
 while True:
  for events in pygame.event.get():
    if event.type == pygame.QUIT:
      sys.exit()
    elif event.type == pygaqme.KEYDOWN:
      if event.key == pygame.K_w:
        forward = True
      elif event.key == pygame.K_a:
        left = True
      elif event.key == pygame.K_s:
        reverse = True
      elif event.key == pygame.K_d:
        right = True
    elif event.type == pygame.KEYUP:
      if event.key == pygame.K_w:
        forward = False
      elif event.key == pygame.K_a:
        left = False
      elif event.key == pygame.K_s:
        reverse = False
      elif event.key == pygame.K_d:
        right = False
  if forward:
    print ("forward")
  elif left:
    print("left")
  elif reverse:
    print("reverse")
  elif right:
    print("right")

And on executing this, python tells me that line 35 has invalid syntax, but the problem is that my code is only 34 lines long. I checked to see if there was an accidental new line created and it turns out there was. So I deleted that and executed it again but I still got the same error.

4
  • 2
    You've begun a try statement (used to catch an exception) and not finished it an except, which would appear on line 35 at the latest. Is the try necessary here? If so, add an except; otherwise, you can remove it. Commented May 6, 2015 at 17:09
  • 1
    Whenever you get a "random syntax error" like this, it almost always means either (1) you're missing a ), ], or } on the previous line, or (2) you've got a try: without any except:/finally: farther up the current block. (And if it's not one of those, the next thing to look for is mixing tabs and spaces and hiding problem (1) or (2).) Commented May 6, 2015 at 17:14
  • @abarnert There should be some canonical question on SO for this type of Python problem, with the answers that you have just provided. Do you know of one? Commented May 6, 2015 at 17:40
  • @SethMMorton: No. Every once in a while I search for one, which just reminds me of how hard of a question it is to search for even if you know the problem (much less for the poor person who's encountering this for the first time and has no clue what's wrong…). Commented May 6, 2015 at 17:46

1 Answer 1

9

Python is looking for a except: or finally: block; you cannot just open a try: block without one of those.

Since there was no such block by the time the last line is reached, you get the syntax error for that last, empty line. Line 35 in your case.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.