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