天天看点

python第六章函数课后答案_第六章 函数

[TOC]

# 函数

## 语法

* ` def 函数名():`

~~~ python

def hello():

print 'Hello Shihongji'

hello()

~~~

## 参数

* func(无默认值形参, 有默认值形参, 元组参数*args, 字典参数**args)

* 例:`def func(x, y, z = 1, *tupleArgs, **dicArgs1)`

~~~ python

'''

普通参数

* def hello(参数1,参数2,参数3....)

'''

def sayHello(name):

print 'Hello ' + str(name)

sayHello('Shihongji')

sayHello(123)

'''

缺省参数(设置默认值的参数)

* def hello(name='123')

* 当函数有多个参数时,如果你想给部分参数提供默认参数,那么这些参数必须在参数的末尾。

* def func(a, b=5) 可以

* def func(a=5, b) 不可以

'''

def sayHello1(name = 'World'):

print 'Hello ' + str(name)

sayHello1()

sayHello1("Shihongji")

'''

元组参数

* def func(*args)

'''

def calcSum(*args):

sum = 0

for i in args:

sum += i

print i

print sum

calcSum(1,2,3,4,5,6,7,8,9)

'''

字典参数

* func(**kargs)

* 把参数以键值对字典的形式传入

* 字典是无序的,所以输出的结果不是按照顺序输出的

'''

def printAll(**args):

for key in args:

print key,':',args[key]

print

printAll(a=1,b=2,c=3,d=4)

'''

四种方式混合使用

* 形参顺序(必须遵守):func(无默认值形参, 有默认值形参, 元组参数*args, 字典参数**args)

* 可以省略某种类型的参数,但仍需保证此顺序规则。

在函数被调用时,参数的传递过程为:

* 按顺序把无指定参数的实参赋值给形参;

* 把指定参数名称(arg=v)的实参赋值给对应的形参;

* 将多余的无指定参数的实参打包成一个 tuple 传递给元组参数(*args);

* 将多余的指定参数名的实参打包成一个 dict 传递给字典参数(**kargs)。

'''

def func(x,y=5,*a,**b):

print x,y,a,b

func(1) #结果:1 5 () {}

func(1,2) #结果:1 2 () {}

func(1,2,3) #结果:1 2 (3,) {}

func(1,2,3,4) #结果:1 2 (3, 4) {}

func(x=1) #结果:1 5 () {}

func(x=1,y=1) #结果:1 1 () {}

func(x=1,y=1,a=1) #结果:1 1 () {'a': 1}

func(x=1,y=1,a=1,b=1) #结果:1 1 () {'a': 1, 'b': 1}

func(1,y=1) #结果:1 1 () {}

func(1,2,3,4,a=1) #结果:1 2 (3, 4) {'a': 1}

func(1,2,3,4,k=1,t=2,o=3) #结果:1 2 (3, 4) {'k': 1, 't': 2, 'o': 3}

~~~

## 参数反转

* 使用*号运算符

~~~ python

def add(x, y):

return x + y

>>> params = (1, 2)

>>> print add( *params ) # 3

~~~

* 使用**运算符

~~~ python

def hello(name = 'shihongji', greeting = 'Hello'):

print greeting, name

>>> params = {'name':'hongji', 'greeting':'Well met'}

>>> hello( **params ) # hongji Well met

~~~

~~~ python

def foo(x, y, z, m = 0, n = 0):

print x, y, z, m, n

>>> tup = (1,2,3)

>>> dic = {'m':1, 'n':2}

>>> foo(*tup, **dic)

结果:

======================

1 2 3 1 2

======================

~~~

# vars()函数

* 变量和所对应的值是个不可见的字典,vars()函数可以返回该字典

~~~ python

>>> ccc = 1 # 实质是一个不可见的字典

>>> dic = vars()

>>> print dic

>>> print dic['ccc']

结果:

==================================

>>> {'ccc': 1}

>>> 1

==================================

~~~

# globals()函数

* 返回全局变量的字典

~~~ python

>>> hello = 'Hello'

>>> hongji = 'hongji'

>>> print globals()

结果:

=================================

>>> {'hongji': 'hongji', 'hello': 'Hello'}

=================================

~~~

* 如果局部变量或参数的名字和想要访问的全局变量名相同的话, 可以使用globals()函数获取全局变量值

~~~ python

>>> parameter = 'berry'

def combin(parameter):

print parameter , globals()['parameter']

>>> combin('Shrub') # Shrub berry

~~~

# global 全局变量语句

* Python中如果在函数内部给全局变量赋值,那该变量会自动转为局部变量

~~~ python

>>> x = 1

def add():

x = x + 1

print x

>>> add()

>>> print x

结果:

==================================

>>> local variable 'x' referenced before assignment 的异常

代码 x = x + 1: 在函数内给全局变量x赋值,导致变量x自动转为了局部变量

x + 1 中x变量还没有被声明就开始使用,所以会报错

=================================

~~~

* 函数内使用golbal 访问全局变量

~~~ python

>>> x = 1

def abcd():

global x

x = x + 1

print x # 2

>>> print x # 1

>>> abcd()

>>> print x # 2

~~~

# 嵌套作用域

* Python中函数可以嵌套

* 在需要用一个函数创建另一个函数时使用

* 外层函数返回里层函数

* 返回的函数还可以访问他定义所在的作用域(它带着它的相关环境和先关局部变量)

* 每次调用外层函数,它内部的函数都会被重新定义

~~~ python

def mul(factor):

def mulByFactor(number):

print factor * number

return mulByFactor # 返回里层函数mulByFactor

>>> mbf = mul(5)

>>> print type(mbf)

>>> mbf(5) # 25

>>> mul(10)(2) # 20

~~~

返回顶部