首页 > 技术文章 > Day03——Python函数

rangle 2018-01-24 17:41 原文

函数定义和使用

1、语法

def 函数名(参数):
       
    ...
    函数体
    ...
    返回值

函数的定义主要有如下要点:

  def:表示函数的关键字
  函数名:函数的名称,日后根据函数名调用函数
  函数体:函数中进行一系列的逻辑计算,如:发送邮件、计算出 [11,22,38,888,2]中的最大数等...
  参数:为函数体提供数据
  返回值:当函数执行完毕后,可以给调用者返回数据。

2、返回值

函数执行后,将执行结果返回,示例如下:

#!/usr/bin/env python
# -*- UTF-8 -*-
# Author:Rangle

def test():

    """    
    test codes ...
    """
    if 1 == 1:
        return True
    else:
        return False

status=test()

print(status)

3、参数

python函数的参数分为普通参数、默认参数、动态参数

(1)普通参数

#!/usr/bin/env python
# -*- UTF-8 -*-
# Author:Rangle

def fname(name):

    print('My name is :%s'%name)

fname('Lucy')

(2)默认参数

#!/usr/bin/env python
# -*- UTF-8 -*-
# Author:Rangle

def 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:Rangle

def 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:Rangle

def 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.
        """
        pass

2.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)  # default

3.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)格式输出

 

格式符号如下:
%s    字符串 (采用str()的显示)
%r    字符串 (采用repr()的显示)
%c    单个字符
%b    二进制整数
%d    十进制整数
%i    十进制整数
%o    八进制整数
%x    十六进制整数
%e    指数 (基底写为e)
%E    指数 (基底写为E)
%f    浮点数
%F    浮点数,与上相同
%g    指数(e)或浮点数 (根据显示长度)
%G    指数(E)或浮点数 (根据显示长度)
%%    字符"%"

主要说明:
%s:格式化初始字符串
%d:格式化输出整数数字
%f:格式化输出浮点数,其中可以通过%.nf保留n位小数,n位实际数字。例如保留两位小数%.2f
%8d:指定输出数字占用8个字符位置,其中输出数字居右排列
%-8d:指定输出数字占用8个字符位置,其中输出数字居左排列
%08d:指定占位符号用0表示

format(0.0015,'.2e'):科学计数法表示1.50e-03即1.50*10^-3

 

5、练习题

(1)、简述普通参数、指定参数、默认参数、动态参数的区别

(2)、写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数

(3)、写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5。

(4)、写函数,检查用户传入的对象(字符串、列表、元组)的每一个元素是否含有空内容。

(5)、写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。

(6)、写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者。

(7)、写函数,检查传入字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
1
2
3
    
dic = {"k1": "v1v1", "k2": [11,22,33,44]}
 
PS:字典中的value只能是字符串或列表

(8)、写函数,利用递归获取斐波那契数列中的第 10 个数,并将该值返回给调用者。

 

推荐阅读