1.条件语句
2.循环语句
1.条件语句:
形式:
if 判断语句 : 执行语句1elif 判断语句2: 执行语句2elif 判断语句3: 执行语句3#...else: 执行语句4占位符 pass
意义:
if(如果) A : 就 B(当A为True)elif(或者) C : 就 D(当A为False并且C为True)else(否则) : 就E(当A和C都为False)#if a,b=1,2 if a > b: #if 必须接判断语句 print(a) elif a == b: #elif 后面必接判断语句,可以有多个 print('equal') else: #不能接语句 print(b) #可用pass函数占位 2##必须满足判断条件才会执行相应的语句#input(内置函数),用于获取输入,输出为字符串 >>> input('Please enter:') Please enter:a 'a' >>> input('Please enter:') Please enter:1 '1'#example a = input('Please enter your grade: ') if a.isdigit() : a = int(a) if a > 90 : print('A') elif a > 80 : print('B') elif a > 60 : print('C') else : print('difference') elif len(a) == 0 : print('Enter blank') else : print('enter is not a number!!!')#random 随机函数 >>> import random >>> a=random.randint(1,3) #闭区间,随机生成一个整数 >>> a 3 >>> a=random.randint(1,3) >>> a 1 >>> random.random() #随机生成0-1的浮点数 0.5976110450434942 >>> random.randrange(5) #随机范围,默认从0开始,也可定义(1,5),可添加步长左闭右开 1 >>> random.randrange(1,5) 2 >>> li=[1,23,4,5] >>> random.sample(li,2) #从序列中随机生成一个的指定的个数 [1, 5] >>> random.sample(li,1) [5] >>> random.sample(li,3) [1, 5, 23] >>> random.choice(li) #从序列中随机生成一个数 4
2.循环语句
1.while循环
while 判断语句A: 执行语句Belse: print('程序正常结束,执行else')
注意:循环要有终止条件
a=1while a < 5 : a += 1 print(a)a=1while a < 5 : print(a) a += 1a=1while a < 11 : if a % 2 == 0 : print(a) a += 1
2.break和continue (函数)
while True: break #终止循环 continue #跳过本次循环#break 会终止循环,循环不再执行#continue是跳过本次循环,循环继续#break 终止当前循环,循环不在执行 >>> a = 10 >>> while a > 4 : a -= 1 if a == 5 : break print(a) 9 8 7 6#continue 跳过本次循环,循环继续 >>> a = 10 >>> while a > 4 : a -= 1 if a == 5 : continue print(a) 9 8 7 6 4
3.range(函数)
range(10) #表示0 - 9 这个范围range(1,10) #表示 1 - 9这个范围range(1,10,2) #表示 1 - 9这个范围,并且以步长2进行取数>>> range(10)range(0, 10)>>> list(range(10))[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> range(1,10)range(1, 10)>>> list(range(1,10,2))[1, 3, 5, 7, 9]>>> list(range(1,10,3))[1, 4, 7]
4.for循环
for item in iterable: 执行语句else: print('程序正常结束,执行else')#循环条件可以是任何可迭代的对象,如:序列类型,集合和字典while,for:相同点:循环不同点:while需要些终止条件>>> for i in range(10): print(i) 0123456789a=5>>> for i in range(a): print(i) 01234
5.嵌套循环
>>> for i in range(1,3): print('***',i) for j in range(1,3): print('###',j) *** 1### 1### 2*** 2### 1### 2>>> for i in range(1,3): for j in range(1,3): print('###',j) print('***',i) ### 1### 2*** 1### 1### 2*** 2>>> for i in range(1,3): for j in range(1,3): print('###',j,end='') print('***',i)### 1### 2*** 1### 1### 2*** 2
6.else
while True: breakelse: print('OK')#for for item in iterable: breakelse: print('OK')""" 只有正常结束的循环,非break结束的循环才会执行else部分""">>> for i in range(5): if i == 3: break else: print('000 %s' % i) 000 0000 1000 2
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