random库的使用
随机运算的标准函数库random共提供了9个常用函数。
Python内置的random库主要用于产生各种分布的伪随机数序列,所有的函数都是基于最基本的random.random()函数扩展实现。
random库的常用函数(共9个)

对random库的引用方法与math库一样
import random
-
from random import *
randrange(0,100,4)
从0开始到100以4递增的元素中随机返回。

随机生成100以内的10个整数
from random import *
for i in range(10):
print(randint(1,100),end=' ')

随机选取0到100间的奇数。
from random import *
print(randrange(0,100,1))
从字符串中'abcdefghij’中随机的选择4个字符。
from random import *
str='abcdefghij'
for i in range(4):
print(choice(str),end=' ')

异常处理
Python通过try、except等保留字提供异常处理功能。
1、异常处理:try-except
观察下列程序
num=eval(input("请输入一个整数:"))
print(num**2)

Python解释器返回了异常信息,同时退出了程序。

Python异常信息中最重要的部分是异常类型,它表明了发生异常的原因,同时也是程序处理异常的依据。
基本格式:
try:
<语句块1>
except <异常类型>:
<语句块2>
try:
num=eval(input("请输入一个整数:"))
print(num**2)
except NameError:
print("输入错误,请输入一个整数")

网友评论