This is a very simplified version of my actual code in another file:
import keyboard
def main():
test()
def test():
yes = input("enter a ").lower()
if yes == "a":
test2()
def test2():
i = 0
key = "esc"
while True:
i = 1
if keyboard.is_pressed(key):
print(i) # press the esc button on your keyboard to print out "i"
break
elif keyboard.is_pressed("f"):
menu() # press the f button on your keyboard to go to the menu function
def menu():
sth = input("a for test, b for test2 ").lower()
if sth == "a":
test() # press the a button on your keyboard to go back to the test function
elif sth == "b":
test2() # press the b button on your keyboard to go back to the test2 function
if __name__ == "__main__":
main()
You can install the keyboard pip down below or here:
pip install keyboard
When I pressed "f" in test2 function to go to the menu function and press "b" in the menu function to go back to test function and then going back to the test2 function (just like a loop), when I print out the variable "i", it somehow printed out 2 values. I expected it to overwrite the first "i" but it didn't. I have tried just using input()
to stop the loop but it does not add 1 to "i" constantly so I scrapped that idea.
To make things even worse, VS Code keeps on saying ModuleNotFoundError
and I cannot use the run and debug on the sidebar to try and figure out why is that happening.
I have no idea why does the "i" variable has 2 values and how to fix this issue
CodePudding user response:
When you call menu()
from test2
, it doesn't end the body of test2
. That function is still on the call stack, paused while other code runs.
When menu
calls test2
again, you then have two versions of it running at once, the original one, and a new one on top. When you break out the loop by pressing escape, the second call returns to menu()
, which in turn returns to the first call, which probably breaks its loop too, since the escape key is still pressed.
If you want the call to menu
to be the last thing you do in test2
, you need to return
from that line. Or better yet, design your code differently so that you're not building up a big recursive stack with your program logic. Generally recursion is only a good idea in Python if you're recursing on a data structure. If you're just repeating things, use a loop (which you already have).