Global and Local Variables

Global and local Variables in Functions

Let's have a look at the following function:

def f(): 
    print s 
s = "I hate spam"
f()
The variable s is defined as the string "I hate spam", before we call the function f(). The only statement in f() is the "print s" statement. As there is no local s, the value from the global s will be used. So the output will be the string "I hate spam". The question is, what will happen, if we change the value of s inside of the function f()? Will it affect the global s as well? We test it in the following piece of code:
def f(): 
    s = "Me too."
    print s 

s = "I hate spam." 
f()
print s
The output looks like this:
Me too.
I hate spam.
What if we combine the first example with the second one, i.e. first access s and then assigning a value to it? It will throw an error, as we can see the the following example:
def f(): 
	print s
	s = "Me too."
	print s


s = "I hate spam." 
f()
print s
If we execute the previous script, we get the error message:
UnboundLocalError: local variable 's' referenced before assignment
Python "assumes" that we want a local variable due to the assignment to s inside of f(), so the first print statement throws this error message. Any variable which is changed or created inside of a function is local, if it hasn't been declared as a global variable. To tell Python, that we want to use the global variable, we have to use the keyword "global", as can be seen in the following example:
def f():
    global s
    print s
    s = "That's clear."
    print s 


s = "Python is great!" 
f()
print s
Now there is no ambiguity. The output is as follows:
Python is great!
That's clear.
Python is great!
Local variables of functions can't be accessed from outside, when the function call has finished:
def f():
    s = "I am globally not known"
    print s 

f()
print s
Starting this script gives us the following output with an error message:
I am globally not known
Traceback (most recent call last):
  File "global_local3.py", line 6, in <module>
    print s
NameError: name 's' is not defined
The following example shows a wild combination of local and global variables and function parameters:
def foo(x, y):
    global a
    a = 42
    x,y = y,x
    b = 33
    b = 17
    c = 100
    print a,b,x,y

a,b,x,y = 1,15,3,4
foo(17,4)
print a,b,x,y
The output looks like this:
42 17 4 17
42 15 3 4
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值