day13-异常和模块

一、异常

1.异常
  • 运行程序的时候程序报错,又叫程序出现异常
  • 当执行程序的时候如果出现异常,出现异常的线程会直接奔溃,不会再执行线程中后面其它的代码
list1 = [1, 2, 3]
# print(list1[10])  # IndexError: list index out of range
print('==================')
2.异常捕获

1)语法一:可以捕获任何类型的异常

try:
    代码块1
except:
    代码块2
其他语句

说明:

  • try, except —— 关键字,固定写法
  • 代码块1 —— 和try保持一个缩进的一条或者多条语句;需要捕获异常的代码
  • 代码块2 —— 和except保持缩进的一条或者多条语句;异常发生后会执行的代码

执行过程:
会执行代码块1,
如果在执行代码块1的时候出现了异常,程序不奔溃,直接执行代码块2;然后再执行后面的其他语句;
如果在执行代码块1的时候没有出现异常,代码块2不会执行;直接执行后面的语句

try:
    print({'a': 10}['b'])  # KeyError: 'b'
    list1 = [1, 2, 3]
    print(list1[10])
    print('=======')
except IndexError:
    print('出现异常!')
except KeyError:
    print('KeyError')

# name = input('姓名:')
# try:
#     age = int(input('请输入年龄:'))
#     # age += 'abc'
# except ValueError:
#     print('输入有误!年龄只能是数字!')

"""

2)语法二:捕获指定异常

try:
    代码块1
except 异常类型:
    代码块2

执行过程:
先执行代码块1的时候出现异常,检查异常类型和except后面的异常类型是否一致;
如果一致程序不奔溃,直接执行代码块2;
如果不一致,程序直接奔溃;
如果执行代码块1的时候没有出现异常,不执行代码块2,接着往后执行。

print('======================================')
try:
    # print([1, 2, 3][10])
    print({'a': 1}['b'])
    print('===========')
    print({'a': 1}['b'])
    print('+++++')
except KeyError:
    print('key值错误')

"""

3)语法三:同时捕获指定多个异常

try:
    代码块1
except (异常类型1, 异常类型2, ...):
    代码块2

4)语法四:同时捕获多个异常

try:
    代码块1
except 异常类型1:
    代码块11
except 异常类型2:
    代码块22
...
3.finally

前面四种捕获异常结构的最后面都可以添加一个finally;
finally后面的代码段一定会执行

try:
    代码块1
except:
    代码块2
finally:
    代码块3
其他语句
try:
    # print({'a': 1, 'd': 2}['b'])
    print('====2222====')
    # print([1, 2, 3][10])
except IndexError:
    print('错误!下标越界!')
finally:
    print('写遗书!')
print('其他语句')
4.抛出异常

主动让程序奔溃

语法:
raise 异常类型

说明:异常类型必须是Exception的子类

class AgeError(Exception):
    def __str__(self):
        return '年龄值范围不在0~150'


age = 1000
if not 0 <= age <= 150:
    raise AgeError  # __main__.AgeError: 年龄值范围不在0~150

二、模块的使用

1.什么是模块

python中一个py文件就是一个模块

import math
import random
math.sqrt(4)
print(random.randint(1, 3))
print(dir(math))
2.怎么在一个模块中使用另外一个模块中的内容

如果要在一个模块中使用另外一个模块中的内容,必须先导入模块

1)语法:

a. import 模块名
导入指定模块,导入后可以在当前模块中使用模块中所有的全局变量,以模块名.全局变量名的方式去使用

b.from 模块名 import 变量名1, 变量名2, ...
导入指定模块,导入后只能使用import后面指定的变量
导入后的指定的全局变量在当前模块中直接使用,不用在前面加模块名.

c.from 模块名 as 新模块名
导入后采用新模块名去使用模块中的内容

e.from 模块名 import 变量名1 as 新变量名1, 变量名2, ...

# 导入方式一:
import test
print(test.test_a, test.test_str1)
test.func1()

# 导入方式二
from test import test_a, func1
print(test_a)
func1()
print(test_str1)  # NameError: name 'test_str1' is not defined
print(test.test_str1)  # NameError: name 'test' is not defined

