函数基本操作

函数包括内置函数及自定义函数,用来实现单一或者相同功能的代码段,有效的提高了代码的可读性及重读利用率。语法如下:

def  函数名(参数):                 
     代码块

定义函数规则:

  • def关键字开头 ,与函数名以空格隔开
  • ()中可以自定义参数,参数个数可以为0~N个
  • ()后面必须跟冒号,代码块以冒号开始,且缩进
  • return表达式用来结束函数,不带return表达式的函数返回None

一、函数返回值

def  num():                #自定义函数
    a=10
    b=5
    print(a+b)
    return 666 
    print(a-b)

s=num()                   #调用函数,并将return返回的值赋予s
print(s)                  #---->输出 15  666

#调用函数时,执行过程中若遇到return则会退出函数,不会再执行return表达式后的语句

 二、参数传递

Python中参数传递采用的是传值和引用相结合的一种传值方法,具体传值方法由对象类型而定,若参数是可变对象类型(如dict、list),相当于采用了引用方式,就会修改对象的初始值;若是不可变对象类型(如int、str、tuple),相当于采用了传值方式,就不会修改对象的初始值。

参数大体概括为:普通参数、默认参数、动态参数

1. 普通参数

【示例1】
def  num():                #自定义函数,无参数
    a=10
    b=5
    print(a+b)
    return 666 
    print(a-b)

s=num()                   #调用函数,并将return返回的值赋予s
print(s)                  #输出15   666



【实例2】
def  num(a,b):                #自定义函数,2个参数
    print(a+b)
    return 666 
    print(a-b)

s=num(12,4)                   #调用函数,并将return返回的值赋予s
print(s)                      #输出16  666

 2. 默认参数

【示例1】
def  num(a,b=5):                 #定义函数,参数默认有指定值
    print(a,b)

num(6)                        #实参按照顺序依次对应形参,即a为6,输出6  5


【示例2】
def num(a,b=5):                
    print(a,b)

num(6,12)                  #实参依次对应形参,6对应a,12对应b,输出6   12


【示例3】
def num(a,b):
    print(a,b)

num(b=5,a=2)           #指定参数值,无序考虑参数的顺序,输出2   5

3. 动态参数

【示例1】
def num(*arg):                    #定义函数,不定长参数,*表示参数对象为元组类型
    print(arg,type(arg))

num(1,2,3,4)                       #将实参依次存入形参,形参类型为元组
                                           # 输出 (1,2,3,4)<class 'tuple'>

【示例2】
def  num(**arg):                #**表示参数对象为字典类型
    print(arg,type(arg))

num(a=11,b=22,c=33)             #输出一个字典{'a':11,'b':22,'c':33}<class 'dict'>


【示例3】
def num(*args,**kwargs):      #*args与**kwargs形参顺序不能调换
    print(args,**kwargs)

num(11,22,33,a=1,b=2,c=3)     #传参时实参也不能调换,如类似a=1这种实参不能放在前半部分
                              #输出(11,22,33){'a':1,'b':2,'c':3}

【示例4】
def num(*args,**kwargs):      #*args与**kwargs形参顺序不能调换
    print(args)
    print(**kwargs)

l=[11,22,33]
d={'a':1,'b':2,'c':3}
num(l,d)                      #传参时会直接传给第1个形参
                              #输出((11,22,33),{'a':1,'b':2,'c':3})    {}

【示例5】
def num(*args,**kwargs):      #*args与**kwargs形参顺序不能调换
    print(args)
    print(**kwargs)

l=[11,22,33]
d={'a':1,'b':2,'c':3}
num(*l,**d)                 #传参时变量前面需要加上*与**,方可对应传参
                             #输出(11,22,33)
                             #{'a':1,'b':2,'c':3}

使用动态参数还可实现字符串格式化:

【示例1】
str1='{0} is a {1}'                #定义字符串
L=['Tom','boy']
s=str1.format(*L)         #使用动态参数*格式化字符串,将list表中第1个元素分配给字符串中的位置0,第2个元素分配给字符窜中的位置1,以此类推
print(s)                      # 输出 Tom is a boy


