1.条件语句:git
形式:dom
if 判断语句 : 执行语句1 elif 判断语句2: 执行语句2 elif 判断语句3: 执行语句3 #... else: 执行语句4 占位符 pass
意义:ide
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循环code
while 判断语句A: 执行语句B else: print('程序正常结束,执行else')
注意:循环要有终止条件对象
a=1 while a < 5 : a += 1 print(a) a=1 while a < 5 : print(a) a += 1 a=1 while 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(函数)input
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循环it
for item in iterable: 执行语句 else: print('程序正常结束,执行else') #循环条件能够是任何可迭代的对象,如:序列类型,集合和字典 while,for: 相同点:循环 不一样点:while须要些终止条件 >>> for i in range(10): print(i) 0 1 2 3 4 5 6 7 8 9 a=5 >>> for i in range(a): print(i) 0 1 2 3 4
5.嵌套循环for循环
>>> 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: break else: print('OK') #for for item in iterable: break else: print('OK') """ 只有正常结束的循环,非break结束的循环才会执行else部分 """ >>> for i in range(5): if i == 3: break else: print('000 %s' % i) 000 0 000 1 000 2