1.4 函数的变量 1.5 函数的返回值

1.4 函数的变量

  • 局部变量和全局变量

python中的任何变量都有特定的做用域 在函数定义中的变量通常只能在该函数内部使用,这些只能在程序特定部分使用的变量咱们称之为局部变量python

在一个文件顶部定义的变量可供文件中的人和函数调用,这些被称为全局变量函数

#!/usr/bin/pythoncode

_global = 'global'
def fun():
	_local = 'local'
	print _local
	print _global

fun()  
# 若是在这里打印_local这个变量会报错
----------
local
global

函数中声明全局变量

def fun():
	global x  \\这样x这个变量就能够在外部使用
	x = 100

1.5 函数的返回值

函数被调用后会返回一个指定的值 函数调用后默认返回None 使用return 能够返回值,返回只能够是任意数据类型 return后函数会终止作用域

def fun():
	print ("Hello world")

print fun()
------
Hello world
None   \\这就是返回值,默认为None

def fun():
	return True
	print ("Hello world")
	
print fun()
------
True
相关文章
相关标签/搜索