python基础-函数

Posted soldier-lj

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python基础-函数相关的知识,希望对你有一定的参考价值。

在函数里使用全局变量(用global声明):

>>> x = 1
>>> def change_global():
	global x
	x = x+1

	
>>> change_global()
>>> x
2

函数中的局部变量与全局变量同名,且2者都使用的情况下(使用globals获取全局变量的值):

>>> parameter = "alex"
>>> def combine(parameter):
	print(parameter+globals()[‘parameter‘])

	
>>> combine("hello ")
hello alex

nonlocal关键字和global关键字的使用方式类似,可以让用户对外部作用域(但并非全局作用域)的变量进行赋值。  

  

以上是关于python基础-函数的主要内容,如果未能解决你的问题,请参考以下文章