when to use global? anyone mind to give examples :))

0 Steven Yohanes · September 21, 2015
im making  a full scale application, having troubles on using global

Post a Reply

Replies

Oldest  Newest  Rating
0 James Kon · September 22, 2015
global variables can be used OUTSIDE of functions, while local variables can only be used INSIDE the function it's already in.

By default, a variable is global if not made in a functioin
however if the variable is made inside a function, it's local (meaning it can only be used inside the function)
0 sfolje 0 · September 24, 2015
 #example1.py

myGlobal = 5
def func1():
    myGlobal = 42
def func2():
    global myGlobal
    myGlobal = 79
print(myGlobal,"before") #will print 5
func1()
print(myGlobal,"after executed func1") #will print 5, because func1 changes local variable, global remains unchanged
func2()
print(myGlobal,"after executed func2") #will print 79 because func1 changes global variable

#example2.py <will return error>


def func3():
    myglobal=34
func3()
print(myglobal) #will cause error, beacuse func3 makes local variable -> no global variable named myglobal

#example3.py
def func4():
    global myglobal
    myglobal=52
func4()
print(myglobal) # func4 makes global variable myglobal -> variable named myglobal exists
  • 1

Python

107,217 followers
About

This section is all about snakes! Just kidding.

Links
Moderators
Bucky Roberts Administrator