python3进阶_python自动化系列(二)--python3进阶

1、函数命名定义规范:

(1)、函数代码块以 def 关键词开头,后接函数标识符名称和圆括号 ()。

(2)、圆括号之间可以用于传入参数。

(3)、函数内容以冒号起始,并且缩进。

(4)、return [表达式] 结束函数,将返回值传给调用方。不带return相当于返回 None。

格式如下:

def 函数名(参数列表):

函数体

def sayHello():

print(“HelloWorld”)

sayHello()

2、不定长参数:

(1)、一个星(*):表示接收的参数作为元组来处理

(2)、两个星(**):表示接收的参数作为字典来处理

def add(a, *kwargs):                                                    def add(a, ** kwargs):

sum = a;                                                                      sum = a

for i in kwargs:                                                             for (i ,j) in kwargs.items():

sum = sum + i                                                               sum = sum + j

return sum                                                                   return sum

res = add(1, 2, 3, 4)                                                      res = add(a = 1, b = 2, c = 3)

print(res)                                                                       print(res)

3、类

class ClassName:

(里面写标识符或方法)

. . .

实例:

class student:

age = 0

name = “”

def get_name(self):           #self 代表这个类本身非传入参数

return self.name

def set_name(self, name):

self.name = name

4、List列表常用函数

list.append(obj)            在列表末尾添加新的对象

list.index(obj)               从列表中找出某个值第一个匹配项的索引位置

list.insert(index, obj)    将对象插入列表的索引位置

list.remove(obj)            移除列表中某个值的第一个匹配项

list.copy()                     复制列表

len(list)                     获取list里面元素个数

5、Dict字典常用函数:

dict.items()         以列表返回可遍历的(键, 值) 元组数组

dict.pop(key)      删除key 所对应的值

dict.copy()          复制列表

len(dict)         获取dict里面key个数

6、random常用函数:

random.random()                    返回随机生成的一个实数,它在[0,1)范围内

random.randint(begin,end)  返回随机生成的一个整数,它在[begin,end]范围内

random.sample(str,length)    返回随机生产的一个列表,列表长度为length

7、File读写常用函数:

open(filepath,method)     打开文件

method主要包括下面3种方式

r         以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式

w       打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。

a        打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。

file.readline()                  读取单行

file.readlines()                读取多行

file.write(str)                   写入数据

file.flush()                       刷新文件内部缓冲,直接把内部缓冲区的数据立刻写入文件, 而不是被动的等待输出缓冲区写入(配合file.write使用)

file.close()                        关闭文件

8、time模块实际主要有2种应用

(1)获取当前时间:-------在日志中常见

import time

print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

%Y 年     %m 月      %d 日     %H 时    %M 分     %S 秒

(2)获取一段程序运行的时间:

import time

start = time.time() #time.time()获取当前时间戳

time.sleep(3)

end = time.time()

print(end-start)

9、正则模块实际主要有2种应用

(1)、提取返回值中的一串字符串(比如想获得code的值)

使用:re. findall(regex, str)

(2)、判断返回值中是否有期望的值

使用:re. search

import re

text = “0000100” + \

a

res = re.findall(“(.*?)”, text)

print(res[0])

if re.search(“0001”, text):

print(“True”)

else:

print(“False”)

10、异常:运行期检测到的错误被称为异常

2种常用异常操作方式:

(1)、捕获异常

try:

操作步骤(比如open(一个不存在文件路径,”r”))

except 异常类型:         (异常类型种类https://www.cnblogs.com/zln1021/p/6106185.html)

print(异常信息)

(2)、自定义异常

raise Exception(异常信息)

11、练习

(1)、def sayHello(name):

hw = name

print(hw + “ SayHello”)

return hw  #不加retrun和加return这句查看下面运行结果

response = sayHello(“rlk”);

print(response)

(2)、写一个加法函数,得到a+b的结果

(3)、写一个减法函数,得到a,b的相差值(正数)

(4)、已知list = [“a”, 1 ,”name”,”age”] ,求分别进行下列操作得到list结果

list.append(“app”)

list.index(“name”)

list.insert(1,”ins”)

list.remove(“age”)

(5)、获得一个长度为6,里面字符为a-zA-z0-9的字符串(比如ay8372)

(6)、第一步在D盘写入一个文件mytest.txt,内容为“new create”

第二步追加内容(“追加的内容”)

第三步读取文件内容

(7)、计算第6题的执行时长,并打印当前时间(年-月-日 时:分:秒形式)

(8)、从code = “20foddlfk20000”中获取到0000

(9)、定义一个相加方法,当所得和小于20,抛出一个自定义异常

12、习题答案

(1)、加return情况返回rlk SayHello  以及  rlk

不加return情况返回rlk SayHello  以及 None

(2)、def add(a, b):

return a + b

sum = add(1, 2)

print(sum)

(3)------------------------------------------------

def subtraction(a, b):

if a > b:

return a - b

else:

return b - a

print(subtraction(2, 1))

(4)------------------------------------------------------------------------------------------

list.append(“app”) ---------------       ['a', 1, 'name', 'age', 'app']

list.index(“name”)  ---------------       2

list.insert(1,”ins”)   ----------------      ['a', 'ins', 1, 'name', 'age']

list.remove(“age”) ----------------      ['a',  1, 'name’]

(5)、

import random str2 = ""

for i in range(0,9):

str2 = str2 + str(i)

for i in range(65, 91):

str2 = str2 + chr(i)

for i in range(97,

123):

str2 = str2 + chr(i)

card = random.sample(str2, 6)

card = ''.join(card)

print(card)

(6)、

wt = open("d:/mytest.txt", "w")

wt.write("new create")

wt.flush()

wt.close()

fo = open("d:/mytest.txt", "a")

fo.write("追加的内容")

fo.flush()

fo.close()

rd = open("d:/mytest.txt", "r")

print(rd.readlines())

rd.close()

(7)、

import time

start = time.time()

wt = open("d:/mytest.txt", "w")

wt.write("new create")

wt.flush()

wt.close()

fo = open("d:/mytest.txt", "a")

fo.write("追加的内容")

fo.flush()

fo.close()

rd = open("d:/mytest.txt", "r")

print(rd.readlines())

rd.close()

end = time.time()

print(end - start)

print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

(8)、

import re code = "20foddlfk20000"

list = re.findall("(.*?)", code)

print(list[0])

(9)、

def add(a ,b):

sum = a + b

if sum >= 20:

return sum

else:

raise Exception("相加小于20了")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值