注:本笔记对应江灏老师在B站的教学视频https://www.bilibili.com/video/BV1zE411V79p
python的程序控制
(一)顺序语句
(二)分支语句
条件判断语句
-
python中提供的分支语句
#单分支 id = 0 if id == 0: print("user") #双分支 id = 50 if id == 0: print("user") else: print("visitor") #多分支 id = 100 if id ==0: print("user") elif id ==100: print("VIP user") else: print("visitor")
-
if嵌套
day=input("today is: ") weather=input('the weather is: ') if day in ['Saturday','Sunday']: if weather == 'sunny': print('let`s go to hiking!') elif weather == 'rainy': print("let`s go to some coffee!") else: print("let go to movie") else: print("just work!!!!!!!")
-
if中常用的操作符:
< <= > >= == !=
(三)循环语句
有while 和for,但是没有do while,还会用到continue和break
-
while循环
#while循环 a = 1 while a<10: print(a) a += 2 #while与if结合 a = 1 while a<7: if(a%2==0): print(a,"is even") else: print(a,"is odd") a+=1
-
for循环
格式:
(1)for 变量 in 某序列:
(2)for 变量 in range(start,stop,step): #(起始,停止,步长)
(3)for 变量 in range(len(序列)):
fruit = ["apple","banana","peach","orange"] for x in fruit: print(x) #输出序列中的元素 print("\n") for i in range(len(fruit)): print(i) #输出0,1,2,3 print("\n") for i in range(len(fruit)): print(i,fruit[i]) print("\n") for i in range(5): print(i) #输出0,1,2,3,4 pront("\n") for i in range(3,7): print(i) #输出3,4,5,6 print("\n") for i in range(1,10,3): print(i) #输出1,4,7
-
break,continue,pass
break:可以跳出for和while循环体,终止后,任何对应循环else块将不再执行
break用于跳出本层循环
for letter in "python": if letter == 'h': break print("输出字母为: ",letter) print("\n") var = 10 while var>0: print("当前变量为: ",var) #没有5及后面的4,3,2,1 var = var-1 if var==5: break print("Good bye")
continue:用于退出本次循环,继续下次循环
var = 10 while var>0: var = var-1 if var==5: continue print("当前变量为",var) #没有5,有后面的4,3,2,1 print("Good bye")
pass:在程序中没有作用,仅仅是空白,也就是占位符,为了代码的完整性和美观
for letter in "Python": if letter == 'o': pass print("执行pass块") print("当前字母: ",letter) print("Good bye")