Python学习笔记(六)——函数 Cyrus

2023-11-05 10:50

本文主要是介绍Python学习笔记(六)——函数 Cyrus,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

函数

  有了语句我们可以做很多事,但是如果要编写大型或更复杂的程序,那么代码的重用性值得我们考虑,因此就有了函数,函数其实可以重复利用的代码块。回忆一下我们N年前用C++痛苦的编写一个斐波那契数列,现用python是多么容易的实现:

fibs=[0,1]

num=input('How much numbers do you want:') #注意这里是input,或者是int(raw_input("")),不然会出错

for i in range(num-2):

    fibs.append(fibs[-2]+fibs[-1])

print fibs

raw_input('press any key to exit!')

  函数可以调用,它执行某种操作并且可能返回值,内建的callable函数(python3中无此函数)可以判断函数是否可以调用:

复制代码

>>> import math
>>> x=1
>>> y=math.sqrt
>>> callable(x)
False
>>> callable(y)
True

复制代码

创建函数——用def关键字来定义

复制代码

>>> def fibs(num):  #创建函数result=[0,1]for i in range(num-2):result.append(result[-2]+result[-1])return result>>> fibs(10)   #调用函数
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
>>> fibs(15)   #调用函数
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]

复制代码

记录函数

  要想给函数写文档让函数容易理解的话,除了写注释外还可以写文档字符串,它作为函数的一部分进行存储,并且可以调用查看:

复制代码

>>> def square(x):'caculate the square of the number x.'  #插入文档字符串return x*x>>> square.func_doc   #访问文档字符串
'caculate the square of the number x.'
(__doc是函数属性,输入square.,然后按tab键,能看到所有的函数属性)

复制代码

函数参数

函数的定义和调用都比较简单,但是函数的用法是体现在它的参数上的,这个比较复杂。

(1)、普通形参

复制代码

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

复制代码

(2)、默认参数值

复制代码

>>> def say(message, times = 2):print message * times>>> say('hello')
hellohello
>>> say(4)
8

复制代码

(3)、关键参数

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

(4)、可变长度参数

  1)、*非关键字可变长参数(元组)

复制代码

>>> def tupleVarArgs(arg1, arg2 = "defaultB", *theRest):print 'arg 1:', arg1print 'arg 2:', arg2for eachXtrArg in theRest:print 'another arg:', eachXtrArg>>> tupleVarArgs('abc')
arg 1: abc
arg 2: defaultB
>>> tupleVarArgs(45,67.8)
arg 1: 45
arg 2: 67.8
>>> tupleVarArgs('abc',123,'xyz',456.7)
arg 1: abc
arg 2: 123
another arg: xyz
another arg: 456.7

复制代码

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

复制代码

>>> def dictVarArgs(arg1, arg2 = "defaultB", **theRest):print 'arg 1:', arg1print 'arg 2:', arg2for 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 = 'zoo', arg1 = 'my')
arg 1: my
arg 2: tales
Xtra arg c: 123
Xtra arg d: zoo>>> dictVarArgs('one', d = 10, e = 'zoo', girls = ('Jenny', 'Penny'))
arg 1: one
arg 2: defaultB
Xtra arg girls: ('Jenny', 'Penny')
Xtra arg e: zoo
Xtra arg d: 10

复制代码

   3)、组合使用

复制代码

>>> def newfoo(arg1, arg2, *t, **d):print 'arg1 is :', arg1print 'arg2 is :', arg2for eacht in t:print 'add non-keyword:', eachtfor eachd in d.keys():print "add keyword '%s': %s" %(eachd, d[eachd])>>>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),**{'jzhou':22,'James':45})
arg1 is : 2
arg2 is : 4
add non-keyword: 6
add non-keyword: 8
add keyword 'jzhou': 22
add keyword 'James': 45>>> atuple=(7,8,9)
>>> adict={'jzhou':22}
>>> newfoo(1,2,3,x=4,y=5,z=6,*atuple ,**adict)
arg1 is : 1
arg2 is : 2
add non-keyword: 3
add non-keyword: 7
add non-keyword: 8
add non-keyword: 9
add keyword 'y': 5
add keyword 'jzhou': 22
add keyword 'z': 6
add keyword 'x': 4

复制代码

变量

(1)、变量作用域

python能够改变变量作用域的代码段是def、class、lamda

复制代码

>>> def scopetest():localvar=6;print(localvar)>>> scopetest()
6
>>> scopetest(localvar)  #在函数外不能访问lcoalvarTraceback (most recent call last):File "<pyshell#74>", line 1, in <module>scopetest(localvar)
NameError: name 'localvar' is not defined

复制代码

if/elif/else、try/except/finally、for/while 并不能涉及变量作用域的更改,也就是说他们的代码块中的变量,在外部也是可以访问的

复制代码

>>> if True:a=3print a
else: print 'not equals 3'3
>>> a  #外部也可以访问
3

复制代码

(2)、局部变量和全局变量

复制代码

#局部变量
>>> def func(x):print 'x is', xx = 2print 'Changed local x to', x>>> x=50
>>> func(x)
x is 50
Changed local x to 2
>>> x
50
#全局变量
>>> def func():global x   #定义全局变量xprint 'x is', xx = 2print 'Changed local x to', x>>> x=50
>>> func()
x is 50
Changed local x to 2
>>> x
2

复制代码

lambda匿名函数

  使用方法:lambda [arg1[,arg2,arg3,...,argn]] : expression

复制代码

>>> Factorial = lambda x: x > 1 and x * Factorial(x - 1) or 1   # x>1时求x的阶乘,其它返回1
>>> print Factorial(6)  # 6!
720
>>> max = lambda a, b: (a > b) and a or b  # a>b时返回a,否则返回b
>>> print max(2,4)
4
>>> x,y=11,12
>>> print (lambda:x+y)() #使用默认的x,y
23
>>> print (lambda x:x+y)(x)  #传的参数是x,y使用默认的12
23
>>> print (lambda x:x+y)(y)  #传的参数是y,则y替换x
24

