函数定义和使用

1、语法

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

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

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

2、返回值

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

#!/usr/bin/env python
# -*- UTF-8 -*-
# Author:Rangledef test():"""    test codes ..."""if 1 == 1:return Trueelse: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 argsprint 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 forfurther I/O operations.  close() may be called more than once withouterror.  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. """passdef isatty(self): # real signature unknown; restored from __doc__
        判断文件是否是同意tty设备""" isatty() -> true or false.  True if the file is connected to a tty device. """return Falsedef next(self): # real signature unknown; restored from __doc__
        获取下一行数据,不存在,则报错""" x.next() -> the next value, or raise StopIteration """passdef 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 requestedmay be returned, even if no size parameter was given."""passdef readinto(self): # real signature unknown; restored from __doc__
        读取到缓冲区,不要用,将被遗弃""" readinto() -> Undocumented.  Don't use this; it may go away. """passdef 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 maximumnumber of bytes to return (an incomplete line may be returned then).Return an empty string at EOF."""passdef 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 thetotal 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 (moverelative to end of file, usually negative, although many platforms allowseeking 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 causesundefined behavior.Note that not all file objects are seekable."""passdef tell(self): # real signature unknown; restored from __doc__
        获取当前指针位置""" tell() -> current file position, an integer (may be a long integer). """passdef 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()."""passdef 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 beforethe file on disk reflects the data written."""passdef 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 objectproducing strings. This is equivalent to calling write() for each string."""passdef xreadlines(self): # real signature unknown; restored from __doc__
        可用于逐行读取文件,非全部"""xreadlines() -> returns self.For backward compatibility. File objects now include the performanceoptimizations 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 bedecoded or encoded with. It defaults to locale.getpreferredencoding(False).errors determines the strictness of encoding and decoding (seehelp(codecs.Codec) or the documentation for codecs.register) anddefaults 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 isenabled. Lines in the input can end in '\n', '\r', or '\r\n', andthese are translated into '\n' before being returned to thecaller. If it is '', universal newline mode is enabled, but lineendings are returned to the caller untranslated. If it has any ofthe other legal values, input lines are only terminated by the givenstring, and the line ending is returned to the caller untranslated.* On output, if newline is None, any '\n' characters written aretranslated to the system default line separator, os.linesep. Ifnewline is '' or '\n', no translation takes place. If newline is anyof the other legal values, any '\n' characters written are translatedto the given string.If line_buffering is True, a call to flush is implied when a call towrite contains a newline character."""def close(self, *args, **kwargs): # real signature unknown
        关闭文件passdef fileno(self, *args, **kwargs): # real signature unknown
        文件描述符  passdef flush(self, *args, **kwargs): # real signature unknown
        刷新文件内部缓冲区passdef isatty(self, *args, **kwargs): # real signature unknown
        判断文件是否是同意tty设备passdef read(self, *args, **kwargs): # real signature unknown
        读取指定字节数据passdef readable(self, *args, **kwargs): # real signature unknown
        是否可读passdef readline(self, *args, **kwargs): # real signature unknown
        仅读取一行数据passdef seek(self, *args, **kwargs): # real signature unknown
        指定文件中指针位置passdef seekable(self, *args, **kwargs): # real signature unknown
        指针是否可操作passdef tell(self, *args, **kwargs): # real signature unknown
        获取指针位置passdef truncate(self, *args, **kwargs): # real signature unknown
        截断数据,仅保留指定之前数据passdef writable(self, *args, **kwargs): # real signature unknown
        是否可写passdef write(self, *args, **kwargs): # real signature unknown
        写内容passdef __getstate__(self, *args, **kwargs): # real signature unknownpassdef __init__(self, *args, **kwargs): # real signature unknownpass@staticmethod # known case of __new__def __new__(*args, **kwargs): # real signature unknown""" Create and return a new object.  See help(type) for accurate signature. """passdef __next__(self, *args, **kwargs): # real signature unknown""" Implement next(self). """passdef __repr__(self, *args, **kwargs): # real signature unknown""" Return repr(self). """passbuffer = 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)格式输出

格式符号如下:
%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
3dic = {"k1": "v1v1", "k2": [11,22,33,44]}PS:字典中的value只能是字符串或列表(8)、写函数,利用递归获取斐波那契数列中的第 10 个数,并将该值返回给调用者。

转载于:https://www.cnblogs.com/rangle/p/8342327.html

Day03——Python函数相关推荐

  1. 【Python百日基础系列】Day03 - Python 数据类型

    文章目录 一.Python中的数据类型 1.1 数据类型系统是编程语言的核心 1.2 Python中的数据类型种类 1.3 数据类型的可变性 1.4 数据类型查看函数 - type() 二.Numbe ...

  2. Pass算子python 函数

    Pass算子python 函数 函数 • 函数是代码的一种组织形式 • 函数应该能完成一项特定的工作,而且一般一个函数只完成一项工作 • 有些语言,分函数和过程两个概念,通俗解释是,有返回结果的是函数 ...

  3. Python 函数的可变参数(*paramter与**paramter)的使用

    Python 函数的可变参数主要有 *paramter与**paramter 可变参数主要有 *paramter的作用 接受任意多个实际参数并放到一个元组中 def people(*people):f ...

  4. 【python教程入门学习】Python函数定义及传参方式详解(4种)

    这篇文章主要介绍了Python函数定义及传参方式详解(4种),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧 一.函数初识 1.定 ...

  5. python系统提供构造函数传入参数_[ Python入门教程 ] Python函数定义和使用

    函数是一段可以重复多次调用的代码,通过输入的参数值,返回需要的结果.通过使用函数,可以提高代码的重复利用率.本文主要介绍Python函数的定义.调用和函数参数设置方法. 函数的定义 Python函数定 ...

  6. python函数第二次运行报错_Python学习笔记2-函数、高级特性

    函数 调用函数 要调用一个函数,需要知道函数的名称和参数,比如求绝对值的函数abs,只有一个参数 >>> abs(100) 100 >>> abs(-20) 20 ...

  7. [教程]Python函数的参数

    Python函数的参数 位置参数.默认值参数.可变参数.关键字参数和命名关键字参数 1 函数结构 def 函数名(参数):函数体返回值 2 位置参数 略 3 默认值参数 略 4 可变参数 # 可变长度 ...

  8. python函数+定义+调用+多返回值+匿名函数+lambda+高级函数(reduce、map、filter)

    python函数+定义+调用+多返回值+匿名函数+lambda+高级函数(reduce.map.filter) Python 中函数的应用非常广泛,比如 input() .print().range( ...

  9. python函数参数*arg和**kwargs分别代表什么?

    python函数参数*arg和**kwargs分别代表什么? 注意: 注意:参数arg.*args.**kwargs三个参数的位置必须是一定的.必须是(arg,*args,**kwargs)这个顺序, ...

最新文章

  1. 如何为Pyramid添加Middleware
  2. ebs oracle pl sql开发_PL/SQL设置
  3. .NET网站国际化策略
  4. 【图论】【斜率优化】前往大都会(loj 2769)
  5. CentOS 7 防火墙命令
  6. python 字典性质描述_卧槽!Python还有这些特性(2):奇怪的字典
  7. 技术大会值得参加吗?
  8. Sketch54 for mac汉化破解版
  9. Java是什么?Java能干什么工作?
  10. mysql评论回复表设计_数据库设计——评论回复功能
  11. vuepress+github+versel部署免费个人博客
  12. 女生学计算机专业用考研吗,计算机专业女生考研,该选什么方向比较好?谢谢!...
  13. Kaldi WFST HCLG.fst 构图 学习
  14. 最全Android 11新特性概览
  15. iOS音效和音乐播放
  16. [渝粤教育] 深圳信息职业技术学院 《新理念英语》English For You 参考 资料
  17. 做开发遇到35岁瓶颈被裁员,体验了一把“自由职业”,最后入行了软件测试...
  18. linux添加临时环境变量,关于linux:设置临时环境($ PATH)
  19. PHP中的面向对象思想
  20. Linux——shell练习题01

热门文章

  1. 机器学习,满足人类情感:如何帮助电脑监控你的精神状态
  2. Linux启动加载过程解析
  3. “口罩厂”霍尼韦尔搞出的量子计算机,刚刚获得了Nature认可
  4. GTA 5祖传「屎山」代码终于修复!R星认可黑客方案,还给他发了1万美元奖金
  5. 苹果正和激光雷达供应商谈判,自动驾驶硬件一把手:辞职,去看星辰大海
  6. 李飞飞团队从动物身上get AI新思路,提出RL计算框架,让机器在复杂环境学习和进化...
  7. 能跑TensorFlow,能唱KTV,这是国产车吉利的智能系统和背后的芯片
  8. JSP标签:jsp内置标签、jstl标签、自定义标签
  9. Squid配置二级代理(父代理)
  10. 解读Windows更新下载器文件列表(推荐)