python成长之路第三篇(1)_初识函数

时间:2022-09-14 10:05:05

目录:

函数

  1. 为什么要使用函数
  2. 什么是函数
  3. 函数的返回值
  4. 文档化函数
  5. 函数传参数

文件操作(二)

1、文件操作的步骤

2、文件的内置方法

函数:

一、为什么要使用函数

在日常写代码中,我们会发现有很多代码是重复利用的,这样会使我们的代码变得异常臃肿,比如说:

我们要写一个验证码的功能

例子:

比如说我们要进行一些操作,而这些操作需要填写验证码

验证码代码

 import random
number_check = ''
for i in range(0,6):
number_curr = random.randrange(0,5)
if number_curr != i:
number_temp = chr(random.randint(97,122))
else:
number_temp = random.randint(0,9)
number_check += str(number_temp)
先不用管这段代码什么意思,后续会提到

验证码实现代码

例子代码:
 验证码代码
 功能1
 验证码代码
 功能2
 验证码代码
 功能3
这段文字呢就表示没写一个功能,加入这个功能需要验证码,就需要在这个功能上加判断这样大大增加了代码量
所以呢就产生了函数

二、什么是函数

函数准确的来说就是实现某个功能的代码的集合

那么我们接着上面的例子来写把验证码模块变成一个函数

 import random

 def code():#其实这家伙是个伪函数,因为没有返回值

    number_check = ''
for i in range(0,6):
number_curr = random.randrange(0,5)
if number_curr != i:
number_temp = chr(random.randint(97,122))
else:
number_temp = random.randint(0,9)
number_check += str(number_temp)

验证码函数

那么我们功能来去调用函数的时候只需要这样
  import random
  code():
  功能1
  code():
  功能2
  code():
  功能3
代码如下:
 import random
def code():
number_check = ''
for i in range(0,6):
number_curr = random.randrange(0,5)
if number_curr != i:
number_temp = chr(random.randint(97,122))
else:
number_temp = random.randint(0,9)
number_check += str(number_temp)
print(number_check)
code()

随机验证码

#这样我们每次运行就能看到一个随机的字符,那么我们怎么拿到这个随机的字符呢

三、函数的返回值(return)

上一小节我们学习了怎么来创建一个函数和怎么调用一个函数那么我们来看看怎么拿到函数的返回值

接着我们上面的例子:

 import random#别忘了我!
def code():
number_check = ''#设置一个空变量
for i in range(0,6): #循环0到6也就是6次
number_curr = random.randrange(0,5)#生成一个随机数
if number_curr != i: #判断当前循环次数与随机生成的数是否一样
number_temp = chr(random.randint(97,122))#如果不一样则生成随机数97-122并转化成字母
else:#否则
number_temp = random.randint(0,9)#生成0到9的任意数字
number_check += str(number_temp)#最后添加到变量中
return number_check#原来加个这货就好了啊
#那么如何调用和取到返回值呢 a_code = code()
print(a_code)

返回值函数

 

四、文档化函数

什么叫做文档化函数,其实就是丫的注释!,只不过这货写在了函数里面在def关键字下面0.0,他的目的呢只是为了更好的注释这个函数的功能

def code():
'This is a function of generated random authentication code'
pass
pass

五、函数传参数

有的小伙伴思考来思考去发现我没办法往里面传入参数啊,这怎么可以那么下面我们就讲解传参

函数分为三种:

  • 普通参数
  • 默认参数
  • 动态参数

1、普通参数

啥是普通参数,就是很普通的意思哈哈我们来看看普通参数

还是以生成随机数为例:假如我们想自己规定这个随机验证码的长度

 import random
def code(frequency):
frequency = int(frequency)
number_check = ''
for i in range(0,frequency):
number_curr = random.randrange(0,frequency)
if number_curr != i:
number_temp = chr(random.randint(97,122))
else:
number_temp = random.randint(0,9)
number_check += str(number_temp)
return number_check
in_frequency = input("请输入次数长度:")
a_code = code(in_frequency)
print(a_code)

随机数传参

!!!发生了什么,原来def code(frequency)多了个参数下图详解,frequency在这里有个别名叫做形参(形式参数),而in_frequency叫做实参(实际参数),形式参数的值由实际参数提供
python成长之路第三篇(1)_初识函数2、默认参数