# 导入方式三
from test import *
print(test_str1, test_a)
func1()

# 模块重命名
import fileManager as FM
FM.readfile()
FM.writefile()

import time as TIME
time = 10
print(TIME.asctime(TIME.localtime(TIME.time())))

from test import a as ta
a = 100
print(a, ta)
3.导入模块的原理

当执行导入模块的时候,会直接执行被导入的模块中的所有的代码

1)重复导入问题
import在导入模块的时候会自动检测这个模块之前是否已经导入过,来避免一个模块的重复导入

2)阻止模块中的内容被其他模块导入
将不需要被其他模块执行的语句写入if __name__ == '__main__'对应的if语句中

import test
from test import test_a
import test
import test
from test import test_a

from test2 import save_file

import test2
print('04: ', __name__)

需要的test模块(test.py文件)

import fileManager
print('========================test开始================')
a = 10

test_a = 100

test_str1 = 'hello'


def func1():
    # a = 10
    print('test中的函数')


func1()
print('================test结束================')

需要的test2模块(test2.py)

# import requests


def download(url):
    print('网络请求不断获取数据')
    save_file('')
    print('将获取到的数据保存到本地')


def save_file(file):
    print('保存文件的功能')


def main():
    a = 10
    download('海贼王1.mp4')
    download('海贼王2.mp4')
    download('海贼王3.mp4')


print('test2: ', __name__)
if __name__ == '__main__':
    main()

需要的fileManager模块(fileManager.py)

import test
print('=============fileManager开始=============')


def readfile():
    print('fileManager模块里的函数readfile')


def writefile():
    print('fileManager模块名里的函数writefile')


print('=============fileManager开始=============')

三、包的使用

1.什么是包

一个带有__init__.py文件的文件夹就叫包

a. 直接导入包 —— 只执行__init__.py文件

import animals
print(animals.cat.c)
print(animals.type1)
animals.fly

from animals import bird
bird.fly()

b.从包中导入指定的模块

from animals import bird, dog, cat
print(bird.b)

c.从包中的模块导入变量

from animals.cat import c
print(c)

新建一个animals包(含__init__.py文件的文件夹),里面包含cat、dog、bird模块(cat.py文件、dog.py文件、bird.py文件)

./animals/__init__.py文件

from animals import bird
from animals import cat
from animals import dog
print('animals=======__init__')

# Bird = bird
type1 = '飞行'
fly = bird.fly

./animals/cat.py文件

print('猫')
c = 200

./animals/dog.py文件

print('狗')
d = 300

./animals/bird.py文件

print('鸟')
b = 100


def fly():
    print('鸟:飞行')

四、系统常用模块

1.hashlib模块

1)加密

hashlib是python3.x提供的一个hash加密函数,支持目前主流一些加密sha256, md5等

hash加密的特点:
a. 相等的数据采用同一个加密算法,保证加密结果一样
b. 通过加密后的数据不能反向获取原数据采用同样的加密算法,不管原数据的大小是多少,加密后的数据的长度是一样

2)加密步骤

pw = input('请输入密码:')
# a.根据加密算法创建一个hash对象
hash1 = hashlib.sha256()
# hash1 = hashlib.sha1()
# hash1 = hashlib.md5()
# b.对数据进行加密
# hash对象,update(加密数据) - 加密数据必须是二进制数据
# 字符串转二进制:a.字符串.encode(encoding='utf-8') b.bytes(字符串, encoding='utf-8')
# hash.update(pw.encode(encoding='utf-8'))
# hash1.update('你好'.encode())
hash1.update(pw.encode())
# 3)根据hash对象获取加密后的数据
result = hash1.hexdigest()
# sha256: 8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92
# sha256: 8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92
# sha256: 32f45ec3cd0d56235672d8e4620d385c3e279612e5f454b52f077ceb9b8f9130
# sha1: 7c4a8d09ca3762af61e59520943dc26494f8941b
# md5: e10adc3949ba59abbe56e057f20f883e
print(result)

你可能感兴趣的:(day13-异常和模块)