Python Global, Local and Nonlocal variables

1. Global variables

1.1 Definition

Global variables: A variable can be accessed inside or outside funtions.

1.2 Example of Usage

在函数里( Inside functions ),能用全局变量( global variables ),但不能改变其值。

Example 1.

x = "global"

def foo():
	print("x inside: ", x)

foo()
print("x outside: ", x)

Output:

x inside:  global
x outside:  global

Example 2.

x = "global"

def foo():
	x = x * 2
	print(x)

foo()

Output:

UnboundLocalError: local variable 'x' referenced before assignment

1.3 global keyword(global关键字)

倘若我们想在函数内改变全局变量的值,需要用到global关键字

x = "global"

def foo():
	global x
	x = x * 2
	print(x)

foo()

Output:

globalglobal

2. Local variables

2.1 Definition

Local variables: We can only access local variables inside functions. Local Variables will be destroyed when the function ends.

2.2 Global variable and Local variable with the same name

x = 5

def foo():
	x = 10
	print("Inside x = {}".format(x))

foo()
print("Outside x = {}".format(x))

Output:

Inside x = 10
Outside x = 5

3. Unlocal variables

3.1 Definition

Unlocal variables: Nonlocal variables are used in nested functions whose local scope is not defined. This means that variable can be neither in the local nor the global scope.

3.2 Example

def outer():
	x = "local"

	def inner():
		nonlocal x
		x = "nonlocal"
		print("inner: ", x)
	inner()
	print("outer:", x)


outer()

Output:

inner:  nonlocal
outer: nonlocal
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值