Python学习心路历程-day3

学习内容

1.集合及其操作

2.文件操作

3.字符转编码操作

4.函数介绍

5.递归

6.返回值

7.高阶函数

8.内置参数

1.集合及其操作                                                                                 

集合是一个无序的,不重复的数据组合,它的主要作用如下:

  • 去重,把一个列表变成集合,就自动去重了
  • 关系测试,测试两组数据之前的交集、差集、并集等关系

常用操作

s = set([3,5,9,10])      #创建一个数值集合  

t = set("Hello")         #创建一个唯一字符的集合  


a = t | s          # t 和 s的并集  

b = t & s          # t 和 s的交集  

c = t – s          # 求差集(项在t中,但不在s中)  

d = t ^ s          # 对称差集(项在t或s中,但不会同时出现在二者中)  



基本操作:

t.add('x')            # 添加一项  

s.update([10,37,42])  # 在s中添加多项  



使用remove()可以删除一项:

t.remove('H')


len(s)
set 的长度

x in s
测试 x 是否是 s 的成员

x not in s
测试 x 是否不是 s 的成员

s.issubset(t)
s <= t
测试是否 s 中的每一个元素都在 t 中

s.issuperset(t)
s >= t
测试是否 t 中的每一个元素都在 s 中

s.union(t)
s | t
返回一个新的 set 包含 s 和 t 中的每一个元素

s.intersection(t)
s & t
返回一个新的 set 包含 s 和 t 中的公共元素

s.difference(t)
s - t
返回一个新的 set 包含 s 中有但是 t 中没有的元素

s.symmetric_difference(t)
s ^ t
返回一个新的 set 包含 s 和 t 中不重复的元素

s.copy()
返回 set “s”的一个浅复制
View Code

2.文件操作                                                                                        

对文件操作流程

  1. 打开文件,得到文件句柄并赋值给一个变量
  2. 通过句柄对文件进行操作
  3. 关闭文件

现有文件如下 :

Somehow, it seems the love I knew was always the most destructive kind
不知为何,我经历的爱情总是最具毁灭性的的那种
Yesterday when I was young
昨日当我年少轻狂
The taste of life was sweet
生命的滋味是甜的
As rain upon my tongue
就如舌尖上的雨露
I teased at life as if it were a foolish game
我戏弄生命 视其为愚蠢的游戏
The way the evening breeze
就如夜晚的微风
May tease the candle flame
逗弄蜡烛的火苗
The thousand dreams I dreamed
我曾千万次梦见
The splendid things I planned
那些我计划的绚丽蓝图
I always built to last on weak and shifting sand
但我总是将之建筑在易逝的流沙上
I lived by night and shunned the naked light of day
我夜夜笙歌 逃避白昼赤裸的阳光
And only now I see how the time ran away
事到如今我才看清岁月是如何匆匆流逝
Yesterday when I was young
昨日当我年少轻狂
So many lovely songs were waiting to be sung
有那么多甜美的曲儿等我歌唱
So many wild pleasures lay in store for me
有那么多肆意的快乐等我享受
And so much pain my eyes refused to see
还有那么多痛苦 我的双眼却视而不见
I ran so fast that time and youth at last ran out
我飞快地奔走 最终时光与青春消逝殆尽
I never stopped to think what life was all about
我从未停下脚步去思考生命的意义
And every conversation that I can now recall
如今回想起的所有对话
Concerned itself with me and nothing else at all
除了和我相关的 什么都记不得了
The game of love I played with arrogance and pride
我用自负和傲慢玩着爱情的游戏
And every flame I lit too quickly, quickly died
所有我点燃的火焰都熄灭得太快
The friends I made all somehow seemed to slip away
所有我交的朋友似乎都不知不觉地离开了
And only now I'm left alone to end the play, yeah
只剩我一个人在台上来结束这场闹剧
Oh, yesterday when I was young
噢 昨日当我年少轻狂
So many, many songs were waiting to be sung
有那么那么多甜美的曲儿等我歌唱
So many wild pleasures lay in store for me
有那么多肆意的快乐等我享受
And so much pain my eyes refused to see
还有那么多痛苦 我的双眼却视而不见
There are so many songs in me that won't be sung
我有太多歌曲永远不会被唱起
I feel the bitter taste of tears upon my tongue
我尝到了舌尖泪水的苦涩滋味
The time has come for me to pay for yesterday
终于到了付出代价的时间 为了昨日
When I was young
当我年少轻狂
View Code

