第五章、 函数
定义语句后面要加冒号
1)    定义函数

def sayHello():
    print 'Hello World!'
sayHello() 

2)    变量作用域
LEGB原则
L本地作用域
E上层结构中def或lambda的作用域
G全局作用域
B内置作用域

3)    工厂/闭合函数

def maker(N):
    def action(X):
        return X ** N
    return action

f = maker(2)
print f    #<function action at 0x00E87730>
print f(3) #9
print f(4) #16
g = maker(3)
print g(3) #27 

4)    函数形参

def printMax(a, b):
    if a > b:
        print a, 'is maximum'
    else:
        print b, 'is maximum'
printMax(3, 4) 

5)    局部变量
x是函数的局部变量

def func(x):
    print 'x is', x
    x = 2
    print 'Changed local x to', x
x = 50
func(x)
print 'x is still', x 

全局变量

def func():
    global x
    print 'x is', x
    x = 2
    print 'Changed local x to', x
x = 50
func()
print 'Value of x is', x 

6)    默认参数值

def say(message, times = 1):
    print message * times
say('Hello') 

7)    关键参数

def func(a, b=5, c=10):
    print 'a is', a, 'and b is', b, 'and c is', c
func(3) 

8)    可变长度参数
*非关键字可变长参数(元组)

>>> def tupleVarArgs(arg1, arg2 = "defaultB", *theRest):
    print 'arg 1:', arg1
    print 'arg 2:', arg2
    for eachXtrArg in theRest:
        print 'another arg:', eachXtrArg
>>> tupleVarArgs('abc')
arg 1: abc
arg 2: defaultB
>>> tupleVarArgs(23, 4.56)
arg 1: 23
arg 2: 4.56
>>> tupleVarArgs('abc', 123, 'xyz', 456.7)
arg 1: abc
arg 2: 123
another arg: xyz
another arg: 456.7 

**关键字变量参数(字典)

>>> def dictVarArgs(arg1, arg2 = "defaultB", **theRest):
    print 'arg 1:', arg1
    print 'arg 2:', arg2
    for eachXtrArg in theRest.keys():
        print 'Xtra arg %s: %s' \
         %(eachXtrArg, str(theRest[eachXtrArg]))
>>> dictVarArgs(1220, 740.0, c = 'gmail')
arg 1: 1220
arg 2: 740.0
Xtra arg c: gmail
>>> dictVarArgs(arg2 = 'tales', c = 123, d = 'poe', arg1 = 'my')
arg 1: my
arg 2: tales
Xtra arg c: 123
Xtra arg d: poe
>>> dictVarArgs('one', d = 10, e = 'zoo', men = ('freud', 'gaudi'))
arg 1: one
arg 2: defaultB
Xtra arg men: ('freud', 'gaudi')
Xtra arg e: zoo
Xtra arg d: 10 

组合使用

>>> def newfoo(arg1, arg2, *nkw, **kw):
    print 'arg1 is :', arg1
    print 'arg2 is :', arg2
    for eachNKW in nkw:
        print 'add non-keyword:', eachNKW
    for eachKW in kw.keys():
        print "add keyword '%s': %s" %(eachKW, kw[eachKW])
>>> newfoo(10, 20, 30, 40, foo = 50, bar = 60)
arg1 is : 10
arg2 is : 20
add non-keyword: 30
add non-keyword: 40
add keyword 'foo': 50
add keyword 'bar': 60
>>> newfoo(2, 4, *(6, 8), **{'foo':10, 'bar':12})
arg1 is : 2
arg2 is : 4
add non-keyword: 6
add non-keyword: 8
add keyword 'foo': 10
add keyword 'bar': 12
>>> aTuple = (6, 7, 8)
>>> aDict = {'z':9}
>>> newfoo(1, 2, 3, x = 4, y = 5, *aTuple, **aDict)
arg1 is : 1
arg2 is : 2
add non-keyword: 3
add non-keyword: 6
add non-keyword: 7
add non-keyword: 8
add keyword 'y': 5
add keyword 'x': 4
add keyword 'z': 9
>>> 

9)    return语句

def maximum(x, y):
    if x > y:
        return x
    else:
        return y
print maximum(2, 3) 

10)    DocStrings
文档字符串,一个多行字符串。
你可以使用__doc__(注意双下划线)调用函数的文档字符串属性。
建议对你所写的任何正式函数编写文档字符串。

def printMax(x, y):
    '''Prints the maximum of two numbers.

    The two values must be integers.'''
    x = int(x) # convert to integers, if possible
    y = int(y)
    if x > y:
        print x, 'is maximum'
    else:
        print y, 'is maximum'

printMax(3, 5)
print printMax.__doc__

