2

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 2

3

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")
Sign up to request clarification or add additional context in comments.

7 Comments

I tried that replit.com/@EmmaGao8/Keyboard-Sensor#main.py but nothing happens if I press the q key.
Ok i will try it on replit later, but try to install python in ur pc, and then see if it works
I already installed Python, but if I try there, they say that keyboard isn't defined, so I just use replit.com
pip install keyboard in command prompt as keyboard doesnt come pre installed, it happened to me too
|
2

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

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.