基本操作

f = open('lyrics') #打开文件
first_line = f.readline()
print('first line:',first_line) #读一行
print('我是分隔线'.center(50,'-'))
data = f.read()# 读取剩下的所有内容,文件大时不要用
print(data) #打印文件
f.close() #关闭文件
View Code
读取键盘输入

Python提供了两个内置函数从标准输入读入一行文本,默认的标准输入是键盘。如下:

  • raw_input(python 2.x)
  • input (python 3.x)
raw_input函数

raw_input([prompt]) 函数从标准输入读取一个行,并返回一个字符串(去掉结尾的换行符):

#!/usr/bin/python
# -*- coding: UTF-8 -*- 

str = raw_input("请输入:");
print "你输入的内容是: ", str
View Code

这将提示你输入任意字符串,然后在屏幕上显示相同的字符串。当我输入"Hello Python!",它的输出如下:

请输入:Hello Python!
你输入的内容是:  Hello Python!
View Code
input函数

input([prompt]) 函数和 raw_input([prompt]) 函数基本类似,但是 input 可以接收一个Python表达式作为输入,并将运算结果返回。

#!/usr/bin/python
# -*- coding: UTF-8 -*- 

str = input("请输入:");
print "你输入的内容是: ", str
View Code

这会产生如下的对应着输入的结果:

请输入:[x*5 for x in range(2,10,2)]
你输入的内容是:  [10, 20, 30, 40]
View Code
打开和关闭文件

现在,您已经可以向标准输入和输出进行读写。现在,来看看怎么读写实际的数据文件。

Python 提供了必要的函数和方法进行默认情况下的文件基本操作。你可以用 file 对象做大部分的文件操作。

open 函数

你必须先用Python内置的open()函数打开一个文件,创建一个file对象,相关的方法才可以调用它进行读写。

语法:

file object = open(file_name [, access_mode][, buffering])
View Code

各个参数的细节如下:

  • file_name:file_name变量是一个包含了你要访问的文件名称的字符串值。
  • access_mode:access_mode决定了打开文件的模式:只读,写入,追加等。所有可取值见如下的完全列表。这个参数是非强制的,默认文件访问模式为只读(r)。
  • buffering:如果buffering的值被设为0,就不会有寄存。如果buffering的值取1,访问文件时会寄存行。如果将buffering的值设为大于1的整数,表明了这就是的寄存区的缓冲大小。如果取负值,寄存区的缓冲大小则为系统默认。

不同模式打开文件的完全列表:

File对象的属性

一个文件被打开后,你有一个file对象,你可以得到有关该文件的各种信息。

以下是和file对象相关的所有属性的列表:

如下实例:

  1 #!/usr/bin/python
  2 # -*- coding: UTF-8 -*-
  3 
  4 # 打开一个文件
  5 fo = open("foo.txt", "wb")
  6 print "文件名: ", fo.name
  7 print "是否已关闭 : ", fo.closed
  8 print "访问模式 : ", fo.mode
  9 print "末尾是否强制加空格 : ", fo.softspace
View Code

以上实例输出结果:

  1 文件名:  foo.txt
  2 是否已关闭 :  False
  3 访问模式 :  wb
  4 末尾是否强制加空格 :  0
View Code
close()方法

File 对象的 close()方法刷新缓冲区里任何还没写入的信息,并关闭该文件,这之后便不能再进行写入。

当一个文件对象的引用被重新指定给另一个文件时,Python 会关闭之前的文件。用 close()方法关闭文件是一个很好的习惯。

语法:

fileObject.close();
View Code

例子:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 打开一个文件
fo = open("foo.txt", "wb")
print "文件名: ", fo.name

# 关闭打开的文件
fo.close()
View Code

以上实例输出结果:

文件名:  foo.txt
View Code

读写文件:

file对象提供了一系列方法,能让我们的文件访问更轻松。来看看如何使用read()和write()方法来读取和写入文件。

write()方法

write()方法可将任何字符串写入一个打开的文件。需要重点注意的是,Python字符串可以是二进制数据,而不是仅仅是文字。

write()方法不会在字符串的结尾添加换行符('\n'):

语法:

fileObject.write(string);
View Code

在这里,被传递的参数是要写入到已打开文件的内容。

例子:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 打开一个文件
fo = open("foo.txt", "wb")
fo.write( "www.runoob.com!\nVery good site!\n");

# 关闭打开的文件
fo.close()
View Code

上述方法会创建foo.txt文件,并将收到的内容写入该文件,并最终关闭文件。如果你打开这个文件,将看到以下内容:

$ cat foo.txt
www.runoob.com!
Very good site!
View Code
read()方法

read()方法从一个打开的文件中读取一个字符串。需要重点注意的是,Python字符串可以是二进制数据,而不是仅仅是文字。

语法:

fileObject.read([count]);
View Code

在这里,被传递的参数是要从已打开文件中读取的字节计数。该方法从文件的开头开始读入,如果没有传入count,它会尝试尽可能多地读取更多的内容,很可能是直到文件的末尾。

例子:

这里我们用到以上创建的 foo.txt 文件。

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 打开一个文件
fo = open("foo.txt", "r+")
str = fo.read(10);
print "读取的字符串是 : ", str
# 关闭打开的文件
fo.close()
View Code

以上实例输出结果:

读取的字符串是 :  www.runoob
View Code

文件位置:

文件定位

tell()方法告诉你文件内的当前位置;换句话说,下一次的读写会发生在文件开头这么多字节之后。

seek(offset [,from])方法改变当前文件的位置。Offset变量表示要移动的字节数。From变量指定开始移动字节的参考位置。

如果from被设为0,这意味着将文件的开头作为移动字节的参考位置。如果设为1,则使用当前的位置作为参考位置。如果它被设为2,那么该文件的末尾将作为参考位置。

例子:

就用我们上面创建的文件foo.txt。

  1 #!/usr/bin/python
  2 # -*- coding: UTF-8 -*-
  3 
  4 # 打开一个文件
  5 fo = open("foo.txt", "r+")
  6 str = fo.read(10);
  7 print "读取的字符串是 : ", str
  8 
  9 # 查找当前位置
 10 position = fo.tell();
 11 print "当前文件位置 : ", position
 12 
 13 # 把指针再次重新定位到文件开头
 14 position = fo.seek(0, 0);
 15 str = fo.read(10);
 16 print "重新读取字符串 : ", str
 17 # 关闭打开的文件
 18 fo.close()
View Code

以上实例输出结果:

读取的字符串是 :  www.runoob
当前文件位置 :  10
重新读取字符串 :  www.runoob
View Code

打开文件的模式有:

  • r,只读模式(默认)。
  • w,只写模式。【不可读;不存在则创建;存在则删除内容;】
  • a,追加模式。【可读;   不存在则创建;存在则只追加内容;】

"+" 表示可以同时读写某个文件

  • r+,可读写文件。【可读;可写;可追加】
  • w+,写读
  • a+,同a

"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)

  • rU
  • r+U

"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)

  • rb
  • wb
  • ab

其它语法

