函数定义和使用

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 个数,并将该值返回给调用者。

Day03——Python函数的更多相关文章

  1. Day03 - Python 函数

    1. 函数简介 函数是组织好的,可重复使用的,用来实现单一或相关联功能的代码段. 函数能提高应用的模块性,和代码的重复利用率.Python提供了许多内建函数,比如print():也可以自己创建函数,这 ...

  2. python 函数之day3

    一 函数的语法及特性 什么是函数? 定义:函数是一个功能通过一组语句的集合,由名字(函数名)将其封装起来的代码块,要想执行这个函数,只要调用其函数名即可. 特性: 减少重复代码 使程序变的可扩展 使程 ...

  3. Python函数作用域的查找顺序

    函数作用域的LEGB顺序 1.什么是LEGB? L:local 函数内部作用域 E:enclosing 函数内部与内嵌函数之间 G:global 全局作用域 B:build-in 内置作用域 2.它们 ...

  4. Python函数讲解

    Python函数

  5. Python函数信息

    Python函数func的信息可以通过func.func_*和func.func_code来获取 一.先看看它们的应用吧: 1.获取原函数名称: 1 >>> def yes():pa ...

  6. Python函数参数默认值的陷阱和原理深究"

    本文将介绍使用mutable对象作为Python函数参数默认值潜在的危害,以及其实现原理和设计目的 本博客已经迁移至: http://cenalulu.github.io/ 本篇博文已经迁移,阅读全文 ...

  7. Python开发【第四章】:Python函数剖析

    一.Python函数剖析 1.函数的调用顺序 #!/usr/bin/env python # -*- coding:utf-8 -*- #-Author-Lian #函数错误的调用方式 def fun ...

  8. Python函数解析

    对于Python的函数,我们需要记住的是: 1. 函数的默认返回值是None. 2. python是一个自上而下逐行解释并执行的语言.因此,函数的定义必须在函数被调用之前.同名的函数,后定义的会覆盖前 ...

  9. Python入门笔记(18):Python函数(1):基础部分

    一.什么是函数.方法.过程 推荐阅读:http://www.cnblogs.com/snandy/archive/2011/08/29/2153871.html 一般程序设计语言包含两种基本的抽象:过 ...

随机推荐

  1. $bzoj1016-JSOI2008$ 最小生成树计数 最小生成树 $dfs/matrix-tree$定理

    题面描述 现在给出了一个简单无向加权图.你不满足于求出这个图的最小生成树,而希望知道这个图中有多少个不同的最小生成树.(如果两颗最小生成树中至少有一条边不同,则这两个最小生成树就是不同的).由于不同的 ...

  2. decode 和 encode 区别

    字符串在Python内部的表示是unicode编码,因此,在做编码转换时,通常需要以unicode作为中间编码,即先将其他编码的字符串解码(decode)成unicode,再从unicode编码(en ...

  3. 【c++】流状态的查询和控制

    源自 c++primer 4th, 248页 代码 #include <iostream> #include <limits> #include <stdexcept&g ...

  4. 最小化安装的redhat/centos安装gnome桌面

    因系统版本和语言环境不同,安装包的名字会有所差别 安装方式可以选择直接联网安装,也可以加载dvd镜像源安装,这里针对配置redhat/centos本地dvd的yum源做个记录: 1.复制 redhat ...

  5. Java入门系列-21-多线程

    什么是线程 在操作系统中,一个应用程序的执行实例就是进程,进程有独立的内存空间和系统资源,在任务管理器中可以看到进程. 线程是CPU调度和分派的基本单位,也是进程中执行运算的最小单位,可完成一个独立的 ...

  6. 使用 Qt 获取 UDP 数据并显示成图片

    一个项目,要接收 UDP 数据包,解析并获取其中的数据,主要根据解析出来的行号和序号将数据拼接起来,然后将拼接起来的数据(最重要的数据是 R.G.B 三个通道的像素值)显示在窗口中.考虑到每秒钟要接收 ...

  7. MySQL之存储引擎(表类型)的选择

    和大部分的数据库不同,MySQL中有一个存储引擎的概念,用户可以根据数据存储的需求来选择不同的存储引擎.本次博客就来介绍一下MySQL中的存储引擎.MySQL版本 5.7.19. 概述 MySQL的存 ...

  8. webHttpBinding

    [ServiceContract] public interface IHanger { /// <summary> /// 根据请求的用户的所属的组织,决定工单发布到哪个吊挂产线 /// ...

  9. 如何高效的算出2x8的值

    原文出自:https://blog.csdn.net/seesun2012 位移算法,如何高效的算出2*8的值,为什么8<<1,4<<2,2<<3,1<< ...

  10. 深入Java关键字null

    一.null是代表不确定的对象   Java中,null是一个关键字,用来标识一个不确定的对象.因此可以将null赋给引用类型变量,但不可以将null赋给基本类型变量.   比如:int a = nu ...