D
D
DimaD0106d2021-06-15 23:41:04
Python
DimaD0106d, 2021-06-15 23:41:04

Why doesn't the code work?

import keyboard
import time
s = (0)
def func():
    while True:
        time.sleep(1)
        s +=(1)
        print(s)
while True:        
    time.sleep(0.05)
    if keyboard.is_pressed('f'):
        func()

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
dmshar, 2021-06-16
@DimaD0106d

Because the variable s is global. (although why - it is not clear, but oh well). And if so, then it must be declared explicitly:
global s
But the most unpleasant thing is that the interpreter probably told you about this, but you didn’t even understand it.

A
Andrew, 2021-06-16
@AndreyJoestar

You declare the use of a variable before assigning it to the
variable s, you must specify it at the beginning of the function,
or declare it global

import keyboard
import time

def func():
    s = 0
    while True:
        time.sleep(1)
        s += (1)
        print(s)
while True:        
    time.sleep(0.05)
    if keyboard.is_pressed('f'):
        func()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question