def close(self): # real signature unknown; restored from __doc__
        """
        Close the file.

        A closed file cannot be used for further I/O operations.  close() may be
        called more than once without error.
        """
        pass

    def fileno(self, *args, **kwargs): # real signature unknown
        """ Return the underlying file descriptor (an integer). """
        pass

    def isatty(self, *args, **kwargs): # real signature unknown
        """ True if the file is connected to a TTY device. """
        pass

    def read(self, size=-1): # known case of _io.FileIO.read
        """
        注意,不一定能全读回来
        Read at most size bytes, returned as bytes.

        Only makes one system call, so less data may be returned than requested.
        In non-blocking mode, returns None if no data is available.
        Return an empty bytes object at EOF.
        """
        return ""

    def readable(self, *args, **kwargs): # real signature unknown
        """ True if file was opened in a read mode. """
        pass

    def readall(self, *args, **kwargs): # real signature unknown
        """
        Read all data from the file, returned as bytes.

        In non-blocking mode, returns as much as is immediately available,
        or None if no data is available.  Return an empty bytes object at EOF.
        """
        pass

    def readinto(self): # real signature unknown; restored from __doc__
        """ Same as RawIOBase.readinto(). """
        pass #不要用,没人知道它是干嘛用的

    def seek(self, *args, **kwargs): # real signature unknown
        """
        Move to new file position and return the file position.

        Argument offset is a byte count.  Optional argument whence defaults to
        SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values
        are SEEK_CUR or 1 (move relative to current position, positive or negative),
        and SEEK_END or 2 (move relative to end of file, usually negative, although
        many platforms allow seeking beyond the end of a file).

        Note that not all file objects are seekable.
        """
        pass

    def seekable(self, *args, **kwargs): # real signature unknown
        """ True if file supports random-access. """
        pass

    def tell(self, *args, **kwargs): # real signature unknown
        """
        Current file position.

        Can raise OSError for non seekable files.
        """
        pass

    def truncate(self, *args, **kwargs): # real signature unknown
        """
        Truncate the file to at most size bytes and return the truncated size.

        Size defaults to the current file position, as returned by tell().
        The current file position is changed to the value of size.
        """
        pass

    def writable(self, *args, **kwargs): # real signature unknown
        """ True if file was opened in a write mode. """
        pass

    def write(self, *args, **kwargs): # real signature unknown
        """
        Write bytes b to file, return number written.

        Only makes one system call, so not all of the data may be written.
        The number of bytes actually written is returned.  In non-blocking mode,
        returns None if the write would block.
        """
        pass
View Code

with语句

为了避免打开文件后忘记关闭,可以通过管理上下文,即:

  1 with open('log','r') as f:
  2 
  3     ...
View Code

如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。

在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:

  1 with open('log1') as obj1, open('log2') as obj2:
  2 
  3     pass
View Code
3. 字符编码与转码                                                                             

详细文章:

http://www.cnblogs.com/yuanchenqi/articles/5956943.html

http://www.diveintopython3.net/strings.html

需知:

1.在python2默认编码是ASCII, python3里默认是unicode

2.unicode 分为 utf-32(占4个字节),utf-16(占两个字节),utf-8(占1-4个字节), so utf-16就是现在最常用的unicode版本, 不过在文件里存的还是utf-8,因为utf8省空间

3.在py3中encode,在转码的同时还会把string 变成bytes类型,decode在解码的同时还会把bytes变回string

上图仅适用于py2

  1 #!/user/bin/env python
  2 # -*- coding: UTF-8 -*-
  3 # Author: cs
  4 import sys
  5 print(sys.getdefaultencoding())
  6 
  7 
  8 msg = "我爱北京天安门"
  9 msg_gb2312 = msg.decode("utf-8").encode("gb2312")
 10 gb2312_to_gbk = msg_gb2312.decode("gbk").encode("gbk")
 11 
 12 print(msg)
 13 print(msg_gb2312)
 14 print(gb2312_to_gbk)
 15 
 16 in python2
View Code
  1 # Author: cs
  2 import sys
  3 print(sys.getdefaultencoding())
  4 
  5 
  6 msg = "我爱北京天安门"
  7 #msg_gb2312 = msg.decode("utf-8").encode("gb2312")
  8 msg_gb2312 = msg.encode("gb2312") #默认就是unicode,不用再decode
  9 gb2312_to_unicode = msg_gb2312.decode("gb2312")
 10 gb2312_to_utf8 = msg_gb2312.decode("gb2312").encode("utf-8")
 11 
 12 print(msg)
 13 print(msg_gb2312)
 14 print(gb2312_to_unicode)
 15 print(gb2312_to_utf8)
View Code

4.函数介绍                                                                                        

函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段。

函数能提高应用的模块性,和代码的重复利用率。你已经知道Python提供了许多内建函数,比如print()。但你也可以自己创建函数,这被叫做用户自定义函数。

定义一个函数

你可以定义一个由自己想要功能的函数,以下是简单的规则:

  • 函数代码块以 def 关键词开头,后接函数标识符名称和圆括号()
  • 任何传入参数和自变量必须放在圆括号中间。圆括号之间可以用于定义参数。
  • 函数的第一行语句可以选择性地使用文档字符串—用于存放函数说明。
  • 函数内容以冒号起始,并且缩进。
  • return [表达式] 结束函数,选择性地返回一个值给调用方。不带表达式的return相当于返回 None。
