Day03——Python函數,day03python

來源:互聯網
上載者:User

Day03——Python函數,day03python

函數定義和使用

1、文法

def 函數名(參數):           ...    函數體    ...    傳回值

函數的定義主要有如下要點:

  def:表示函數的關鍵字
  函數名:函數的名稱,日後根據函數名調用函數
  函數體:函數中進行一系列的邏輯計算,如:發送郵件、計算出 [11,22,38,888,2]中的最大數等...
  參數:為函數體提供資料
  傳回值:當函數執行完畢後,可以給調用者返回資料。

2、傳回值

函數執行後,將執行結果返回,樣本如下:

#!/usr/bin/env python# -*- UTF-8 -*-# Author:Rangledef test():    """        test codes ...    """    if 1 == 1:        return True    else:        return Falsestatus=test()print(status)

3、參數

python函數的參數分為普通參數、預設參數、動態參數

(1)普通參數

#!/usr/bin/env python# -*- UTF-8 -*-# Author:Rangledef fname(name):    print('My name is :%s'%name)fname('Lucy')

(2)預設參數

#!/usr/bin/env python# -*- UTF-8 -*-# Author:Rangledef fname(name,age=18):    print('My name is :%s and i\'am %s years old'%(name,age))fname('Lucy')

(3)動態參數

 ##接收動態參數,其中動態參數為字串、數字、列表格式,輸出格式為元組

#!/usr/bin/env python# -*- UTF-8 -*-# Author:Rangledef func(*args):    print (args)# 執行方式一func(11,33,4,4454,5)# 執行方式二li = [11,2,2,3,3,4,54]func(*li)

##接收動態參數,其中參數為字典形式,輸出格式為字典

#!/usr/bin/env python# -*- UTF-8 -*-# Author:Rangledef func(**kwargs):    print (kwargs)# 執行方式一func(name='lucy',age=18)# 執行方式二li = {'name':'lucy', 'age':18, 'gender':'male'}func(**li)

##接收動態參數,組合形式

def func(*args, **kwargs):    print args    print kwargs

4、內建函數

官網連結:https://docs.python.org/3/library/functions.html#next

(1)open()函數

用於檔案處理,步驟一般為:開啟檔案——>操作檔案——>關閉檔案

文法如下:

檔案控制代碼 = open('檔案路徑', '模式')

開啟檔案的模式有:

  • r ,唯讀模式【預設】
  • w,唯寫模式【不可讀;不存在則建立;存在則清空內容;】
  • x, 唯寫模式【不可讀;不存在則建立,存在則報錯】
  • a, 追加模式【可讀;   不存在則建立;存在則只追加內容;】

"+" 表示可以同時讀寫某個檔案

  • r+, 讀寫【可讀,可寫】
  • w+,寫讀【可讀,可寫】
  • x+ ,寫讀【可讀,可寫】
  • a+, 寫讀【可讀,可寫】

 "b"表示以位元組的方式操作

  • rb  或 r+b
  • wb 或 w+b
  • xb 或 w+b
  • ab 或 a+b

 註:以b方式開啟時,讀取到的內容是位元組類型,寫入時也需要提供位元組類型

 

