The difference between nonlocal and global in python

The difference between nonlocal and global in python

1, global
global defines global variables, this applies to the global,
for example

count=0
def sums():
	global count
	count+=1
sums()
print(count)

The result is 1,
2, nonlocal
nonlocal is used for the call of external nested variables

def tree():
	count=0
	def sums():
		nonlocal count
		count+=1
	sums()
	print(count)
tree()

The result is 1

Guess you like

Origin blog.csdn.net/qq_44671932/article/details/109250968