语法
def functionname( parameters ):
   "函数_文档字符串"
   function_suite
   return [expression]
View Code

默认情况下,参数值和参数名称是按函数声明中定义的的顺序匹配起来的。

例子:

def printme( str ):
   "打印传入的字符串到标准显示设备上"
   print str
   return
View Code
函数调用

定义一个函数只给了函数一个名称,指定了函数里包含的参数,和代码块结构。

这个函数的基本结构完成以后,你可以通过另一个函数调用执行,也可以直接从Python提示符执行。

如下实例调用了printme()函数:

  1 #!/usr/bin/python
  2 # -*- coding: UTF-8 -*-
  3 
  4 # 定义函数
  5 def printme( str ):
  6    "打印任何传入的字符串"
  7    print str;
  8    return;
  9 
 10 # 调用函数
 11 printme("我要调用用户自定义函数!");
 12 printme("再次调用同一函数");
View Code

以上实例输出结果:

我要调用用户自定义函数!
再次调用同一函数
View Code
参数传递

在 python 中,类型属于对象,变量是没有类型的:

a=[1,2,3]
a="Runoob"
View Code

以上代码中,[1,2,3] 是 List 类型,"Runoob" 是 String 类型,而变量 a 是没有类型,她仅仅是一个对象的引用(一个指针),可以是 List 类型对象,也可以指向 String 类型对象。

可更改(mutable)与不可更改(immutable)对象

在 python 中,strings, tuples, 和 numbers 是不可更改的对象,而 list,dict 等则是可以修改的对象。

  • 不可变类型:变量赋值 a=5 后再赋值 a=10,这里实际是新生成一个 int 值对象 10,再让 a 指向它,而 5 被丢弃,不是改变a的值,相当于新生成了a。

  • 可变类型:变量赋值 la=[1,2,3,4] 后再赋值 la[2]=5 则是将 list la 的第三个元素值更改,本身la没有动,只是其内部的一部分值被修改了。

python 函数的参数传递:

  • 不可变类型:类似 c++ 的值传递,如 整数、字符串、元组。如fun(a),传递的只是a的值,没有影响a对象本身。比如在 fun(a)内部修改 a 的值,只是修改另一个复制的对象,不会影响 a 本身。

  • 可变类型:类似 c++ 的引用传递,如 列表,字典。如 fun(la),则是将 la 真正的传过去,修改后fun外部的la也会受影响

python 中一切都是对象,严格意义我们不能说值传递还是引用传递,我们应该说传不可变对象和传可变对象。

python 传不可变对象实例
#!/usr/bin/python
# -*- coding: UTF-8 -*-

def ChangeInt( a ):
    a = 10

b = 2
ChangeInt(b)
print b # 结果是 2
View Code

实例中有 int 对象 2,指向它的变量是 b,在传递给 ChangeInt 函数时,按传值的方式复制了变量 b,a 和 b 都指向了同一个 Int 对象,在 a=10 时,则新生成一个 int 值对象 10,并让 a 指向它。

传可变对象实例
  1 #!/usr/bin/python
  2 # -*- coding: UTF-8 -*-
  3 
  4 # 可写函数说明
  5 def changeme( mylist ):
  6    "修改传入的列表"
  7    mylist.append([1,2,3,4]);
  8    print "函数内取值: ", mylist
  9    return
 10 
 11 # 调用changeme函数
 12 mylist = [10,20,30];
 13 changeme( mylist );
 14 print "函数外取值: ", mylist
View Code

实例中传入函数的和在末尾添加新内容的对象用的是同一个引用,故输出结果如下:

函数内取值:  [10, 20, 30, [1, 2, 3, 4]]
函数外取值:  [10, 20, 30, [1, 2, 3, 4]]
View Code
参数

以下是调用函数时可使用的正式参数类型:

  • 必备参数
  • 关键字参数
  • 默认参数
  • 不定长参数
必备参数

必备参数须以正确的顺序传入函数。调用时的数量必须和声明时的一样。

