python中的异常:
异常:程序运行中出现的问题或者错误成为程序的异常
控制台会出现(每个异常包含的信息):出错的文件, 行数,具体代码,错误类型,错误的代码
异常处理的模式
异常处理:当程序出现异常的时候,对程序进行处理、
形式一:
try:
监控的代码块
except:
如果监控代码出现问题,怎么处理
形式二:
try…except 错误类型 as e…
#定义一个函数,传入一个字典和字符串,判断字符串是否为字典中的值,如果字符串不在字典中,则添加到字典中,并返回新的字字典
import random
def randomkey(dic):
random_key = "".join(random.sample("abcdefghigklmnopqrstuvwxyz", 3))
while random_key in dic.keys():
random_key = "".join(random.sample("abcdefghigklmnopqrstuvwxyz", 3))
return random_key
def hslx(dic,str):
if str not in dic.values():
if str not in dic.keys():
dic[str]=str
print(dic)
else:
key = randomkey(dic)
dic[key] = str
print(dic)
else:
print(dic)
dic={"key":"value","key2":"abc"}
str="aa"
hslx(dic,str)