1.函数关键字
参考:https://blog.csdn.net/s1h2e3n4g5/article/details/76416257
2.函数的定义
def 函数名(参数列表):
函数体
>>>def hello() :
print("Hello World!")
>>> hello()
Hello World!
>>>
3.函数的参数与作用域
3.1函数的参数
a.位置函数
def power(x):
return x * x
def power(x, n):
s = 1
while n > 0:
n = n - 1
s = s * x
return s
b.默认参数
def power(x, n=2):
s = 1
while n > 0:
n = n - 1
s = s * x
return s
c.可变参数
可变参数就是传入的参数个数是可变的,可以是1个、2个到任意个,还可以是0个。
def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
d.关键字参数
>>> person('Bob', 35, city='Beijing')
name: Bob age: 35 other: {'city': 'Beijing'}
>>> person('Adam', 45, gender='M', job='Engineer')
name: Adam age: 45 other: {'gender': 'M', 'job': 'Engineer'}
3.2 函数的作用域
变量的作用域决定了在哪一部分程序可以访问哪个特定的变量名称。Python的作用域一共有4种,分别是:
L (Local) 局部作用域
E (Enclosing) 闭包函数外的函数中
G (Global) 全局作用域
B (Built-in) 内建作用域
以 L –> E –> G –>B 的规则查找,即:在局部找不到,便会去局部外的局部找(例如闭包),再找不到就会去全局找,再者去内建中找。
原文:http://www.runoob.com/python3/python3-function.html
4.函数返回值
return [表达式] 语句用于退出函数,选择性地向调用方返回一个表达式。不带参数值的return语句返回None。
def sum( arg1, arg2 ):
# 返回2个参数的和."
total = arg1 + arg2
print ("函数内 : ", total)
return total
# 调用sum函数
total = sum( 10, 20 )
print ("函数外 : ", total)