如果说我们想给frequency来个默认值怎么办?def code(frequency = 3):其实就是加个等于号就好了这样在调用的时候就不需要加上实参了a_code = code()

3、动态参数一

问题来了,普通参数只能传一个值那么我想传多个值就需要写多个普通参数,就想这样def code(frequency,frequency1,frequency2):那么有没有进化的方法呢?其实我们可以这样:def code(*frequency):例子:

 def code(*frequency):
print(frequency)
in_frequency = [1,2,3,"dsa"]
code(in_frequency)
([1, 2, 3, 'dsa'],)
或者这么调用
code(1,2,3,"dsa")

动态参数一

这样我们就可以传入多个参数了,注意的是传入的值之后会变成一个元组,元组是不可修改的哦。
改动态参数的方法
咳咳事情不是绝对的其实这个参数还是可以修改的不过我们就要用些小技巧,借助列表喽,原理就是改不了元组我改列表就是了
def code(*frequency):
frequency[0][0] = int(frequency[0][0])+1
print(frequency)
a = [10]
code(a)
([11],)

4、动态参数二

某某小伙伴说那么那个字典能不能传进去。啪啪啪,答案是可以:例子:

def code(**frequency):
     print(frequency)

code(times=10)
{'times': 10}
最后我们来总结一下,一个基本的函数有一下几个特点:
  • def:表示函数的关键字
  • 函数名:表示函数的名称,并根据函数名调用函数
  • 函数体:这里也就是指得逻辑运算和注释
  • 参数:为函数传入数据
  • 返回值:经过函数执行完毕给调用者返回的结果

文件操作(二):

一.文件操作的步骤

在成长之路第一篇的第五章曾将讲过了文件的一些操作,在这里呢我们既然了解到了函数那我们就一起来深入的看看文件操作

首先来整理一下文件操作的几个步骤

1、打开文件

2、操作文件

3、关闭文件

打开文件

对于打开文件来说python有两种方式:open()和file()本质上前者会调用后者,所以推荐用open,其次如果打开的文件要做跨平台操作的话我们就要使用二进制的方法来去打开,为什么呢?因为在windows和linux上的换行符不一样,在使用二进制来去操作文件python默认的机制会把在linux打开windows的文件会把windows下的换行符\r\n转换成\n,同样windows打开linux的文件也是如此,如果非要用文本模式去读的话我们可以使用“U”来把换行符整理成\n

打开文件的模式有

  • r,只读模式(默认)。
  • w,只写模式。【不可读;不存在则创建;存在则删除内容;】
  • a,追加模式。【可读;   不存在则创建;存在则只追加内容;】

"+" 表示可以同时读写某个文件

  • r+,可读写文件。【可读;可写;可追加】
  • w+,写读
  • a+,同a

"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)

  • rU
  • r+U

"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)

  • rb
  • wb
  • ab

有人总好忘记关闭文件释放资源,为了方便在python2.5中增加了with语句(2.5中需要导入如下模块才能使用'from_future_import with_statement'),并且在python2.7后with支持同时打开多个文件进行处理,并且不用再写讨厌的关闭文件语句了

with:

with open('l1') as A1, open('l2') as A2:

   pass

这样我们就可以操作A1就是操作l1文件,操作A2就是操作l2文件

文件操作源码:

 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