调用printme()函数,你必须传入一个参数,不然会出现语法错误:

  1 #!/usr/bin/python
  2 # -*- coding: UTF-8 -*-
  3 
  4 #可写函数说明
  5 def printme( str ):
  6    "打印任何传入的字符串"
  7    print str;
  8    return;
  9 
 10 #调用printme函数
 11 printme();
View Code

以上实例输出结果:

Traceback (most recent call last):
  File "test.py", line 11, in <module>
    printme();
TypeError: printme() takes exactly 1 argument (0 given)
View Code
关键字参数

关键字参数和函数调用关系紧密,函数调用使用关键字参数来确定传入的参数值。

使用关键字参数允许函数调用时参数的顺序与声明时不一致,因为 Python 解释器能够用参数名匹配参数值。

以下实例在函数 printme() 调用时使用参数名:

  1 #!/usr/bin/python
  2 # -*- coding: UTF-8 -*-
  3 
  4 #可写函数说明
  5 def printme( str ):
  6    "打印任何传入的字符串"
  7    print str;
  8    return;
  9 
 10 #调用printme函数
 11 printme( str = "My string");
View Code

以上实例输出结果:

My string
View Code

下例能将关键字参数顺序不重要展示得更清楚:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

#可写函数说明
def printinfo( name, age ):
   "打印任何传入的字符串"
   print "Name: ", name;
   print "Age ", age;
   return;

#调用printinfo函数
printinfo( age=50, name="miki" );
View Code

以上实例输出结果:

Name:  miki
Age  50
View Code
缺省参数

调用函数时,缺省参数的值如果没有传入,则被认为是默认值。下例会打印默认的age,如果age没有被传入:

  1 #!/usr/bin/python
  2 # -*- coding: UTF-8 -*-
  3 
  4 #可写函数说明
  5 def printinfo( name, age = 35 ):
  6    "打印任何传入的字符串"
  7    print "Name: ", name;
  8    print "Age ", age;
  9    return;
 10 
 11 #调用printinfo函数
 12 printinfo( age=50, name="miki" );
 13 printinfo( name="miki" );
View Code

以上实例输出结果:

Name:  miki
Age  50
Name:  miki
Age  35
View Code
不定长参数

你可能需要一个函数能处理比当初声明时更多的参数。这些参数叫做不定长参数,和上述2种参数不同,声明时不会命名。基本语法如下:

def functionname([formal_args,] *var_args_tuple ):
   "函数_文档字符串"
   function_suite
   return [expression]
View Code

加了星号(*)的变量名会存放所有未命名的变量参数。选择不多传参数也可。如下实例:

  1 #!/usr/bin/python
  2 # -*- coding: UTF-8 -*-
  3 
  4 # 可写函数说明
  5 def printinfo( arg1, *vartuple ):
  6    "打印任何传入的参数"
  7    print "输出: "
  8    print arg1
  9    for var in vartuple:
 10       print var
 11    return;
 12 
 13 # 调用printinfo 函数
 14 printinfo( 10 );
 15 printinfo( 70, 60, 50 );
View Code

以上实例输出结果:

输出:
10
输出:
70
60
50
View Code
变量作用域

一个程序的所有的变量并不是在哪个位置都可以访问的。访问权限决定于这个变量是在哪里赋值的。

变量的作用域决定了在哪一部分程序你可以访问哪个特定的变量名称。两种最基本的变量作用域如下:

  • 全局变量
  • 局部变量
全局变量和局部变量

定义在函数内部的变量拥有一个局部作用域,定义在函数外的拥有全局作用域。

局部变量只能在其被声明的函数内部访问,而全局变量可以在整个程序范围内访问。调用函数时,所有在函数内声明的变量名称都将被加入到作用域中。如下实例:

  1 #!/usr/bin/python
  2 # -*- coding: UTF-8 -*-
  3 
  4 total = 0; # 这是一个全局变量
  5 # 可写函数说明
  6 def sum( arg1, arg2 ):
  7    #返回2个参数的和."
  8    total = arg1 + arg2; # total在这里是局部变量.
  9    print "函数内是局部变量 : ", total
 10    return total;
 11 
 12 #调用sum函数
 13 sum( 10, 20 );
 14 print "函数外是全局变量 : ", total