11)    lambda匿名函数
使用方法:lambda [arg1[,arg2,arg3,...,argn]] : expression

Factorial = lambda x: x > 1 and x * Factorial(x - 1) or 1
print Factorial(6)
max = lambda a, b: (a > b) and a or b
print max(2,3)
x, y = 11, 12
print (lambda : x+y)() #23
print (lambda x: x+y)(x) #23
print (lambda x: x+y)(y) #24 

12)    Generator生成器
可以保存状态的函数,用yield指令(不是return)返回一个值,并保存当前整个函数执行状态,等待下一次调用,如此循环往复,直至函数末尾,发生StopIteration异常。
generator利用next()来获取下一个返回值。

def gen(n):
    for i in xrange(n):
        yield i
g = gen(5)
print g #<generator object gen at 0x00E82350>
print g.next() #0
print g.next() #1
for x in g:
    print x    #2, 3, 4
print g.next() #Error: StopIteration 

13)    Iterations迭代器
Iteration: iter and next

L = [1, 2, 3]
I = iter(L)
print I.next() #1
print I.next() #2
print I.next() #3
print I.next() #StopIteration Error
for x in I: print(x) # map iterator is now empty: one pass only

Y = iter(L)
while True:
    try:
        X = next(Y)  # Or call I.__next__
    except StopIteration:
        break
print X ** 2 #1 4 9

支持两个(2.6支持map, zip, range, 3.0只有range支持)

R = range(3)
I1, I2 = iter(R), iter(R)
print next(I1), next(I1), next(I2) #0 1 0 

14)    内建函数
enumerate函数
获得数组,或列表的索引及值

string = 'hi'
print list(enumerate(string)) #[(0, 'h'), (1, 'i')]
for index,value in enumerate(string):
    print index, value
#0 h
#1 i 

filter函数
filter(bool_func,seq):此函数的功能相当于过滤器。调用一个布尔函数bool_func来迭代遍历每个seq中的元素;返回一个使bool_seq返回值为true的元素的序列。

def f(x): return x % 2 != 0 and x % 3 != 0
print filter(f, range(2, 25)) 

map函数
map(func,seq1[,seq2...]):将函数func作用于给定序列的每个元素,并用一个列表来提供返回值;如果func为None,func表现为身份函数,返回一个含有每个序列中元素集合的n个元组的列表。

def cube(x): return x*x*x
print map(cube, range(1, 5)) #[1, 8, 27, 64]
print filter(cube, range(1,5)) #[1, 2, 3, 4]
print map(lambda x : x * 2,[1,2,3,4,[5,6,7]])

#运行结果  
[2, 4, 6, 8, [5, 6, 7, 5, 6, 7]]  
None参数

>>> map(None, 'abc', 'xyz123')
[('a', 'x'), ('b', 'y'), ('c', 'z'), (None, '1'), (None, '2'), (None, '3')] 

reduce函数
reduce(func,seq[,init]):func 为二元函数,将func作用于seq序列的元素,每次携带一对(先前的结果以及下一个序列的元素),连续的将现有的结果和下一个值作用在获得的随后的结果上,最后减少我们的序列为一个单一的返回值:如果初始值init给定,第一个比较会是init和第一个序列元素而不是序列的头两个元素。

print reduce((lambda x, y: x + y), [1, 2, 3, 4]) #10
print reduce((lambda x, y: x * y), [1, 2, 3, 4]) #24 

zip函数
zip允许用户使用for循环访问平行的多个序列,zip将一个或多个序列作为参数,然后返回一系列的与序列中项平行的元组.

x, y = [1, 2, 3], [4, 5, 6]
print zip(x, y) #[(1, 4), (2, 5), (3, 6)]
print list(zip(x, y)) #[(1, 4), (2, 5), (3, 6)]
print dict(zip(x, y)) #{1: 4, 2: 5, 3: 6}
print tuple(zip(x, y)) #((1, 4), (2, 5), (3, 6))

T1, T2, T3 = (1,2,3), (4,5,6), (7,8,9)
print list(zip(T1, T2, T3)) #[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
print tuple(zip(T1, T2, T3)) #((1, 4, 7), (2, 5, 8), (3, 6, 9)) 

其他函数
type得到对象的类型

>>> type(42) #<type 'int'>
>>> type(type(42)) #<type 'type'>
>>>type([].append) #<type 'builtin_function_or_method'>

cmp比较两个对象是否相等

>>> cmp(1,2) #-1
>>> cmp(0xFF, 255) #0

类型转换

>>> float(4) #4.0
>>> complex(2.4, 8) #(2.4+8j)
>>> coerce(1j, 123) #(1j, (123+0j))

ASCII转换

>>> ord('s') #115返回对应的ASCII码
>>> chr(115)# 's'返回对应的字符

进行转换

