sNane = "alloSAD HERop"
print(sNane.title())
print(sNane.upper())
print(sNane.lower())
rstrip 去除右边空格
lstrip 去除左边空格
strip 去除左右空格
sText = " howd ihiu gi hboip! "
print("111"+sText.rstrip()+"111")
print("111"+sText.lstrip()+"111")
print("111"+sText.strip()+"111")
整除符号 //,结果忽略小数部分
abs 返回一个数的绝对值
round 返回一个数四舍五入后的值
ceil 向上取整
floor 向下取整
%d 指一个整数
%.2f 指一个浮点数,保留两位小数
%s 字符串
%c 字符
sName = "Mary"
fPrice = 128.36
n = 5
sText = "%s has %d lambs, each lamb worth %.2f yuan. So, these lambs worth %.1f yuan. If in total." % (sName,n,fPrice,fPrice*n)
print(sText)
#Mary has 5 lambs, each lamb worth 128.36 yuan. So, these lambs worth 641.8 yuan. If in total.
0x 16进制
0b 2进制
hex() 数字转换为16进制
bin() 数字转换为二进制
%x 以16进制输出
append(x) 在列表尾部添加元素x
insert(index,x) 在index位置添加元素x,其中index从0开始
pop() 从列表尾部删除元素,并且返回删除的值(若pop(index) 则删除对应位置的元素)
del list[index] 删除index位置的元素
remove(x) 移除第一个遇到的x元素
sort 会改变列表元素的顺序
list.sort() 按递增(非递减)排序
list.sort(key=len) 使用len函数为每一个元素生成键值,按结果大小递增排序
list.sort(reverse=True) 按递减(非递增)排序
sorted(list) 不会改变列表元素的顺序 按递增(非递减)排序
list.reverse() 将列表元素顺序倒置
range(x) 从0到x(不包含x)
range(x,y) 从x到y (包含x,不包含y)
range(x,y,z) 从x到y,步长为z (包含x,不包含y)
生成列表:
cubs = [x**3+100 for x in range(1,11)]
print(cubs)
#[101, 108, 127, 164, 225, 316, 443, 612, 829, 1100]
生成10行8列矩阵:
matrix = [[0]*8]*10
print(matrix)
#更复杂
matrix = [[r*c for c in range(8)] for r in range(10)]
print(matrix)
matrix = [x + y for x in "abs" for y in "0123"]
print(matrix)
#['a0', 'a1', 'a2', 'a3', 'b0', 'b1', 'b2', 'b3', 's0', 's1', 's2', 's3']
list + list = list
list * n n为数字,列表将重复n次
string*n n为数字,字符串将重复n次
list.count(x) 返回列表中x出现的次数
list.clear() 清空列表所有元素
list.index(x) 返回x的下标
list[x:y] 从下标x一直复制到y (包含x但不包含y)
list[x:] 从x一直复制到列表尾部(包含最后元素)
list[:y] 从第一个元素一直复制到y(不包含y)
list[x:y:z] 从下标x一直复制到y,步长为z (包含x但不包含y)
list[2:4] = 77,78 将2和3位置的元素修改为77、78
元祖是只读列表。创建后只能读与操作,不能修改其元素与顺序。(可以切片/将不同元组连接)
patient = (1,2,3,4,5,6)
print(type(patient),patient)
print(patient[1:4])
print((1,2)+(3,4)+(5,))
print((1,2)*5)
'''
<class 'tuple'> (1, 2, 3, 4, 5, 6)
(2, 3, 4)
(1, 2, 3, 4, 5)
(1, 2, 1, 2, 1, 2, 1, 2, 1, 2)
'''
集合不允许重复的元素,同时,集合的元素不分前后顺序,不能使用下标访问集合,集合元素不能是列表、字典、集合
set() 创建集合 或 大括号{}
生成集合时,多余的元素将会被剔除掉
count = {1,2,3,4,5}
print(type(count),count)
s1 = set("hello")
print(s1)
s2 = set([1,3,5,7])
print(s2)
value = list(s2)
print(value)
'''
<class 'set'> {1, 2, 3, 4, 5}
{'e', 'o', 'l', 'h'}
{1, 3, 5, 7}
[1, 3, 5, 7]
'''
set.add() 向集合中添加一个元素
set.remove(x) 从集合当中移除指定元素x
len/sum/max/min 用法相同
set.pop() 从集合中随机数弹出并返回一个元素
s2.issubset(s1) 判断s2是否是S1的子集
s1.issuperset(s2) 判断s1是否是S2的超集
s1 & s2 交集
s1 | s2 并集
s1 - s2 差集
s1 ^ s2 补集
x = 65534
bufferLittle = x.to_bytes(2,'little')
print("little endian:",bufferLittle)
bufferBig = x.to_bytes(2,'big')
print("big endian:",bufferBig)
y = int.from_bytes(b'\xfe\xff','little')
print(y)
'''
little endian: b'\xfe\xff'
big endian: b'\xff\xfe'
65534
'''
#to_bytes(n,'little'/'big') 将整数转换成指定字节长度(这里为2),‘little’与‘big’为编码顺序,一般都是‘little’
#from_bytes() 将bytes 重新打包成int
与bytes相比,可修改
buffer = bytearray(0x00 for x in range(10))
print(type(buffer),buffer)
buffer = bytearray(b'abcdefghijklmn')
buffer[1] = ord('B')
print(buffer)
print(buffer[3:11:3])
'''
<class 'bytearray'> bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
bytearray(b'aBcdefghijklmn')
bytearray(b'dgj')
'''
& 按位与
| 按位或
<< 左移位
‘>>’ 右移位
sName = input('Please enter your name:').strip().lower()
sName = sName.split()
x = ord('a')
luckynumber = 0
for i in sName:
for j in i:
v = ord(j) - x + 1
luckynumber += v
print('value of',j,'=',v)
print("Your lucky number is:",luckynumber)
== 比较两个变量的值
a = 3
b = a
print('id(a)',id(a),'id(b)',id(b),end = '')
b = a.copy() 只复制列表本身,复制出来的列表与原列表仍可能绑定在一个相同的子列表对象上
b = copy.deepcop(a) 将列表与其嵌套列表完整复制
#copy2.py
a = [1,2,3,[3,2,1]]
b = a.copy()
print("id(a):",id(a),'id(b):',id(b))
print('id(a[3]):',id(a[3]),'id(b[3]):',id(b[3]))
b[3][2]= 99
print(a,b)
'''
id(a): 2471550621696 id(b): 2471550671744
id(a[3]): 2471520296256 id(b[3]): 2471520296256
[1, 2, 3, [3, 2, 99]] [1, 2, 3, [3, 2, 99]]
'''
#deepcopy2.py
import copy
a = [1,2,3,[3,2,1]]
b = copy.deepcopy(a)
print("id(a):",id(a),'id(b):',id(b))
print('id(a[3]):',id(a[3]),'id(b[3]):',id(b[3]))
b[3][2]= 99
print(a,b)
'''
id(a): 2037795479424 id(b): 2037795559424
id(a[3]): 2037795485632 id(b[3]): 2037795558720
[1, 2, 3, [3, 2, 1]] [1, 2, 3, [3, 2, 99]]
'''
x,y,z = 'x','y','z'
print(x,y,z)
#x y z
numbers = 1,2,3 #numbers = (1,2,3)
a,b,c = numbers #a=1,b=2,c=3
d,e,f = [4,5,6] #d=4,e=5,f=6
g,h,i = '789' #g=7,h=8,i=9
解包时,可以用*吸收多余的值
x,y,*rest = [1,2,3,4,5]
print(x,y,rest)
#1 2 [3, 4, 5]
x,*middle,y = [1,2,3,4,5]
from matplotlib import pyplot as plt
fBalance = 10000
fRate = 0.0005
balances = []
for i in range(365*30):
fBalance = fBalance + fBalance*fRate
balances.append(fBalance)
print('30年后连本带利欠款总额:%.2f'%fBalance)
plt.plot(list(range(365*30)),balances)
plt.title("Loan balance grow by days")
plt.show()
略
enumerate() 将序列的元素加上其下标,形成元组
reversed() 接受一个序列作为参数,返回一个可迭代对象,与原序列相反
names = ['Tom','Andy','Alex','Dorothy']
print(list(enumerate(names)))
for idx, name in enumerate(names):
print(names,'is at index',idx,'in the list.')
for x in reversed(names):
print(x)
'''
[(0, 'Tom'), (1, 'Andy'), (2, 'Alex'), (3, 'Dorothy')]
['Tom', 'Andy', 'Alex', 'Dorothy'] is at index 0 in the list.
['Tom', 'Andy', 'Alex', 'Dorothy'] is at index 1 in the list.
['Tom', 'Andy', 'Alex', 'Dorothy'] is at index 2 in the list.
['Tom', 'Andy', 'Alex', 'Dorothy'] is at index 3 in the list.
Dorothy
Alex
Andy
Tom
'''
exec 接受一个字符串,将其作为代码来执行。
eval 作用:去掉最外层的引号。
区别:exec无返回值,eval有返回值
exec('print("Hello, I am exex.")')
eval('print("Hello, I am eval.")')
'''
Hello, I am exex.
Hello, I am eval.
'''
#创建用大括号{}包裹,键值之间用:分隔,键值对之间用,分隔
#添加新的键值对只需要 字典名[键]=值 即可。
#获取给定键的值,只需要 字典名[键] 即可
#键可以是int类型等
phoneBook = {'Alex':'6511-2002','Betty':'6512-7252','Dora':'65546-2708',
'Peter':'6716-4203'}
phoneBook['Dorothy'] = '6557-7272'
print("Dora's call number is",phoneBook['Dora'])
print(type(phoneBook))
print(phoneBook)
'''
Dora's call number is 65546-2708
<class 'dict'>
{'Alex': '6511-2002', 'Betty': '6512-7252', 'Dora': '65546-2708', 'Peter': '6716-4203', 'Dorothy': '6557-7272'}
'''
dict() 函数可以将元组键-值对构成的列表或元组转换成字典
可以通过实参列表的键值对生成字典
items = [('name',1),('id',2),('age',3)]
dor = dict(items)
print(dor)
dor = dict(name='dor',id='10003',age='26')
print(dor)
'''
{'name': 1, 'id': 2, 'age': 3}
{'name': 'dor', 'id': '10003', 'age': '26'}
'''
用于完成输出时的字符替代
clear() 清楚所有内容
copy() 浅层拷贝,类似列表
fromkeys() 接受两个参数,第一个为一个序列,第二个为值的默认值,创建一个新的字典。第一个为键,第二个为对应的值。
get(name,value) 第一个为要返回的键,第二个为默认返回值。第一个键存在,返回其值,不存在,返回默认值value,当value省略时,返回none。
pop() 从字典中删除指定键值对,并返回值
popitem() 从字典中删除随机的键值对并返回值。(不确定删除)
update() 用一个字典更新另外一个字典
#x.update(y) 将字典y合并更新到字典x中
#fromkeys.py
d = dict.fromkeys(['id','name','age'],'notknown')
dl = {}.fromkeys(['id','name','age'],'notknown')
print(d)
print(dl)
'''
{'id': 'notknown', 'name': 'notknown', 'age': 'notknown'}
{'id': 'notknown', 'name': 'notknown', 'age': 'notknown'}
'''
dict.key() 返回字典所有的键
dict.value() 返回字典所有的值
dict.items() 返回字典所有的键值对
dora = {'id':'1003','name':'Dora Li','gender':'female',\
'age':88,'title':'sales'}
print("Dora.keys():",dora.keys)
print('Dora.values():',dora.values())
print('Dora.items():',dora.items())
sText = ''
for x in dora:
sText = x + '-' + sText
'''
Dora.keys(): <built-in method keys of dict object at 0x000001751A89F800>
Dora.values(): dict_values(['1003', 'Dora Li', 'female', 88, 'sales'])
Dora.items(): dict_items([('id', '1003'), ('name', 'Dora Li'), ('gender', 'female'), ('age', 88), ('title', 'sales')])
title-age-gender-name-id-
'''
dict.get(name,0) 默认字典不存在该键,返回0。
略
str = ''
n = 0
wordLen = 0
while True:
str = input("请输入英文句子,用空号分隔单词:('q'结束)")
if str == 'q':
break
str.strip()
fstr = str.split()
n += len(fstr)
for i in fstr:
for j in i:
wordLen += 1
print("输入单词数:{}".format(n))
print("平均单次长度:{}".format(wordLen/n))
'''
请输入英文句子,用空号分隔单词:('q'结束)hello, I am Dora.
请输入英文句子,用空号分隔单词:('q'结束)hello, I'm not dora.
请输入英文句子,用空号分隔单词:('q'结束)q
输入单词数:8
平均单次长度:3.875
'''
字符串称为 文档字符串-docstring
作为函数的属性存在,及 doc 。特殊属性。执行help(函数名) 可以调出函数的文档字符串
def add(x,y):
"Calculate the sum of two numbers.\
\nThe numbers could be integer or float"
return x+y
print(add.__doc__)
'''
Calculate the sum of two numbers.
The numbers could be integer or float
'''
*contents 形参吸收任意数量的实参,形成元组,传给contents.
一个函数中,带*的形参只能有一个,且只能放在最后。
带一个*号的形参不会吸收关键字参数,可以用带两个*的形参吸收
def myprint(title,*contents):
print(title,":")
for x in contents:
print("\t",x)
myprint("Read-only data type","int","float","str","tuple","tytes")
'''
Read-only data type :
int
float
str
tuple
tytes
'''
略
globals() 返回包含全部全局变量的字典
globals()[“name”] 返回全局变量为name的变量对应的值
from enum import Enum
class Gender(Enum):
male = 0
female = 1
class Person:
def __init__(self,idNo='N/A',name='N/A'):
self.name=name
self.gender=Gender.male
self.sId=idNo
self.iWeight=0
def speak(self):
print("Person():speak.")
def eat(self,weight):
self.iWeight += weight
print("Person():eat")
def description(self):
print("Person():description.")
def main():
a = Person()
a.eat(100)
a.description()
main()
'''
Person():eat
Person():description.
'''
......
dora = Person('659866600001','Dora Li')
Peter = Person('659866600002','Peter Wang')
dora.gender = Gender.demale
dora.iWeight = 1000000
dora.eat(360)
from Person import Person,Gender
class Employee(Person):
def __init__(self,emplNo,idNo,name):
Person.__init__(self,idNo,name)
self.sEmployeeNo = emplNo
self.sJobTitle = ''
self.sDepartment = ''
self.iWeekSalary = 0
def work(self):
print("I am a",self.sJobTitle+",","I \
am working with my parents in department:",self.sDepartment)
def speak(self):
print('Employee():speak')
def description(self):
print('Employee():description')
def main():
dora = Employee("007","369800001","Dora Li")
dora.sJobTitle = "Manager"
dora.sDepartment = "ShangHaiDaSha"
dora.work()
dora.speak()
dora.description()
main()
'''
I am a Manager, I am working with my parents in department: ShangHaiDaSha
Employee():speak
Employee():description
'''
abc 为库,@abstractmethod表示后面的是抽象函数
ABC是抽象基类
抽象类不能直接实例化
#Shapes.py #定义抽象类
from abc import ABC,abstractmethod
class Shape(ABC):
@abstractmethod
def draw(self):
pass
@abstractmethod
def getSize(self):
pass
必须实例化抽象类的所有成员函数,才能够创建对象
#Shapes.py
......
class Triangle(Shape):
def __init__(self):
pass
def draw(self):
print('Triangle::draw')
def getSize(self):
pass
def getArea(self):
return 0
t = Triangle()
t.draw()
'''
Triangle::draw
'''
未找到一个方法,会逐渐向父类寻找
class A:
def __init__(self):
print('A init.')
class B(A):
def __init__(self):
print('B init.')
class C(B):
def __init__(self):
print('C init.')
class D(C):
def __init__(self):
super(C,self).__init__()
print('D init.')
d = D()
'''
B init.
D init.
'''
几个与继承有关的方法:
issubclass(D,A) 确定D类是否是A类的子类
D.__bases__: 返回D类的基类
isinstance(d,B) 判断d对象是否是B类的实例
d.__class__ 返回对象d的类型
在变量名或函数名前加上 __ ,可以实现变量或函数的隐藏
{:} 称为替代字段,冒号前为替代字段名,冒号后为格式说明符
sText = "pi = {pi:e}.".format(pi=3.1415926)
print("pi:e",sText)
sText = "pi = {pi:.2f}.".format(pi=3.1415926)
print("pi:.2f",sText)
sText = "pi = {pi:.1%}.".format(pi=3.1415926)
print("pi:.1%",sText)
sText = 'n = {n:d}'.format(n=77)
print('n:d',sText)
sText = 'n = {n:b}'.format(n=77)
print('n:b',sText)
sText = 'n = {n:o}'.format(n=77)
print('n:o',sText)
'''
pi:e pi = 3.141593e+00.
pi:.2f pi = 3.14.
pi:.1% pi = 314.2%.
n:d n = 77
n:b n = 1001101
n:o n = 115
'''
冒号之后,加数字,设定宽度。
{:.5} 对字符串应用精度,这里取前五个字符
{:,} 十进制整数中逗号作为分节符
print('pi = {pi:10.2f}'.format(pi=3.1415926))
print('1k Bytes = {num:10} Bytes'.format(num=1024))
print('{:.5}'.format("Da caudas"))
print('pow(2,64) = {:,}'.format(2**64))
'''
pi = 3.14
1k Bytes = 1024 Bytes
Da ca
pow(2,64) = 18,446,744,073,709,551,616
'''
{pi:010.2f} 宽度为10,精度为2,10前面的0表示补0
< 表示左对齐, ^表示居中,>表示右对齐。
{:@>10.2f} 表示宽度为10,精度为2,右对齐,用@符号填充
{0:+10.2f} 使用第0个参数,正号表示要显示正号
{0:=+10.2f} 使用第0个参数,正号表示要显示正号。等号表示在符号位和数之间插入空格满足10位宽度。
print('pi = {pi:010.2f},{pi:<10.2f},'
"{pi:^10.2f},{pi:@>10.2f}".format(pi=3.1415926))
print('pi = {0:+10.2f}, {1:=+10.2f}'.format(3.14159,3.14159))
'''
pi = 0000003.14,3.14 , 3.14 ,@@@@@@3.14
pi = +3.14, + 3.14
'''
center(x,y) 接收两个参数,第一个为目标宽度,第二个为填充字符,默认为空格。
ljust() 右边补填充字符 rjust() 左端补填充字符 zfill() 左端补0
print("'","center".center(60),"'")
print("center".center(60,"*"))
print("'","ljust".ljust(80,"*"))
print("'","rjust".rjust(80,"*"))
print("'","zfill".zfill(80))
'''
' center '
***************************center***************************
' ljust***************************************************************************
' ***************************************************************************rjust
' 000000000000000000000000000000000000000000000000000000000000000000000000000zfill
'''
find(str,start,end) 寻找str第一次出现的位置下标。从start下标到end下标,寻找str字符串,未找到返回-1,找到返回首字符出现的下标。(默认为整个字符串范围内寻找)
rfind() 寻找str最后一次出现的未知下标。
index(str) 找指定子串第一次出现的位置下标,未找到引发异常。
rindex(str) 找指定子串最后一次出现的位置下标,未找到引发异常。
count() 统计子串出现的次数
startwith() 是否以子串开头
endwith() 是否以子串结尾
s = "python is easy to learn. is easy to use."
print(s.find("to",0,len(s)))
print(s.find("not exist"))
print(s.rfind("to",0,len(s)))
'''
15
-1
33
'''
将序列里多个字符串用指定的间隔字符串拼接起来。
str.replace(s1,s2) 用s2代替str里的s1,不改变str字符串。
dir = ["","i","don't","like","it"]
print('/'.join(dir))
s = "python is good."
str = s.replace("python","C++")
print("str:",str)
print("s:",s)
'''
/i/don't/like/it
str: C++ is good.
s: python is good.
'''
split() 将字符串用指定的间隔符拆分成多个字符串,并放入一个列表中返回。
partition(sep) 将字符串用指定的字符串拆分成3个字符串:sep前的部分,sep,sep后的部分并放入一个元组中返回。
splitlines() 拆分字符串为多行
print("1+2+3+4+5".split("+"))
print("1 2 3 4 5".split())
'''
['1', '2', '3', '4', '5']
['1', '2', '3', '4', '5']
'''
translate()
isspace()/isdigit()/isupper()/islower()/isdecimal()/isidentifier()/isnumeric()/istitle
open(file,mode) 打开一个文件,file为文件名也可以是绝对路径,mode参数为字符串,表明文件的工作模式
close() 关闭打开的文件。应该在不用时关闭文件。或者也可以用flush()函数。
f.write() 向文件写入字符串
f.read() 从文件读出全部内容,并以字符串形式(文本模式时)返回。
f.read(5) 从文件读取5个字符。
f.readline() 从文件读取一行
f.readlines() 读取所有内容,并把每一行作为一个元素存储在一个列表中返回。
f.writelines() 向文件写入一行
w 只能操作写入 r 只能读取 a 向文件追加
w+ 可读可写 r+可读可写 a+可读可追加
wb+写入进制数据
w模式打开文件,如果而文件中有数据,再次写入内容,会把原来的覆盖掉
f = open("datafile.txt","w")
f.write("This is a file\n")
f.write("'w' means open file in write mode.")
f.close()
f = open("datafile.txt","r")
sLine1 = f.readline()
sLine2 = f.readline()
print(sLine1,sLine2)
f.close()
'''
This is a file
'w' means open file in write mode.
'''
sys.stdin 输入
sys.stdout 输出
sys.stderr 错误
import sys
f = open("input.txt","w")
f.write("Alex\n")
f.write("18\n")
f.close()
fIn = open("input.txt","r")
sys.stdin = fIn #将输入流重定向到文件input.txt中,后同
fOut = open('output.txt','w')
sys.stdout = fOut
fError = open('error.txt','w')
sys.stderr = fError
sName = input("What's your name>")
iAge = int(input("How old are you?"))
print("Hi,",sName.title(),"You are {} years old.".format(iAge))
fIn.close()
fOut.close()
raise Exception("ERROR INFO")
fError.close()
'''
#input.txt
Alex
18
#output.txt
What's your name>How old are you?Hi, Alex You are 18 years old.
#error.txt
Traceback (most recent call last):
File "d:\Study\ѧϰ\pythonLearn\Chapter11\stdio.py", line 22, in <module>
raise Exception("ERROR INFO")
Exception: ERROR INFO
'''
with等等,按行,按字符
略
略
最初来源于JavaScript,具有轻量级跨语言特性
默认只支持字符串、整数、浮点数、布尔型、字典、列表等数据类型的序列化与反序列化,不直接支持类等
json.dump(value,file) 将value放入file中
json.load(file) 读取file的内容
import json
dora = {'name':'dora','no':'20136987','age':20,'married':False,
'score':[{'C++':88},{'Data Structure':98},{'Math':89}]}
with open('dora.json','w') as f:
json.dump(dora,f)
with open('dora.json') as f:
doraLoaded = json.load(f)
for key,value in doraLoaded.items():
print(key+':',value)
'''
name: dora
no: 20136987
age: 20
married: False
score: [{'C++': 88}, {'Data Structure': 98}, {'Math': 89}]
'''
f = open(file,‘rb’) 读取二进制文件
“<f” 中的<表示是little endian格式,f表明是4字节的浮点数
rawData[i*4:i*4+4] 对rawData切片
unpack() 函数返回元组
fValue, = 中逗号并非多余,告诉解释器,此处为序列解包
#若二进制文件有1600个字节,没四个字节一个float
import struct
rawData = f.read()
iSampleCount = len(rawData) // 4
curData = []
for i in range(iSampleCount):
fValue, = struct.unpack("<f",rawData[i*4:i*4+4])
curData.append(fValue)
- 通常以"wb"-二进制写模式打开
- 把需要写的数据通过struct.pack() 函数打包成bytes类型
- 执行file.write(bytes) 将数据写入
import struct
k = [1,2,3,4,5,6,7]
f = open("fileName","wb")
for x in k:
data = struct.pack("<f",x)
f.write(data)
f.close()
先执行try内语句块。若出现异常,在except语句块内找对应异常,最后执行finally语句块。否则执行try语句块后,执行else语句块,最后执行finally语句块。
出现异常后,按顺序在except语句块内寻找对应异常,做相应处理。
def divide(a,b):
return a/b
while True:
sFirst = input("First number:")
sSEcond = input("Second number:")
if sFirst == "q" or sSEcond == "q":
break
try:
iFirst = int(sFirst)
iSecond = int(sSEcond)
fResult = divide(iFirst,iSecond)
except (ZeroDivisionError) as e:
print("You can not divide by 0:",e)
except (ValueError,TypeError) as e:
print("Illegal value been inputed:",e)
print(type(e))
except (Exception) as e:
print("An exception found, I do not know how to process it.")
raise
else:
print(sFirst,'/',sSEcond,'=',fResult)
finally:
print("Finally will be executed what ever happens.")
'''
First number:15
Second number:3
15 / 3 = 5.0
Finally will be executed what ever happens.
First number:15
Second number:0x38
Illegal value been inputed: invalid literal for int() with base 10: '0x38'
<class 'ValueError'>
Finally will be executed what ever happens.
First number:q
Second number:q
'''
warn(str) 发出警告,不影响程序执行
from warnings import warn
def divide(a,b):
fResult = a/b
if fResult <0.0000001:
warn("The result is very close to zero.")
return fResult
print(divide(0.1,10000000000))
print("Something error.")
'''
UserWarning: The result is very close to zero.
warn("The result is very close to zero.")
1.0000000000000001e-11
Something error.
'''
略
testcase方法表:略
先进行功能分析,再设计测试用例与测试代码,再编写代码实现功能,使用测试用例进行测试。
#testisprime.py
from prime import isPrime
import unittest
class isPrimeTestCase(unittest.TestCase):
def testIsPrime(self):
self.assertEqual(isPrime(2),True,'素数判断错误')
self.assertEqual(isPrime(7),True,'素数判断错误')
self.assertEqual(isPrime(12),False,'12不是素数,判断错误')
self.assertEqual(isPrime(0),False,'0不是素数,判断错误')
self.assertEqual(isPrime(1),False,'1不是素数,判断错误')
self.assertEqual(isPrime(-2),False,'负数')
if __name__=='__main__':
unittest.main()
#prime.py
from math import sqrt
def isPrime(a):
if a <= 1:
return False
elif a==2:
return True
elif a==3:
return True
else:
k = int(sqrt(a))
for i in range(2,k+1):
if a % i == 0:
return False
return True
'''
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
'''
略