python3 函数:return语句和变量范围

return语句

return [expression]语句退出一个函数,可选地将一个表达式传回给调用者。没有参数的return语句与return None相同。

变量范围

变量的范围决定了可以访问特定标识符的程序部分。Python中有两个变量的基本范围:
全局变量
局部变量

全局与局部变量

在函数体内定义的变量具有局部作用域,外部定义的变量具有全局作用域。
局部变量只能在它们声明的函数内部访问,而全局变量可以通过所有函数在整个程序体中访问。
当调用一个函数时,它内部声明的变量被带入范围。

total = 0 # This is global variable.
def sum( arg1, arg2 ):
   total = arg1 + arg2; # Here total is local variable.
   print ("Inside the function local total : ", total)
   return total

sum( 10, 20 )
print ("Outside the function global total : ", total )

输出:

Inside the function local total :  30
Outside the function global total :  0

 

posted @ 2018-11-27 09:52  刘-皇叔  阅读(2161)  评论(0编辑  收藏  举报