0 (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

python成长之路第三篇(1)_初识函数的更多相关文章

  1. python成长之路第三篇(3)_内置函数及生成器迭代器

    打个广告欢迎加入linux,python资源分享群群号:478616847 目录: 1.lambda表达式 2.map内置函数 3.filter内置函数 4.reduce内置函数 5.yield生成器 ...

  2. python成长之路第三篇(2)_正则表达式

    打个广告欢迎加入linux,python资源分享群群号:478616847 目录: 1.什么是正则表达式,python中得正则简介 2.re模块的内容 3.小练习 一.什么是正则表达式(re) 正则表 ...

  3. python成长之路第三篇(4)_作用域,递归,模块,内置模块(os,ConfigParser,hashlib),with文件操作

    打个广告欢迎加入linux,python资源分享群群号:478616847 目录: 1.作用域 2.递归 3.模块介绍 4.内置模块-OS 5.内置模块-ConfigParser 6.内置模块-has ...

  4. (转)Python成长之路【第九篇】:Python基础之面向对象

    一.三大编程范式 正本清源一:有人说,函数式编程就是用函数编程-->错误1 编程范式即编程的方法论,标识一种编程风格 大家学习了基本的Python语法后,大家就可以写Python代码了,然后每个 ...

  5. python成长之路【第九篇】:网络编程

    一.套接字 1.1.套接字套接字最初是为同一主机上的应用程序所创建,使得主机上运行的一个程序(又名一个进程)与另一个运行的程序进行通信.这就是所谓的进程间通信(Inter Process Commun ...

  6. python成长之路【第二篇】:列表和元组

    1.数据结构数据结构是通过某种方式(例如对元素进行编号)组织在一起的数据元素的集合,这些数据元素可以是数字或者字符,甚至可以是其他数据结构.在Python中,最基本的数据结构是序列(sequence) ...

  7. python成长之路【第一篇】:python简介和入门

    一.Python简介 Python(英语发音:/ˈpaɪθən/), 是一种面向对象.解释型计算机程序设计语言. 二.安装python windows: 1.下载安装包 https://www.pyt ...

  8. python成长之路——第三天

    一.collections系列: collections其实是python的标准库,也就是python的一个内置模块,因此使用之前导入一下collections模块即可,collections在pyt ...

  9. 我的Python成长之路---第三天---Python基础(12)---2016年1月16日(雾霾)

    四.函数 日常生活中,要完成一件复杂的功能,我们总是习惯把“大功能”分解为多个“小功能”以实现.在编程的世界里,“功能”可称呼为“函数”,因此“函数”其实就是一段实现了某种功能的代码,并且可以供其它代 ...

随机推荐

  1. ps命令

    Linux中的ps命令是Process Status的缩写.ps命令用来列出系统中当前运行的那些进程.ps命令列出的是当前那些进程的快照,就是执行ps命令的那个时刻的那些进程,如果想要动态的显示进程信 ...

  2. winform程序重启

    winform程序重启的方法: private void ReStart() { string processName = System.Diagnostics.Process.GetCurrentP ...

  3. Spring Web Flow 简介

    Spring Web Flow 简介 博客分类: 转载 SSH 最近在TSS上看到了一片介绍Spring Web Flow的文章,顺便就翻译了下来,SWF的正式版估计要到6月份才能看到了,目前的例子都 ...

  4. [GDKOI2016]小学生数学题

    记 $F(n)=\sum\limits_{i=1}^{n}i^{-1}$ $G(n)=\sum\limits_{i=1,i\neq jp}^{n}i^{-1}$ 我们要算$F(n)\%p^k$ 那么 ...

  5. HDU 1180 诡异的楼梯(BFS)

    诡异的楼梯 Time Limit:1000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u Submit Status ...

  6. 13张动图助你彻底看懂马尔科夫链、PCA和条件概率!

    13张动图助你彻底看懂马尔科夫链.PCA和条件概率! https://mp.weixin.qq.com/s/ll2EX_Vyl6HA4qX07NyJbA [ 导读 ] 马尔科夫链.主成分分析以及条件概 ...

  7. Leetcode-645 Set Mismatch

    The set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of ...

  8. Nginx 对上游使用SSL链接

    L96 双向认证SSL指令示列 对下游使用证书指令 Syntax: ssl_certificate file; Default: — Context: http, server Syntax: ssl ...

  9. 【LeetCode】矩阵操作

    1. 矩阵旋转 将 n × n 矩阵顺时针旋转 90°. 我的思路是 “ 从外到内一层一层旋转 ”. 一个 n × n 矩阵有 (n + 1) / 2 层,每层有 4 部分,将这 4 部分旋转. 顺时 ...

  10. 创建模式--原型模式(JAVA)

    原型模式: 原型模式主要针对模型对象类型的克隆,对已有构造好的对象进行复制获取一个新的对象实例.比如我们在获取一个对象并成功赋值后,要传递给多个处理类去处理. 打个比方:吃面是个处理类,面是个模型对象 ...