Python学习day09 - Python进阶(3)异常处理1. 什么是异常2. 语法错误3. 逻辑错误4. 万能捕捉异常的方式Python深浅拷贝1. 拷贝(赋值)2. 浅拷贝3. 深拷贝基本的文件操做1. 找到文件路径2. 双击打开3. 看文件4. 写文件5. 关闭文件实战之猜年龄游戏html
异常其实就是咱们平时写程序运行程序时的报错,在Python中,异常通常分为两类,即语法错误和逻辑错误node
语法错误过不了python解释器的语法检测,因此在程序执行以前必须改正,不然程序没法正常执行。python
常见以下例:git
xxxxxxxxxx
if#SyntaxError: invalid syntax
0 = 1#SyntaxError: can't assign to literal
语法错误的错误类型基本都是SyntaxError
,后面是较详细的描述。web
逻辑错误不一样于语法错误的是,其错误类型比较多样。好比:windows
xxxxxxxxxx
# TypeError:int类型不可迭代
for i in 3:
pass
# ValueError
num=input(">>: ") #输入hello
int(num)
# NameError
aaa
# IndexError
l=['egon','aa']
l[3]
# KeyError
dic={'name':'egon'}
dic['age']
# AttributeError
class Foo:pass
Foo.x
# ZeroDivisionError:没法完成计算
res1=1/0
res2=1+'str'
固然咱们捕捉异常是为了发现,并处理异常,因此这里介绍一种万能的捕获异常的方法:app
xxxxxxxxxx
s1 = 'hello'
try:
int(s1)
except Exception as e:
print(e)
Exception
能够替代全部的异常类型用来赋值输出,很是方便。而实际上如今的解释器自己的报错,定位错误的功能都挺强大的,因此用这个功能比较有限。less
通常Python的拷贝分为如下三种,咱们分别介绍,用copy以前记得加上头文件import copy
.dom
赋值的常见方式以下:ide
xxxxxxxxxx
lt = [1, 2, 3]
lt2 = lt
print(lt)
print(lt2)
lt.append(4)
print(lt)
print(lt2)
[1,2,3]
[1,2,3]
[1,2,3,4]
[1,2,3,4]
xxxxxxxxxx
上述打印结果能够看到,lt的值变化,lt2的值也会跟着变化,这就是最通常的赋值
xxxxxxxxxx
# lt2没有变化的状况
lt = [1, 2, 3]
lt2 = copy.copy(lt)
lt.append(4)
print(lt) # [1, 2, 3, 4]
print(lt2) # [1, 2, 3]
以上就是lt2没有跟随lt变化而变化,由于添加修改的是一个字符串,不是可变类型。
xxxxxxxxxx
# lt2变化的状况
lt = [1, 2, 3,[4,5,6]]
lt2 = copy.copy(lt)
lt[3].append(7)
print(lt) # [1, 2, 3, [4,5,6,7]]
print(lt2) # [1, 2, 3,[4,5,6]]
该例就是lt2跟随lt变化的状况,由于往里面添加的是修改一个列表,是可变的类型。
深拷贝是最稳定的拷贝,也是对原值保留最好的,永远不会随原值改变。
xxxxxxxxxx
t = [1000, 2000, 3000, [4000, 5000, 6000]]
print('id(lt)',id(lt))
print('id(lt[0])', id(lt[0]))
print('id(lt[1])', id(lt[1]))
print('id(lt[2])', id(lt[2]))
print('id(lt[3])', id(lt[3]))
print('*' * 50)
lt2 = copy.deepcopy(lt)
print('id(lt2)',id(lt2))
print('id(lt2[0])', id(lt2[0]))
print('id(lt2[1])', id(lt2[1]))
print('id(lt2[2])', id(lt2[2]))
print('id(lt2[3])', id(lt2[3]))
print('*' * 50)
由以上打印结果能够看出,无论lt怎么改变,lt2都不会随之改变。
xxxxxxxxxx
# 牢记: 拷贝/浅拷贝/深拷贝 只针对可变数据类型
# 拷贝: 当lt2为lt的拷贝对象时,lt内的可变类型变化,lt2变化;lt内的不可变类型变化,lt2变化。
#浅拷贝:当lt2为lt的浅拷贝对象时,lt内的可变类型变化,lt2变化;lt内的不可变类型变化,lt2不变化
# 深拷贝: 当lt2为lt的深拷贝对象时,lt内的可变类型变化,lt2不变化;lt内的不可变类型变化,lt2不变
什么是文件呢,以前的博客中有介绍,文件其实就是操做系统提供给用户的一个虚拟单位,是用来存储数据的。那么用Python来对文件操做有如下几个经常使用的操做。
xxxxxxxxxx
path = r'D:\Python学习\.idea\Python学习.iml'
# python里就是这样打开文件路径的,以上这种也叫作绝对路径。相对路径能够以下表示
path = r'Python学习.iml'
#相对路径即你所执行的这个py文件的当前文件夹,会默认在这里搜索
xxxxxxxxxx
f = open(path,'w',encoding = 'utf8')
print(f)
# r-->只读,w-->只写,清空当前文件后写入,后面的encoding为所打开文件的编码格式
xxxxxxxxxx
data = f.read()
print(data)
xxxxxxxxxx
f.write('fsfda')
xxxxxxxxxx
del f
f.close()
#须要注意的是,del f只是删除了解释器对文件的引用,并无真正关闭文件,只有f.close才是真正的关闭文件
这是最近学习遇到的第一个稍有规模的代码,实现方式有不少种,如下两种仅供参考:
题目需求以下:
常规猜年龄
xxxxxxxxxx
import random
age = random.randint(18, 60) # 随机一个数字,18-60岁
count = 0 # 计数
f = open('price.txt', 'r', encoding='utf8') # price.txt右下角为何编码,则encoding为何编码
price_dict = f.read()
price_dict = eval(price_dict) # type:dict # 获取奖品字典
f.close()
price_self = dict()
while count < 3:
count += 1
inp_age = input('请输入你想要猜的年龄:')
# 判断是否为纯数字
if not inp_age.isdigit():
print('搞事就骂你傻逼')
continue
inp_age = int(inp_age)
# 筛选年龄范围
if inp_age > 60 or inp_age < 18:
print('好好题目,18-60岁,非诚勿扰')
continue
# 核心逻辑
if age == inp_age:
print('猜中了,请选择你的奖品')
# 打印商品
for k, v in price_dict.items():
print(f'奖品编号:{k} {v}')
# 获取奖品的两次循环
for i in range(2):
price_choice = input('请输入你须要的奖品编号:')
if not price_choice.isdigit():
print("恭喜你已经得到一次奖品,奖品为空!而且请输入正确的奖品编号!")
continue
price_choice = int(price_choice)
if price_choice not in price_dict:
print('你想多了吧!')
else:
price_get = price_dict[price_choice]
print(f'恭喜中奖:{price_get}')
if price_self.get(price_get):
price_self[price_get] += 1
else:
price_self[price_get] = 1
print(f'恭喜你得到如下奖品:{price_self}')
break
elif age > inp_age:
print('猜小了')
elif age < inp_age:
print('猜大了')
continue
抽奖式猜年龄
xxxxxxxxxx
import random
age = random.randint(18, 19) # 随机一个数字,18-60岁
count = 0 # 计数
f = open('price.txt', 'r', encoding='utf8') # price.txt右下角为何编码,则encoding为何编码
price_dict = f.read()
price_dict = eval(price_dict) # type:dict # 获取奖品字典
f.close()
price_self = dict()
while count < 3:
count += 1
inp_age = input('请输入你想要猜的年龄:')
# 判断是否为纯数字
if not inp_age.isdigit():
print('搞事就骂你傻逼')
continue
inp_age = int(inp_age)
# 筛选年龄范围
if inp_age > 60 or inp_age < 18:
print('好好题目,18-60岁,非诚勿扰')
continue
# 核心逻辑
if age == inp_age:
print('猜中了,请选择你的奖品')
# 打印商品
for k, v in price_dict.items():
print(f'奖品编号:{k} {v}')
# 获取奖品的两次循环
for i in range(2):
price_y = input(f'请按"Y or y"转动转盘{chr(9803)}:').lower()
if price_y != 'y':
print("恭喜你已经得到一次奖品,奖品为空!而且请输入'Y or y'!")
continue
#
price_choice = random.randint(0, 10000)
if price_choice > 0 and price_choice < 9900:
price_choice = 6
print('恭喜你, 下次必定有好东西!!', end=' ')
else:
price_choice = price_choice % 7
if price_choice not in price_dict:
print('你想多了吧!')
else:
price_get = price_dict[price_choice]
print(f'恭喜中奖:{price_get}')
if price_self.get(price_get):
price_self[price_get] += 1
else:
price_self[price_get] = 1
print(f'恭喜你得到如下奖品:{price_self}')
break
elif age > inp_age:
print('猜小了')
elif age < inp_age:
print('猜大了')
continue
以上内容均借鉴于恩师nick的博客,但愿你们都去借鉴,关注,点赞~