>>> hex(255) #'0xff'
>>> oct(255) #'0377' 

python 教程 第五章、 函数的更多相关文章

  1. Objective-C 基础教程第五章,复合

    目录 Objective-C 基础教程第五章,复合 什么是复合? Car程序 自定义NSLog() 存取方法get Set Tires(轮胎) 存取方法 Car类代码的其他变化 扩展Car程序 复合还 ...

  2. 2018-06-21 中文代码示例视频演示Python入门教程第五章 数据结构

    知乎原链 续前作: 中文代码示例视频演示Python入门教程第四章 控制流 对应在线文档: 5. Data Structures 这一章起初还是采取了尽量与原例程相近的汉化方式, 但有些语义较偏(如T ...

  3. 进击的Python【第五章】:Python的高级应用(二)常用模块

    Python的高级应用(二)常用模块学习 本章学习要点: Python模块的定义 time &datetime模块 random模块 os模块 sys模块 shutil模块 ConfigPar ...

  4. [ABP教程]第五章 授权

    原文档 地址: Web Application Development Tutorial - Part 5: Authorization 关于此教程 在这个教程系列中,您将构建一个基于ABP的Web应 ...

  5. Cobalt Strike系列教程第五章:截图与浏览器代理

    Cobalt Strike系列教程分享如约而至,新关注的小伙伴可以先回顾一下前面的内容: Cobalt Strike系列教程第一章:简介与安装 Cobalt Strike系列教程第二章:Beacon详 ...

  6. Python入门系列教程(五)函数

    全局变量 修改全局变量 a=100 def test(): global a a=200 print a 多个返回值 缺省参数 def test3(a,b=1): print a,b test3(a) ...

  7. Python自学:第五章 使用函数range( )

    # -*- coding: GBK -*- for value in range(1,5): print(value) 输出为: 1 2 3 4

  8. Flask 教程 第五章:用户登录

    本文翻译自The Flask Mega-Tutorial Part V: User Logins 这是Flask Mega-Tutorial系列的第五部分,我将告诉你如何创建一个用户登录子系统. 你在 ...

  9. Python笔记·第十一章—— 函数 (二) 装饰器

    一 为何要用装饰器 有的时候写完一段代码,过段时间需要对它进行升级.添加一些新功能,但是如果要直接修改原来的代码会影响其他人的调用,所以就需要一个不修改源代码且不修改原函数的调用方式的东西又能为原函数 ...

随机推荐

  1. 【42.86%】【Codeforces Round #380D】Sea Battle

    time limit per test1 second memory limit per test256 megabytes inputstandard input outputstandard ou ...

  2. vue项目build后font-awesome不显示问题

    解决办法: 修改build目录下的utils.js:添加 publicPath: '../../' // Extract CSS when that option is specified // (w ...

  3. angular的Dom操作

    原文 https://www.jianshu.com/p/9d7249922bda 大纲 1.angular的DOM操作 2.为什么不能直接操作DOM? 3.三种错误操作DOM的方式 4.angula ...

  4. Ubuntu10.04下安装Qt4和创建第一个Qt程序

    1.首先安装Qt4并采用Qt Creator进行开发演示 (1)在Terminal中输入: sudo apt-get install qt4-dev-tools qt4-doc qt4-qtconfi ...

  5. Android 利用线程运行栈StackTraceElement设计Android日志模块

    如果你想在你的Android程序中自动打印MainActivity.onCreate(line:37)这种类名.方法名(行数)的日志该如何实现呢? 1.引入Java的线程运行栈 Java.lang包中 ...

  6. 【p091】多项式输出

    一元 n 次多项式可用如下的表达式表示: 其中,aixi 称为i次项,ai称为i次项的系数.给出一个一元多项式各项的次数和系数,请按照如下规定的格式要求输出该多项式: 多项式中自变量为x,从左到右按照 ...

  7. Java多线程系列-线程创建

    1.怎样创建多线程? Java从语言级别实现多线程,因此实现一个多线程程序很easy.有两种方法能够实现多线程,即继承Thread类和实现Runnable接口.由于Java不支持多继承的原因,建议尽可 ...

  8. [RxJS] Split an RxJS observable conditionally with windowToggle

    There are variants of the window operator that allow you to split RxJS observables in different ways ...

  9. 网络异常与SQL Server事务

    SQL Server事务遭遇网络异常时的处理机制浅析 SQL Server数据库中,如果应用程序正在执行一个事务的时候突然遭遇了网络异常,例如网络掉包,网络中断等,那么这个事务会怎么样? SQL Se ...

  10. 【转】priority_queue的用法

    http://www.cnblogs.com/flyoung2008/articles/2136485.html priority_queue调用 STL里面的 make_heap(), pop_he ...