zoukankan      html  css  js  c++  java
  • python成长之路第三篇(1)_初识函数

    目录:

    函数

    1. 为什么要使用函数
    2. 什么是函数
    3. 函数的返回值
    4. 文档化函数
    5. 函数传参数

    文件操作(二)

    1、文件操作的步骤

    2、文件的内置方法

    函数:

    一、为什么要使用函数

    在日常写代码中,我们会发现有很多代码是重复利用的,这样会使我们的代码变得异常臃肿,比如说:

    我们要写一个验证码的功能

    例子:

    比如说我们要进行一些操作,而这些操作需要填写验证码

    验证码代码

     1 import random
     2 number_check = ''
     3 for i in range(0,6):
     4     number_curr = random.randrange(0,5)
     5     if number_curr != i:
     6         number_temp = chr(random.randint(97,122))
     7     else:
     8         number_temp = random.randint(0,9)
     9     number_check += str(number_temp)
    10 先不用管这段代码什么意思,后续会提到
    验证码实现代码
    例子代码:
     验证码代码
     功能1
     验证码代码
     功能2
     验证码代码
     功能3
    这段文字呢就表示没写一个功能,加入这个功能需要验证码,就需要在这个功能上加判断这样大大增加了代码量
    所以呢就产生了函数

    二、什么是函数

    函数准确的来说就是实现某个功能的代码的集合

    那么我们接着上面的例子来写把验证码模块变成一个函数

     1 import random
     2 
     3 def code():#其实这家伙是个伪函数,因为没有返回值
     4 
     5    number_check = ''
     6    for i in range(0,6):
     7        number_curr = random.randrange(0,5)
     8        if number_curr != i:
     9            number_temp = chr(random.randint(97,122))
    10        else:
    11            number_temp = random.randint(0,9)
    12        number_check += str(number_temp)
    验证码函数
    那么我们功能来去调用函数的时候只需要这样
      import random
      code():
      功能1
      code():
      功能2
      code():
      功能3
    代码如下:
     1 import random
     2 def code():
     3     number_check = ''
     4     for i in range(0,6):
     5         number_curr = random.randrange(0,5)
     6         if number_curr != i:
     7             number_temp = chr(random.randint(97,122))
     8         else:
     9             number_temp = random.randint(0,9)
    10         number_check += str(number_temp)
    11     print(number_check)
    12 code()
    随机验证码

    #这样我们每次运行就能看到一个随机的字符,那么我们怎么拿到这个随机的字符呢

    三、函数的返回值(return)

    上一小节我们学习了怎么来创建一个函数和怎么调用一个函数那么我们来看看怎么拿到函数的返回值

    接着我们上面的例子:

     1 import random#别忘了我!
     2 def code():
     3     number_check = ''#设置一个空变量
     4     for i in range(0,6): #循环0到6也就是6次
     5         number_curr = random.randrange(0,5)#生成一个随机数
     6         if number_curr != i: #判断当前循环次数与随机生成的数是否一样
     7             number_temp = chr(random.randint(97,122))#如果不一样则生成随机数97-122并转化成字母
     8         else:#否则
     9             number_temp = random.randint(0,9)#生成0到9的任意数字
    10         number_check += str(number_temp)#最后添加到变量中
    11     return number_check#原来加个这货就好了啊
    12 #那么如何调用和取到返回值呢
    13 
    14 a_code = code()
    15 print(a_code)
    返回值函数
     

    四、文档化函数

    什么叫做文档化函数,其实就是丫的注释!,只不过这货写在了函数里面在def关键字下面0.0,他的目的呢只是为了更好的注释这个函数的功能

    def code():
    'This is a function of generated random authentication code'
    pass
    pass


     

    五、函数传参数

    有的小伙伴思考来思考去发现我没办法往里面传入参数啊,这怎么可以那么下面我们就讲解传参

    函数分为三种:

    • 普通参数
    • 默认参数
    • 动态参数

    1、普通参数

    啥是普通参数,就是很普通的意思哈哈我们来看看普通参数

    还是以生成随机数为例:假如我们想自己规定这个随机验证码的长度

     1 import random
     2 def code(frequency):
     3     frequency = int(frequency)
     4     number_check = ''
     5     for i in range(0,frequency):
     6         number_curr = random.randrange(0,frequency)
     7         if number_curr != i:
     8             number_temp = chr(random.randint(97,122))
     9         else:
    10             number_temp = random.randint(0,9)
    11         number_check += str(number_temp)
    12     return number_check
    13 in_frequency = input("请输入次数长度:")
    14 a_code = code(in_frequency)
    15 print(a_code)
    随机数传参
    !!!发生了什么,原来def code(frequency)多了个参数下图详解,frequency在这里有个别名叫做形参(形式参数),而in_frequency叫做实参(实际参数),形式参数的值由实际参数提供
    image 

    2、默认参数
    如果说我们想给frequency来个默认值怎么办?def code(frequency = 3):其实就是加个等于号就好了这样在调用的时候就不需要加上实参了a_code = code()
    3、动态参数一

     问题来了,普通参数只能传一个值那么我想传多个值就需要写多个普通参数,就想这样def code(frequency,frequency1,frequency2):那么有没有进化的方法呢?其实我们可以这样:def code(*frequency):例子:

    1 def code(*frequency):
    2     print(frequency)
    3  in_frequency = [1,2,3,"dsa"]
    4 code(in_frequency)
    5 ([1, 2, 3, 'dsa'],)
    6 或者这么调用
    7 code(1,2,3,"dsa")
    动态参数一
    这样我们就可以传入多个参数了,注意的是传入的值之后会变成一个元组,元组是不可修改的哦。
    改动态参数的方法
    咳咳事情不是绝对的其实这个参数还是可以修改的不过我们就要用些小技巧,借助列表喽,原理就是改不了元组我改列表就是了
    def code(*frequency):
    frequency[0][0] = int(frequency[0][0])+1
    print(frequency)
    a = [10]
    code(a)
    ([11],)

    4、动态参数二

    某某小伙伴说那么那个字典能不能传进去。啪啪啪,答案是可以:例子:

    def code(**frequency):
         print(frequency)

    code(times=10)
    {'times': 10}
    最后我们来总结一下,一个基本的函数有一下几个特点:
    • def:表示函数的关键字
    • 函数名:表示函数的名称,并根据函数名调用函数
    • 函数体:这里也就是指得逻辑运算和注释
    • 参数:为函数传入数据
    • 返回值:经过函数执行完毕给调用者返回的结果

    文件操作(二):

    一.文件操作的步骤

    在成长之路第一篇的第五章曾将讲过了文件的一些操作,在这里呢我们既然了解到了函数那我们就一起来深入的看看文件操作

    首先来整理一下文件操作的几个步骤

    1、打开文件

    2、操作文件

    3、关闭文件

    打开文件

    对于打开文件来说python有两种方式:open()和file()本质上前者会调用后者,所以推荐用open,其次如果打开的文件要做跨平台操作的话我们就要使用二进制的方法来去打开,为什么呢?因为在windows和linux上的换行符不一样,在使用二进制来去操作文件python默认的机制会把在linux打开windows的文件会把windows下的换行符 转换成 ,同样windows打开linux的文件也是如此,如果非要用文本模式去读的话我们可以使用“U”来把换行符整理成

    打开文件的模式有

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

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

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

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

    • rU
    • r+U

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

    • rb
    • wb
    • ab

    有人总好忘记关闭文件释放资源,为了方便在python2.5中增加了with语句(2.5中需要导入如下模块才能使用'from_future_import with_statement'),并且在python2.7后with支持同时打开多个文件进行处理,并且不用再写讨厌的关闭文件语句了

    with:

    with open('l1') as A1, open('l2') as A2:

       pass

    这样我们就可以操作A1就是操作l1文件,操作A2就是操作l2文件

    文件操作源码:

      1 class file(object):
      2   
      3     def close(self): # real signature unknown; restored from __doc__
      4         关闭文件
      5         """
      6         close() -> None or (perhaps) an integer.  Close the file.
      7          
      8         Sets data attribute .closed to True.  A closed file cannot be used for
      9         further I/O operations.  close() may be called more than once without
     10         error.  Some kinds of file objects (for example, opened by popen())
     11         may return an exit status upon closing.
     12         """
     13  
     14     def fileno(self): # real signature unknown; restored from __doc__
     15         文件描述符  
     16          """
     17         fileno() -> integer "file descriptor".
     18          
     19         This is needed for lower-level file interfaces, such os.read().
     20         """
     21         return 0    
     22  
     23     def flush(self): # real signature unknown; restored from __doc__
     24         刷新文件内部缓冲区
     25         """ flush() -> None.  Flush the internal I/O buffer. """
     26         pass
     27  
     28  
     29     def isatty(self): # real signature unknown; restored from __doc__
     30         判断文件是否是同意tty设备
     31         """ isatty() -> true or false.  True if the file is connected to a tty device. """
     32         return False
     33  
     34  
     35     def next(self): # real signature unknown; restored from __doc__
     36         获取下一行数据,不存在,则报错
     37         """ x.next() -> the next value, or raise StopIteration """
     38         pass
     39  
     40     def read(self, size=None): # real signature unknown; restored from __doc__
     41         读取指定字节数据
     42         """
     43         read([size]) -> read at most size bytes, returned as a string.
     44          
     45         If the size argument is negative or omitted, read until EOF is reached.
     46         Notice that when in non-blocking mode, less data than what was requested
     47         may be returned, even if no size parameter was given.
     48         """
     49         pass
     50  
     51     def readinto(self): # real signature unknown; restored from __doc__
     52         读取到缓冲区,不要用,将被遗弃
     53         """ readinto() -> Undocumented.  Don't use this; it may go away. """
     54         pass
     55  
     56     def readline(self, size=None): # real signature unknown; restored from __doc__
     57         仅读取一行数据
     58         """
     59         readline([size]) -> next line from the file, as a string.
     60          
     61         Retain newline.  A non-negative size argument limits the maximum
     62         number of bytes to return (an incomplete line may be returned then).
     63         Return an empty string at EOF.
     64         """
     65         pass
     66  
     67     def readlines(self, size=None): # real signature unknown; restored from __doc__
     68         读取所有数据,并根据换行保存值列表
     69         """
     70         readlines([size]) -> list of strings, each a line from the file.
     71          
     72         Call readline() repeatedly and return a list of the lines so read.
     73         The optional size argument, if given, is an approximate bound on the
     74         total number of bytes in the lines returned.
     75         """
     76         return []
     77  
     78     def seek(self, offset, whence=None): # real signature unknown; restored from __doc__
     79         指定文件中指针位置
     80         """
     81         seek(offset[, whence]) -> None.  Move to new file position.
     82          
     83         Argument offset is a byte count.  Optional argument whence defaults to
     84         0 (offset from start of file, offset should be >= 0); other values are 1
     85         (move relative to current position, positive or negative), and 2 (move
     86         relative to end of file, usually negative, although many platforms allow
     87         seeking beyond the end of a file).  If the file is opened in text mode,
     88         only offsets returned by tell() are legal.  Use of other offsets causes
     89         undefined behavior.
     90         Note that not all file objects are seekable.
     91         """
     92         pass
     93  
     94     def tell(self): # real signature unknown; restored from __doc__
     95         获取当前指针位置
     96         """ tell() -> current file position, an integer (may be a long integer). """
     97         pass
     98  
     99     def truncate(self, size=None): # real signature unknown; restored from __doc__
    100         截断数据,仅保留指定之前数据
    101         """
    102         truncate([size]) -> None.  Truncate the file to at most size bytes.
    103          
    104         Size defaults to the current file position, as returned by tell().
    105         """
    106         pass
    107  
    108     def write(self, p_str): # real signature unknown; restored from __doc__
    109         写内容
    110         """
    111         write(str) -> None.  Write string str to file.
    112          
    113         Note that due to buffering, flush() or close() may be needed before
    114         the file on disk reflects the data written.
    115         """
    116         pass
    117  
    118     def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__
    119         将一个字符串列表写入文件
    120         """
    121         writelines(sequence_of_strings) -> None.  Write the strings to the file.
    122          
    123         Note that newlines are not added.  The sequence can be any iterable object
    124         producing strings. This is equivalent to calling write() for each string.
    125         """
    126         pass
    127  
    128     def xreadlines(self): # real signature unknown; restored from __doc__
    129         可用于逐行读取文件,非全部
    130         """
    131         xreadlines() -> returns self.
    132          
    133         For backward compatibility. File objects now include the performance
    134         optimizations previously implemented in the xreadlines module.
    135         """
    136         pass
    View Code
  • 相关阅读:
    如何从svn上down项目
    查看当前项目的svn地址
    项目启动失败
    新增sql后面可以跟where条件(多表关联新增数据和复制数据)
    递归思想之---斐波拉契数列
    递归思想之---阶乘算法
    java递归思想之---汉诺塔
    将 Docker 镜像体积减小 转载:https://mp.weixin.qq.com/s/kyK6652kchtudZHhSsYx_Q
    工具 转载 https://mp.weixin.qq.com/s/Y1RHEDu0vuH4qm9QtMISFg
    Kubernetes 学习笔记 权威指南第五&六章
  • 原文地址:https://www.cnblogs.com/bj-xy/p/5211364.html
Copyright © 2011-2022 走看看