函数

  • 完成特定功能的一个语句组,这个语句组可以作为一个单位使用,并且给它组语句取一个名子,即函数名
  • 可以通过函数名在程序不同地方多次执行,即函数调用
  • 预定义函数(可以直接使用)
  • 自定义函数(自编写的)

函数的定义:

  • def 函数句([参数列表]): //定义
def hello ():
print(hello world)

函数的调用:

  • 函数名([参数列表]) //调用
hello()

函数的参数:

形式参数和实际参数

  • 在定义函数时,函数名后面的括号中的变量名称叫做 形式参数, 或者称为 形参
  • 在调用函数时,函数名后面括号中的变量名称叫做 实际参数,或都称为 实参
a = 'hello'
b = 'world' def hello(x, y): //x y 为形式参数
print('{0} {1}'.format(x, y)) hello(a, b) // a, b 这实际参数

函数的默认参数:

  • 在定函数时,也可设置形参的缺省值 (缺省参数)
def func4(x, y=100):
print('x = {0}'.format(x))
print('y = {0}'.format(y)) func4(10, 50)
func4(10)
"""
x = 10
y = 50 x = 10
y = 100
从结果可以看出.当调用时传入第二个实参时,以传入实参为准,不传入时,默认的缺省值生效
"""
  • 函数的多类型传值和冗余参数

*var_args_tuple 和 **var_args_dict (不定长参数)

当一个函数需要处理比声明时更多的参数时,可使用*var_args_tuple 和 **var_args_dict

*var_args_tuple 传入的是一个tuple 类型

def func5(x, y, *z):

print('x = {0}'.format(x))

print('y = {0}'.format(y))

print('z = {0}'.format(z))

print('lenth of z is: {0}'.format(len(z)))

for i in z:

print(i)

func5(10, 20, 30, 40, 50, 60)

等价于

tuple_test = (30, 40, 50, 60)

func5(10, 20, tuple_test)

"""

x = 10

y = 20

z = (30, 40, 50, 60)

lenth of z is: 4

30

40

50

60

从结果可以看出,x, y,分别对应前两个实参10 20,剩余的参数30 40 50 60 做为一个元组传递给形参 z

"""

**var_args_dict 传入的是一个dict 类型

def func6(a, b, **c):

print('a = {0}'.format(a))

print('b = {0}'.format(b))

print('c = {0}'.format(c))

print(type(c))

for key, valaue in c.iteritems():

print('key = {0}, valaue = {1}'.format(key, valaue))

func6(10, 50, x='hello', y='world')

等价于

dict_test = {'x':'hello', 'y':'world'}

func6(10, 50, **dict_test)

"""

a = 10

b = 50

c = {'y': 'world', 'x': 'hello'}

<type 'dict'>

key = y, valaue = world

key = x, valaue = hello

从结果可以看出,10 传给了形参a ,50 传给了形参 b , x='hello', y='world' 作为一个字典传给了 形参 c

"""

函数的变量

局部变量和全局变量
  • python 中的任何变量都有特定的作用域
  • 在函数中定义的变量一般只能在该函数内部使用,这些只能在程序特定部分使用的变量我们称之为局部变量
  • 在一个文件顶部定义的变量可以供文件中的任何函数调用,这些可以为整个程序所使用的变量称为全局变量
x = 100   //全局变量
def func():
x = 200 //局部变量
print(x) func()
print(x) ######
200 在函数内部调用 x = 200
100 在函数外部调用 X = 100
函数中操作局部变量
  • 在函数中要以调用全局变量
x = 100

def fun():
print(x) fun()
########
100 //在函数中要以调用全局变量
  • 正常情况下了函数中不能操作全局变量
x = 100

def fun():
x = x + 1
print(x) fun() ######
UnboundLocalError: local variable 'x' referenced before assignment //报错
  • global 声明一个全局变量

  • 使用global 在函数中操作全局变量

x = 100

def fun():
global x
x = x + 1
print(x) fun()
print(x)
######
101 //全局变量x在函数中执行+1 操作,并打印
101 // 全局变量发生改变
  • 使用global 在函数中声明全局变量
x = 100

def fun():
global x
x = x + 1
print(x)
global y
y = x + 100
fun()
print(x)
print(y)
########
101
101
201

函数的返回值

  • 函数被调用后会返回一个指定的值

  • 函数调用后默认返回None

  • return 返回值

  • 返回值可以是任意类型

  • return 执行后,函数终止

  • return 和 print的区别

    print中是将执行结果打印出来,无法对处理结果进行再次使用

    return 可以将执行结果进行判断或赋值给变量,可以对结果进行使用

函数的递归

  • 在函数中调用本身

例:计算阶乘

正常方法


def factorial(n):
sum = 1
for n in xrange(1, n+1):
sum *= n
return sum print(factorial(5))

使用递归

def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
print(factorial(5))
递归的注意事项
  • 必须有最后的默认结果 (if n == 0)
  • 递归参数必须向默认结果收敛 (n - 1)

最新文章

  1. Android开发学习之路-使用annotationProcessor配置Butterknife
  2. nodejs操作mongodb
  3. 管道寄售库存MRKO结算后,冲销问题
  4. 将dataset写入数据库
  5. bash:ifconfig command not found for contos7.0
  6. BZOJ 1977: [BeiJing2010组队]次小生成树 Tree( MST + 树链剖分 + RMQ )
  7. 在深度linux下安装pip3与jupyter
  8. DWR第一篇之入门示例
  9. JMeter中返回Json数据的处理方法(转)
  10. 手动创建mfc工程(留存方便复制)
  11. jQuery工具--jQuery.isNumeric(value)和jQuery.trim(str)
  12. slot内容分发
  13. Mac破解Sublime Text 3 3176
  14. django的单元测试框架unittest、覆盖率
  15. VirtualBox vbox not found
  16. 在Mac上安装anaconda,在命令行中输入conda,提示不是有效命令的解决办法
  17. noip rp++
  18. 开源代码SlidingMenu的使用
  19. 查询login什么时候过期
  20. java基础14 多态(及关键字:instanceof)

热门文章

  1. LeetCode 36——有效的数独
  2. Week1 Team Homework #2 from Z.XML-Introduction of team member with photos
  3. node + npm 命令
  4. eclipse版本命名规则与其他软件命名
  5. python3 urllib和requests模块
  6. 如何优雅的使用iBatis
  7. 子查询 做where条件 做 from的临时表 ,做select的一个字段 等
  8. 关于&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html:charset=UTF-8&quot;&gt;
  9. 【题解】SDOI2014数数
  10. 【莫比乌斯反演】51nod1594 Gcd and Phi