Python Forum
Global variables or local accessible
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Global variables or local accessible
#3
Fixing your program is not all that simple. Your program has a design flaw that will eventually result in a recursion limit exceeded exception. This would take a while, so let's speed things up a bit.
import random

def stop():
    main()
 
def Left():
    stop()

def Middle():
    stop()

def Right():
    stop()

def main():
    random.choice((Left, Middle, Right))()

main()
Error:
File "...", line 7, in stop main() File "...", line 19, in main random.choice((stop, Left, Middle, Right))() blah, blah, blah calling some function that calls main that calls another function that calls stop() that calls main ... until eventually File "C:\Program Files\Python311\Lib\random.py", line 239, in _randbelow_with_getrandbits k = n.bit_length() # don't use (n-1) here because n can be 1 ^^^^^^^^^^^^^^ RecursionError: maximum recursion depth exceeded while calling a Python object
You should use a loop in main() instead of using recursion. main() should call Left(). Left() should do it's thing and call stop. stop() should do it's thing and end, letting control return to Left(). Left() should execute any remaining code (currently none) and end, letting control return to main().

This does the same thing as above, but it runs forever without consuming more and more resources.
import random

def stop():
    pass
 
def Left():
    stop()

def Middle():
    stop()

def Right():
    stop()

def main():
    while True:
        random.choice((Left, Middle, Right))()

main()
Reply


Messages In This Thread
Global variables or local accessible - by caslor - Jan-27-2023, 12:00 PM
RE: Global variables or local accessible - by deanhystad - Jan-27-2023, 01:32 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  It's saying my global variable is a local variable Radical 5 1,470 Oct-02-2023, 12:57 AM
Last Post: deanhystad
  Trying to understand global variables 357mag 5 1,297 May-12-2023, 04:16 PM
Last Post: deanhystad
  Delete all Excel named ranges (local and global scope) pfdjhfuys 2 2,224 Mar-24-2023, 01:32 PM
Last Post: pfdjhfuys
  global variables HeinKurz 3 1,290 Jan-17-2023, 06:58 PM
Last Post: HeinKurz
  How to use global value or local value sabuzaki 4 1,322 Jan-11-2023, 11:59 AM
Last Post: Gribouillis
  Clarity on global variables JonWayn 2 1,052 Nov-26-2022, 12:10 PM
Last Post: JonWayn
  Global variables not working hobbyist 9 4,989 Jan-16-2021, 03:17 PM
Last Post: jefsummers
  Global vs. Local Variables Davy_Jones_XIV 4 2,805 Jan-06-2021, 10:22 PM
Last Post: Davy_Jones_XIV
  Global - local variables Motorhomer14 11 4,521 Dec-17-2020, 06:40 PM
Last Post: Motorhomer14
  from global space to local space Skaperen 4 2,457 Sep-08-2020, 04:59 PM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020