View Code

以上实例输出结果:

函数内是局部变量 :  30
函数外是全局变量 :  0
View Code

5.递归                                                                                              

在函数内部,可以调用其他函数。如果一个函数在内部调用自身本身,这个函数就是递归函数。

def calc(n):
    print(n)
    if int(n/2) ==0:
        return n
    return calc(int(n/2))

calc(10)

输出:
10
5
2
1
View Code

递归特性:

1. 必须有一个明确的结束条件

2. 每次进入更深一层递归时,问题规模相比上次递归都应有所减少

3. 递归效率不高,递归层次过多会导致栈溢出(在计算机中,函数调用是通过栈(stack)这种数据结构实现的,每当进入一个函数调用,栈就会加一层栈帧,每当函数返回,栈就会减一层栈帧。由于栈的大小不是无限的,所以,递归调用的次数过多,会导致栈溢出)

堆栈扫盲http://www.cnblogs.com/lln7777/archive/2012/03/14/2396164.html 

 

递归函数实际应用案例,二分查找

  1 data = [1, 3, 6, 7, 9, 12, 14, 16, 17, 18, 20, 21, 22, 23, 30, 32, 33, 35]
  2 def binary_search(dataset,find_num):
  3     print(dataset)
  4     if len(dataset) >1:
  5         mid = int(len(dataset)/2)
  6         if dataset[mid] == find_num:  #find it
  7             print("找到数字",dataset[mid])
  8         elif dataset[mid] > find_num :# 找的数在mid左面
  9             print("\033[31;1m找的数在mid[%s]左面\033[0m" % dataset[mid])
 10             return binary_search(dataset[0:mid], find_num)
 11         else:# 找的数在mid右面
 12             print("\033[32;1m找的数在mid[%s]右面\033[0m" % dataset[mid])
 13             return binary_search(dataset[mid+1:],find_num)
 14     else:
 15         if dataset[0] == find_num:  #find it
 16             print("找到数字啦",dataset[0])
 17         else:
 18             print("没的分了,要找的数字[%s]不在列表里" % find_num)
 19 binary_search(data,66)
View Code
6.返回值                                                                                             

要想获取函数的执行结果,就可以用return语句把结果返回

注意:

  1. 函数在执行过程中只要遇到return语句,就会停止执行并返回结果,so 也可以理解为 return 语句代表着函数的结束
  2. 如果未在函数中指定return,那这个函数的返回值为None
7.高阶函数                                                                                        

变量可以指向函数,函数的参数能接收变量,那么一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数。

  1 def add(x,y,f):
  2     return f(x) + f(y)
  3 res = add(3,-6,abs)
  4 print(res)
View Code

8. 内置参数                                                                                        

内置参数详解 https://docs.python.org/3/library/functions.html?highlight=built#ascii 

  1 #compile
  2 f = open("函数递归.py")
  3 data =compile(f.read(),'','exec')
  4 exec(data)
  5 
  6 
  7 #print
  8 msg = "又回到最初的起点"
  9 f = open("tofile","w")
 10 print(msg,"记忆中你青涩的脸",sep="|",end="",file=f)
 11 
 12 
 13 # #slice
 14 # a = range(20)
 15 # pattern = slice(3,8,2)
 16 # for i in a[pattern]: #等于a[3:8:2]
 17 #     print(i)
 18 #
 19 #
 20 
 21 
 22 #memoryview
 23 #usage:
 24 #>>> memoryview(b'abcd')
 25 #<memory at 0x104069648>
 26 #在进行切片并赋值数据时,不需要重新copy原列表数据,可以直接映射原数据内存,
 27 import time
 28 for n in (100000, 200000, 300000, 400000):
 29     data = b'x'*n
 30     start = time.time()
 31     b = data
 32     while b:
 33         b = b[1:]
 34     print('bytes', n, time.time()-start)
 35 
 36 for n in (100000, 200000, 300000, 400000):
 37     data = b'x'*n
 38     start = time.time()
 39     b = memoryview(data)
 40     while b:
 41         b = b[1:]
 42     print('memoryview', n, time.time()-start)
几个内置方法用法提醒

转载于:https://www.cnblogs.com/cs-qzyy/p/8628264.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值