复制代码

Generator生成器

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

复制代码

>>> def gen(n):for i in xrange(n):yield i>>> g=gen(5)  
>>> g.next()
0
>>> g.next()
1
>>> for x in g:print x2
3
4
>>> print g.next()Traceback (most recent call last):File "<pyshell#128>", line 1, in <module>print g.next()
StopIteration  #迭代已停止

复制代码

Iterations迭代器 

  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()Traceback (most recent call last):File "<pyshell#134>", line 1, in <module>print I.next()
StopIteration   #迭代停止
>>> for x in I: print (x)  #已经迭代完了>>> Y=iter(L)
>>> while True:try:X=next(Y)except StopIteration:breakprint X**21
4
9>>> R=range(3)  # R=[0,1,2] 列表
>>> I1,I2=iter(R),iter(R)
>>> print next(I1),next(I1),next(I2)
0 1 0

复制代码

内建函数

(1)、enumerate函数 ——获得数组,或列表的索引及值

复制代码

>>> string = 'hello'
>>> print list(enumerate(string))
[(0, 'h'), (1, 'e'), (2, 'l'), (3, 'l'), (4, 'o')]
>>> for index,value in enumerate(string):print index, value0 h
1 e
2 l
3 l
4 o

复制代码

(2)、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))
[5, 7, 11, 13, 17, 19, 23]

(3)、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')]

(4)、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

(5)、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))

复制代码

(6)、type函数——得到对象的类型

复制代码

>>> type(12)
<type 'int'>
>>> type('hello')
<type 'str'>
>>> type(type(42))
<type 'type'>
>>> type([].append)
<type 'builtin_function_or_method'>

复制代码

(7)、cmp函数——比较两个对象是否相等

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

(8)、类型转换

复制代码

#类型转换
>>> float(4)
4.0
>>> complex (2.4,8)  #转换为复数
(2.4+8j)
>>> coerce(1j,123)  #复数表示
(1j, (123+0j))
#ASCII转换
>>> ord('s')
115
>>> chr(115)
's'
#进制转换
>>> hex(255)  #16进制
'0xff'
>>> oct(255)   #8进制
'0377'

这篇关于Python学习笔记(六)——函数 Cyrus的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/349356

相关文章

Python开发文字版随机事件游戏的项目实例

《Python开发文字版随机事件游戏的项目实例》随机事件游戏是一种通过生成不可预测的事件来增强游戏体验的类型,在这篇博文中,我们将使用Python开发一款文字版随机事件游戏,通过这个项目,读者不仅能够... 目录项目概述2.1 游戏概念2.2 游戏特色2.3 目标玩家群体技术选择与环境准备3.1 开发环境3

Python中模块graphviz使用入门

《Python中模块graphviz使用入门》graphviz是一个用于创建和操作图形的Python库,本文主要介绍了Python中模块graphviz使用入门,具有一定的参考价值,感兴趣的可以了解一... 目录1.安装2. 基本用法2.1 输出图像格式2.2 图像style设置2.3 属性2.4 子图和聚

Python使用Matplotlib绘制3D曲面图详解

《Python使用Matplotlib绘制3D曲面图详解》:本文主要介绍Python使用Matplotlib绘制3D曲面图,在Python中,使用Matplotlib库绘制3D曲面图可以通过mpl... 目录准备工作绘制简单的 3D 曲面图绘制 3D 曲面图添加线框和透明度控制图形视角Matplotlib

Pandas中统计汇总可视化函数plot()的使用

《Pandas中统计汇总可视化函数plot()的使用》Pandas提供了许多强大的数据处理和分析功能,其中plot()函数就是其可视化功能的一个重要组成部分,本文主要介绍了Pandas中统计汇总可视化... 目录一、plot()函数简介二、plot()函数的基本用法三、plot()函数的参数详解四、使用pl

一文教你Python如何快速精准抓取网页数据

《一文教你Python如何快速精准抓取网页数据》这篇文章主要为大家详细介绍了如何利用Python实现快速精准抓取网页数据,文中的示例代码简洁易懂,具有一定的借鉴价值,有需要的小伙伴可以了解下... 目录1. 准备工作2. 基础爬虫实现3. 高级功能扩展3.1 抓取文章详情3.2 保存数据到文件4. 完整示例

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

基于Python打造一个智能单词管理神器

《基于Python打造一个智能单词管理神器》这篇文章主要为大家详细介绍了如何使用Python打造一个智能单词管理神器,从查询到导出的一站式解决,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. 项目概述:为什么需要这个工具2. 环境搭建与快速入门2.1 环境要求2.2 首次运行配置3. 核心功能使用指

Python实现微信自动锁定工具

《Python实现微信自动锁定工具》在数字化办公时代,微信已成为职场沟通的重要工具,但临时离开时忘记锁屏可能导致敏感信息泄露,下面我们就来看看如何使用Python打造一个微信自动锁定工具吧... 目录引言:当微信隐私遇到自动化守护效果展示核心功能全景图技术亮点深度解析1. 无操作检测引擎2. 微信路径智能获

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

利用Python打造一个Excel记账模板

《利用Python打造一个Excel记账模板》这篇文章主要为大家详细介绍了如何使用Python打造一个超实用的Excel记账模板,可以帮助大家高效管理财务,迈向财富自由之路,感兴趣的小伙伴快跟随小编一... 目录设置预算百分比超支标红预警记账模板功能介绍基础记账预算管理可视化分析摸鱼时间理财法碎片时间利用财