Day03——Python函数
函数定义和使用
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函数的更多相关文章
- Day03 - Python 函数
1. 函数简介 函数是组织好的,可重复使用的,用来实现单一或相关联功能的代码段. 函数能提高应用的模块性,和代码的重复利用率.Python提供了许多内建函数,比如print():也可以自己创建函数,这 ...
- python 函数之day3
一 函数的语法及特性 什么是函数? 定义:函数是一个功能通过一组语句的集合,由名字(函数名)将其封装起来的代码块,要想执行这个函数,只要调用其函数名即可. 特性: 减少重复代码 使程序变的可扩展 使程 ...
- Python函数作用域的查找顺序
函数作用域的LEGB顺序 1.什么是LEGB? L:local 函数内部作用域 E:enclosing 函数内部与内嵌函数之间 G:global 全局作用域 B:build-in 内置作用域 2.它们 ...
- Python函数讲解
Python函数
- Python函数信息
Python函数func的信息可以通过func.func_*和func.func_code来获取 一.先看看它们的应用吧: 1.获取原函数名称: 1 >>> def yes():pa ...
- Python函数参数默认值的陷阱和原理深究"
本文将介绍使用mutable对象作为Python函数参数默认值潜在的危害,以及其实现原理和设计目的 本博客已经迁移至: http://cenalulu.github.io/ 本篇博文已经迁移,阅读全文 ...
- Python开发【第四章】:Python函数剖析
一.Python函数剖析 1.函数的调用顺序 #!/usr/bin/env python # -*- coding:utf-8 -*- #-Author-Lian #函数错误的调用方式 def fun ...
- Python函数解析
对于Python的函数,我们需要记住的是: 1. 函数的默认返回值是None. 2. python是一个自上而下逐行解释并执行的语言.因此,函数的定义必须在函数被调用之前.同名的函数,后定义的会覆盖前 ...
- Python入门笔记(18):Python函数(1):基础部分
一.什么是函数.方法.过程 推荐阅读:http://www.cnblogs.com/snandy/archive/2011/08/29/2153871.html 一般程序设计语言包含两种基本的抽象:过 ...
随机推荐
- Java使用占位符拼接字符串-String.format()的使用
String domain = "www.ykmaiz.com"; int iVisit = 0; String info = String.format("该域名%s被 ...
- google +ubuntu16.04
1.在终端中输入以下命令 sudo wget https://repo.fdzh.org/chrome/google-chrome.list -P /etc/apt/sources.list.d/ 2 ...
- 九度oj 1031 xxx定律 2009年浙江大学计算机及软件工程研究生机试真题
题目1031:xxx定律 时间限制:1 秒 内存限制:32 兆 特殊判题:否 提交:5153 解决:3298 题目描述: 对于一个数n,如果是偶数,就把n砍掉一半:如果是奇数,把n变成 3*n ...
- 日调度万亿次,微服务框架TSF大规模应用——云+未来峰会开发者专场回顾
欢迎大家前往腾讯云+社区,获取更多腾讯海量技术实践干货哦~ 演讲者:张浩 腾讯云中间件产品负责人 背景:众多开发者中,一定经历类似的甜蜜烦恼,就是当线上业务规模越来越大,系统分支发展越来越多的时候,初 ...
- SVN命令行怎么用?--转百度知道
http://zhidao.baidu.com/link?url=uPWXURahp5KzdXbgrGTb9-r-abGaNC-J7dkhFkMhf062OJ1jeCM5wpBCgDR7bDg8uFr ...
- 问题集录06--SpringBoot创建Maven项目
1. 如下图,打开idea之后,file -> new -> project2. 如下图,在弹出的new project 页面,选择maven -> 勾选Create from ar ...
- Java并发编程之volatile关键字解析
一内存模型的相关概念 二并发编程中的三个概念 三Java内存模型 四深入剖析volatile关键字 五使用volatile关键字的场景 volatile这个关键字可能很多朋友都听说过,或许也都用过.在 ...
- .NET MVC Scripts.Render 上下文不存在问题解决方法
要想使用 @Scripts.Render(),就要用到 BundleConfig.cs 这个类,在App_Start目录下新建一下这个类, 类的内容如下: 使用这个类需要引入 using System ...
- Cheatsheet: 2017 02.01 ~ 02.28
Web Debouncing and Throttling Explained Through Examples What is TypeScript? An Absolute Beginner's ...
- Editplus编辑器在php文件中变色显示设置
咋editplus中我们编辑时有时会遇到不变色的问题,那么怎么设置呢,从语法配置就好,如下: