程序的控制类型

程序的控制类型

程序的分支结构

二分支模式

紧凑形式

<表达式1> if 条件 <表达式2>

条件判断及组合

条件组合

x and y

x or y

not x

程序的异常处理

try:
<语句块>
except <异常类型>:
<语句块>
try:
<语句块>
except <异常类型>:
<语句块>
else:
<语句块>
#不发生异常执行
finally:
<语句块>
#一定执行

程序的循环结构

遍历循环

for i in range(N):
<语句块>
for i in range(M,N,K):
for c in s:
#s是字符串,遍历字符串每个字符
#例:
for c in "hello":
print(c,end=",")
#h,e,l,l,o,
for item in ls:
#列表
for line in fi:
#文件,遍历每行

无限循环

while 条件:
<语句块>

循环的高级用法

循环与else

while 条件:
<语句块>
else:

循环没有被break退出时,执行else

random库

基本随机数函数

seed() 随机数种子

random() 产生[0.0,1.0)的随机小数

扩展随机数函数

randint(a,b) 产生[a,b]的随机整数

randrange(m,n(,k)) 产生[m,n)之间以k步长为的随机整数

uniform(a,b) 产生[a,b]的随机小数

choice(seq) 从序列seq中随机选一个元素

random.choice([1,2,3,4])

shuffle 将序列seq中的元素随机排列

 

posted @ 2021-10-15 22:09  clown-lan  阅读(80)  评论(0)    收藏  举报