Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Global Variable
#2
Therein lies the evil of global variables.
The answer to your question is yes and yes.

Consider the following,
The program will eventually fail precisely because you are allowed to change a global variable anywhere
MyGlobal = 17

def function_1(n):
    MyGlobal += n

def function_2():
    global MyGlobal
    print('MyGlobal is {}'.format(MyGlobal))

def function_3():
    global MyGlobal
    MyGlobal = str(MyGlobal)

def function_4():
    global MyGlobal
    for n in range(5):
        MyGlobal += n
        function_2()

def main():
    function_4()
    function_3()
    function_4()

if __name__ == '__main__':
    main()
Reply


Messages In This Thread
Global Variable - by jarrod0987 - Apr-05-2018, 12:22 AM
RE: Global Variable - by Larz60+ - Apr-05-2018, 02:43 AM
RE: Global Variable - by Gribouillis - Apr-05-2018, 05:09 AM
RE: Global Variable - by ljmetzger - Apr-05-2018, 12:16 PM
RE: Global Variable - by jarrod0987 - Apr-06-2018, 03:09 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  It's saying my global variable is a local variable Radical 5 1,240 Oct-02-2023, 12:57 AM
Last Post: deanhystad
  Variable scope - "global x" didn't work... ptrivino 5 3,113 Dec-28-2020, 04:52 PM
Last Post: ptrivino
  Spyder Quirk? global variable does not increment when function called in console rrace001 1 2,267 Sep-18-2020, 02:50 PM
Last Post: deanhystad
  NameError for global variable leviporton 3 2,593 Jul-10-2020, 06:51 PM
Last Post: bowlofred
  Function Recognises Variable Without Arguments Or Global Variable Calling. OJGeorge4 1 2,288 Apr-06-2020, 09:14 AM
Last Post: bowlofred
  Global Variable Not Updating joew 2 7,929 Jan-26-2020, 04:15 PM
Last Post: joew
  Help with Global/Coerced Variable (Understanding Scope) Rev2k 6 3,590 Jan-09-2020, 03:43 AM
Last Post: Rev2k
  Declaring a Global Variable in a Function Bob1948 4 3,091 Sep-14-2019, 11:16 PM
Last Post: ichabod801
  Global variable does not seem to be global. Columbo 6 3,764 Jul-15-2019, 11:00 PM
Last Post: Columbo
  change value of a global variable across all modules aster 5 5,107 Jan-01-2019, 06:42 PM
Last Post: aster

Forum Jump:

User Panel Messages

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