Pin-Jiun / Python

Python Document
0 stars 0 forks source link

11-Global and Local Variables in Python #11

Open Pin-Jiun opened 1 year ago

Pin-Jiun commented 1 year ago

Global Variables

These are those which are defined outside any function and which are accessible throughout the program, i.e., inside and outside of every function. Let’s see how to create a global variable.

# This function uses global variable s
def f():
    print("Inside Function", s)

# Global scope
s = "I love Geeksforgeeks"
f()
print("Outside Function", s)

然而不能直接使用local variable, 只有function可以讀取整個program的variable Python “assumes” that we want a local variable due to the assignment to s inside of f() Any variable which is changed or created inside of a function is local if it hasn’t been declared as a global variable

# This function uses global variable s
def f():
    s += 'GFG' #error
    print("Inside Function", s)

# Global scope
s = "I love Geeksforgeeks"
f()

Global Keyword:

We only need to use the global keyword in a function if we want to do assignments or change the global variable. global is not needed for function accessing. To tell Python, that we want to use the global variable, we have to use the keyword global

# This function modifies the global variable 's'
def f():
    global s
    s += ' GFG'
    print(s)
    s = "Look for Geeksforgeeks Python Section"
    print(s)

# Global Scope
s = "Python is great!"
f()
print(s)

Using global and local variables

a = 1

# Uses global because there is no local 'a'
def f():
    print('Inside f() : ', a)

# Variable 'a' is redefined as a local
def g():
    a = 2
    print('Inside g() : ', a)

# Uses global keyword to modify global 'a'
def h():
    global a
    a = 3
    print('Inside h() : ', a)

# Global scope
print('global : ', a)
f()
print('global : ', a)
g()
print('global : ', a)
h()
print('global : ', a)

output

global :  1
Inside f() :  1
global :  1
Inside g() :  2
global :  1
Inside h() :  3
global :  3