class file(object)    def close(self): # real signature unknown; restored from __doc__        關閉檔案        """        close() -> None or (perhaps) an integer.  Close the file.                 Sets data attribute .closed to True.  A closed file cannot be used for        further I/O operations.  close() may be called more than once without        error.  Some kinds of file objects (for example, opened by popen())        may return an exit status upon closing.        """     def fileno(self): # real signature unknown; restored from __doc__        檔案描述符           """        fileno() -> integer "file descriptor".                 This is needed for lower-level file interfaces, such os.read().        """        return 0         def flush(self): # real signature unknown; restored from __doc__        重新整理檔案內部緩衝區        """ flush() -> None.  Flush the internal I/O buffer. """        pass      def isatty(self): # real signature unknown; restored from __doc__        判斷檔案是否是同意tty裝置        """ isatty() -> true or false.  True if the file is connected to a tty device. """        return False      def next(self): # real signature unknown; restored from __doc__        擷取下一行資料,不存在,則報錯        """ x.next() -> the next value, or raise StopIteration """        pass     def read(self, size=None): # real signature unknown; restored from __doc__        讀取指定位元組資料        """        read([size]) -> read at most size bytes, returned as a string.                 If the size argument is negative or omitted, read until EOF is reached.        Notice that when in non-blocking mode, less data than what was requested        may be returned, even if no size parameter was given.        """        pass     def readinto(self): # real signature unknown; restored from __doc__        讀取到緩衝區,不要用,將被遺棄        """ readinto() -> Undocumented.  Don't use this; it may go away. """        pass     def readline(self, size=None): # real signature unknown; restored from __doc__        僅讀取一行資料        """        readline([size]) -> next line from the file, as a string.                 Retain newline.  A non-negative size argument limits the maximum        number of bytes to return (an incomplete line may be returned then).        Return an empty string at EOF.        """        pass     def readlines(self, size=None): # real signature unknown; restored from __doc__        讀取所有資料,並根據換行儲存值列表        """        readlines([size]) -> list of strings, each a line from the file.                 Call readline() repeatedly and return a list of the lines so read.        The optional size argument, if given, is an approximate bound on the        total number of bytes in the lines returned.        """        return []     def seek(self, offset, whence=None): # real signature unknown; restored from __doc__        指定檔案中指標位置        """        seek(offset[, whence]) -> None.  Move to new file position.                 Argument offset is a byte count.  Optional argument whence defaults to(offset from start of file, offset should be >= 0); other values are 1        (move relative to current position, positive or negative), and 2 (move        relative to end of file, usually negative, although many platforms allow        seeking beyond the end of a file).  If the file is opened in text mode,        only offsets returned by tell() are legal.  Use of other offsets causes        undefined behavior.        Note that not all file objects are seekable.        """        pass     def tell(self): # real signature unknown; restored from __doc__        擷取當前指標位置        """ tell() -> current file position, an integer (may be a long integer). """        pass     def truncate(self, size=None): # real signature unknown; restored from __doc__        截斷資料,僅保留指定之前資料        """        truncate([size]) -> None.  Truncate the file to at most size bytes.                 Size defaults to the current file position, as returned by tell().        """        pass     def write(self, p_str): # real signature unknown; restored from __doc__        寫內容        """        write(str) -> None.  Write string str to file.                 Note that due to buffering, flush() or close() may be needed before        the file on disk reflects the data written.        """        pass     def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__        將一個字串列表寫入檔案        """        writelines(sequence_of_strings) -> None.  Write the strings to the file.                 Note that newlines are not added.  The sequence can be any iterable object        producing strings. This is equivalent to calling write() for each string.        """        pass     def xreadlines(self): # real signature unknown; restored from __doc__        可用於逐行讀取檔案,非全部        """        xreadlines() -> returns self.                 For backward compatibility. File objects now include the performance        optimizations previously implemented in the xreadlines module.        """        pass2.x
2.x內建函數

 

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 fileno(self, *args, **kwargs): # real signature unknown        檔案描述符          pass    def flush(self, *args, **kwargs): # real signature unknown        重新整理檔案內部緩衝區        pass    def isatty(self, *args, **kwargs): # real signature unknown        判斷檔案是否是同意tty裝置        pass    def read(self, *args, **kwargs): # real signature unknown        讀取指定位元組資料        pass    def readable(self, *args, **kwargs): # real signature unknown        是否可讀        pass    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    def truncate(self, *args, **kwargs): # real signature unknown        截斷資料,僅保留指定之前資料        pass    def writable(self, *args, **kwargs): # real signature unknown        是否可寫        pass    def write(self, *args, **kwargs): # real signature unknown        寫內容        pass    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)  # default3.x
3.x內建函數

(2)檔案操作之管理上下文

通過Open()函數,需要顯示關閉,這種可能容易導致忽略關閉檔案。通過with open() as f 管理上下文可以自動關閉檔案,具體文法如下:

with open('log','r') as f:            ...

其中2.7以後支援開啟多個檔案 

with open('log1') as obj1, open('log2') as obj2:    pass

(3)三元運算

如果1==1為true則返回name='Lucy',否則則返回name='Tom'

name = 'Lucy' if 1 == 1 else 'Tom'

(4)判斷函數

s='abc'

 

s.isalnum() 所有字元都是數字或者字母,為真返回 Ture,否則返回 False。s.isalpha() 所有字元都是字母,為真返回 Ture,否則返回 False。s.isdigit() 所有字元都是數字,為真返回 Ture,否則返回 False。s.islower() 所有字元都是小寫,為真返回 Ture,否則返回 False。s.isupper() 所有字元都是大寫,為真返回 Ture,否則返回 False。s.istitle() 所有單詞都是首字母大寫,為真返回 Ture,否則返回 False。s.isspace() 所有字元都是空白字元,為真返回 Ture,否則返回 False。

5、練習題

(1)、簡述普通參數、指定參數、預設參數、動態參數的區別(2)、寫函數,計算傳入字串中【數字】、【字母】、【空格] 以及 【其他】的個數(3)、寫函數,判斷使用者傳入的對象(字串、列表、元組)長度是否大於5。(4)、寫函數,檢查使用者傳入的對象(字串、列表、元組)的每一個元素是否含有空內容。(5)、寫函數,檢查傳入列表的長度,如果大於2,那麼僅保留前兩個長度的內容,並將新內容返回給調用者。(6)、寫函數,檢查擷取傳入列表或元組對象的所有奇數位索引對應的元素,並將其作為新列表返回給調用者。(7)、寫函數,檢查傳入字典的每一個value的長度,如果大於2,那麼僅保留前兩個長度的內容,並將新內容返回給調用者。123    dic = {"k1": "v1v1", "k2": [11,22,33,44]} PS:字典中的value只能是字串或列表(8)、寫函數,利用遞迴擷取斐波那契數列中的第 10 個數,並將該值返回給調用者。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.