Unexpected EOF while parsing Syntax Error in Python

Viewed 1319

I just started using Python's keyboard module. I was exploring with the code below until there was a error occurring at the end on line 5. The goal of the code below is to detect if I pressed the "a" on my keyboard. I attempted to put a semicolon at the end of the print function, and I tried to replace the print("A") with pass and break but Python gave me the same error as before.

import keyboard
while True:
    try:
        if keyboard.is_pressed('a'):
            print("A")

Output:

File "c:\users\emma\mu_code\keyboard.py", line 6

Syntax Error: unexpected EOF while parsing

Why do I have this syntax error and how can I get rid of it?

2 Answers

In your code add the except block, like so:

import keyboard
while True:
    try:
        if keyboard.is_pressed('a'):
            print("A")
   except:
      #do something else, if there is an error, or any other key is pressed

If u dont know if u need try except, then just dont keep it in the try block:

import keyboard
while True:
    if keyboard.is_pressed('a'):
            print("A")

You didn't add except part. If you are using try/except statement you need an except statement.

Make it.

import keyboard
while True:
    try:
        if keyboard.is_pressed('a'):
            print("A")
    else:
       # Rest code . If you don't want to do anything then simply pass
       pass
Related