【示例2】
str1s='{name} is a {sex}'         
dic={'name':'Tom','sex':'boy'}
s=str1.format(**dic)               #使用动态参数**格式化字符串,dic中的键值对依次对字符串进行格式化
print(s)                              #输出 TFalsem is a boy

三、lambda表达式

lambda函数也称为匿名函数,用来表达简单的函数,没有具体的函数名称,书写只能是一行

【示例】
foo=lambda  a,b:a+b      #lambda后 冒号之前a b表示形参,形参可以是多个,用逗号隔开;冒号后面是代码块,整个lambda表达式只能是一行,有return值
s=foo(10,20)
print(s)                 # 输出30

四、内置函数

python查看内置函数的方法:打开cmd--->输入python--->import   builtins--->dir(builtins),也可以直接dir(__builtins__)查看

open()文件操作模式:

文件操作方法:

class TextIOWrapper(_TextIOBase):
    """
    Character and line based layer over a BufferedIOBase object, buffer.
    
    encoding gives the name of the encoding that the stream will be
    decoded or encoded with. It defaults to locale.getpreferredencoding(False).
    
    errors determines the strictness of encoding and decoding (see
    help(codecs.Codec) or the documentation for codecs.register) and
    defaults to "strict".
    
    newline controls how line endings are handled. It can be None, '',
    '
', '
', and '
'.  It works as follows:
    
    * On input, if newline is None, universal newlines mode is
      enabled. Lines in the input can end in '
', '
', or '
', and
      these are translated into '
' before being returned to the
      caller. If it is '', universal newline mode is enabled, but line
      endings are returned to the caller untranslated. If it has any of
      the other legal values, input lines are only terminated by the given
      string, and the line ending is returned to the caller untranslated.
    
    * On output, if newline is None, any '
' characters written are
      translated to the system default line separator, os.linesep. If
      newline is '' or '
', no translation takes place. If newline is any
      of the other legal values, any '
' characters written are translated
      to the given string.
    
    If line_buffering is True, a call to flush is implied when a call to
    write contains a newline character.
    """
    def close(self, *args, **kwargs): # real signature unknown
        pass            #关闭文件

    def detach(self, *args, **kwargs): # real signature unknown
        pass           

    def fileno(self, *args, **kwargs): # real signature unknown
        pass            #文件描述符,返回一个int类型

    def flush(self, *args, **kwargs): # real signature unknown
        pass            #刷新缓冲区的内容,将缓冲区的内容写入硬盘

    def isatty(self, *args, **kwargs): # real signature unknown
        pass            #判断文件是否连接tty设备,返回bool值

    def read(self, *args, **kwargs): # real signature unknown
        pass           #读文件,后跟参数,表示读取字符长度

    def readable(self, *args, **kwargs): # real signature unknown
        pass          #判断文件是否可读,返回bool值

    def readline(self, *args, **kwargs): # real signature unknown
        pass         #读取一行数据,若指定读取长度,则返回指定长度的字符

    def seek(self, *args, **kwargs): # real signature unknown
        pass        #指定当前指针位置

    def seekable(self, *args, **kwargs): # real signature unknown
        pass

    def tell(self, *args, **kwargs): # real signature unknown
        pass       #查看文件操作标记的当前位置(即指针位置),按字节计算,如,当前tell()位置为0,读取1个汉字后,tell()会返回3

    def truncate(self, *args, **kwargs): # real signature unknown
        pass       #截取文件内容,将指针后的内容删除,并保存文件

    def writable(self, *args, **kwargs): # real signature unknown
        pass       #判断文件是否可写,返回bool值

    def write(self, *args, **kwargs): # real signature unknown
        pass       #将str写入文件,不会在str后加换行符

    def __getstate__(self, *args, **kwargs): # real signature unknown
        pass

    def __init__(self, *args, **kwargs): # real signature unknown
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __next__(self, *args, **kwargs): # real signature unknown
        """ Implement next(self). """
        pass

    def __repr__(self, *args, **kwargs): # real signature unknown
        """ Return repr(self). """
        pass

    buffer = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    closed = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    encoding = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    errors = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    name = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    newlines = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    _CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    _finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
View Code
三人行,必有我师
原文地址:https://www.cnblogs.com/lwp-king666/p/8395211.html