In Python is a concept named indentation. Other languages use for example { and }. If you want to read more on this topic, try this link.
So your loop is not indented properly, what you can see in this error message:
File "/projects/stackoverflow_70635220.py", line 11
for i in range (10):
^
IndentationError: unindent does not match any outer indentation level
Second, using listener.join()
waits for the listener to terminate, what it doesn't and shouldn't do. So if you want to handle any key events, do that inside the listener functions on_press
and on_release
.
Furthermore, in your on_release
-method, you are trying to increment the variable k
. This is not possible due to the fact, that the variable is not writable in the scope of your function. If you want to learn more about scopes in python, look here.
You can fix the last issue by writing global k
inside your on_release
method.
A final code example could look something like this:
from pynput.keyboard import Key, Listener
k=0
def on_press(key):
pass
def on_release(key):
global k
if key==Key.enter:
k=k+1
print(k)
with Listener(on_press=on_press, on_release=on_release) as listener :
listener.join()