函數基本操做

函數包括內置函數及自定義函數,用來實現單一或者相同功能的代碼段,有效的提升了代碼的可讀性及重讀利用率。語法以下:python

def  函數名(參數):                 
     代碼塊

定義函數規則:app

  • def關鍵字開頭 ,與函數名以空格隔開
  • ()中能夠自定義參數,參數個數能夠爲0~N個
  • ()後面必須跟冒號,代碼塊以冒號開始,且縮進
  • return表達式用來結束函數,不帶return表達式的函數返回None

1、函數返回值ide

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

s=num()                   #調用函數,並將return返回的值賦予s
print(s)                  #---->輸出 15  666

#調用函數時,執行過程當中若遇到return則會退出函數,不會再執行return表達式後的語句

 2、參數傳遞函數

Python中參數傳遞採用的是傳值和引用相結合的一種傳值方法,具體傳值方法由對象類型而定,若參數是可變對象類型(如dict、list),至關於採用了引用方式,就會修改對象的初始值;如果不可變對象類型(如int、str、tuple),至關於採用了傳值方式,就不會修改對象的初始值。ui

參數大致歸納爲:普通參數、默認參數、動態參數spa

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. 默認參數code

【示例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. 動態參數orm

【示例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

3、lambda表達式

lambda函數也稱爲匿名函數,用來表達簡單的函數,沒有具體的函數名稱,書寫只能是一行

【示例】
foo=lambda  a,b:a+b      #lambda後 冒號以前a b表示形參,形參能夠是多個,用逗號隔開;冒號後面是代碼塊,整個lambda表達式只能是一行,有return值
s=foo(10,20)
print(s)                 # 輸出30

4、內置函數

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, '',
    '\n', '\r', and '\r\n'.  It works as follows:
    
    * On input, if newline is None, universal newlines mode is
      enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
      these are translated into '\n' 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 '\n' characters written are
      translated to the system default line separator, os.linesep. If
      newline is '' or '\n', no translation takes place. If newline is any
      of the other legal values, any '\n' 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
相關文章
相關標籤/搜索