第五章、 函数
定义语句后面要加冒号
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. Hbase常见异常 分类: B7_HBASE 2015-02-02 16:16 412人阅读 评论(0) 收藏

    1. HBase is able to connect to ZooKeeper but the connection closes immediately hbase(main):001:0> ...

  2. ios开发多线程一:了解-NSOperation的基本使用

    #import "ViewController.h" @interface ViewController () @end @implementation ViewControlle ...

  3. 【40.17%】【codeforces 569B】Inventory

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

  4. 修改VNC的分辨率

    http://blog.csdn.net/jlds123/article/details/9064437 有时候用VNC View打开远程linux桌面时,桌面显示不出来,只有一个灰色背景加上一个命令 ...

  5. [TypeScript] Catch unsafe use of "this" in TypeScript functions

    this is probably the most tricky thing to use in JavaScript and therefore TypeScript. Fortunately th ...

  6. 非常实用全面的 C++框架,库类等资源

    这次的资源涉及到了标准库.Web应用框架.人工智能.数据库.图片处理.机器学习.日志.代码分析等,C++程序员学习必备! Jason frozen : C/C++的Jason解析生成器 Jansson ...

  7. SpringMVC拦截器-路径语法-略坑

    项目中遇到一种场景,登录拦截器需要拦截.html后缀等动态请求,但是发现语法不对头.    <mvc:interceptors>      <mvc:interceptor> ...

  8. 学习JS的这些日子——十二月总结

    事实上非常想早就发表这篇十二月份的总结了,可是一直拖拖拉拉没有完毕.一直在想2015年都过去了,该不该再去 写这一篇2015年最后一个月的总结.还有就是2015年的年终总结能否够取代十二月的总结,后来 ...

  9. Myeclipse - Web项目转换技巧--处理Java项目、SVN非Web项目问题

    喜欢从业的专注,七分学习的态度. 概述 对于Java调试,使用Eclipse习惯性的使用Junit调试,使用Myeclipse习惯性的将项目转成Web项目在Tomcat或Weblogic中调试,在My ...

  10. 要求两个异步任务都完成后, 才能回到主线程:dispatch_group_t

    需求:两个异步任务都完成后, 回到主线程 /** 1.下载图片1和图片2 2.将图片1和图片2合并成一张图片后显示到imageView上 思考: * 下载图片 : 子线程 * 等2张图片都下载完毕后, ...