- 顺序执行
按照先后顺序一条一条执行,默认的执行顺序是从左至右,从上至下 - 分支
根据不同的情况,条件满足才执行条件下的语句 - 循环
只要满足某个条件,此条件下的语句就反复执行,直至条件不再满足
分支
单分支
if condition:
action
action
...
>>> if 1:
print ('hello world')
hello world ##默认情况下条件为真,因此执行输出语句
>>> if 0:
print ('hello world') ##输出语句只有在假的状态下才会执行,但是实际状态为真,因此此语句不执行
>>> if 1<2:
print ('1 is less than 2')
1 is less than 2 ##条件满足,执行输出
注意:
(1)condition必须是一个布尔值,这个地方有一个隐式的转换bool(condition)
(2)if语句最后需要以英文冒号:
结尾,冒号后面的语句需要另起一行,并且需要缩进
- if,for,def,class等关键字后面都可以跟代码块
- 这些语句后面可以嵌套,比如再接一个
if 2<3:pass
多分支
if condition1:
action
elif condition2:
action
elif condition3:
action
...
else: ##条件语句需要闭环,经常由else完成此种功能
action
>>> score=72
if score<60 and score >0:
print ("you don't pass this exam")
elif score >=60 and score <= 90:
print('you have passed this exam')
elif score > 90 and score <= 100:
print ('excellent!')
else:
print ('your score is wrong')
you have passed this exam ##根据条件的匹配,因此输出了第二个条件中的语句
`嵌套:`
>>> a=0
if a<0:
print ('a is less than zero')
else: ##在此分支下开启嵌套模式
if a==0:
print('a is zero')
else:
print ('a is greater than zero')
循环
while循环
while主要用于死循环,或者不能明确知道循环次数的场景
while crond:
block
while True: #死循环
pass #pass语句主要用于程序的架构,无实质意义
a=10
while a:
print(a)
a-=1
for语句
for element in iteratable: # 可迭代对象中有元素可以迭代,进入循环体
block
for i in range(0,10): # range为序列函数,左闭右开区间,[0,10)
print(i)
# 计数器
for i in range(0): #区间为[0,0),因此此语句无输出
print(i)
print('---------')
for i in range(-2): #计数器中i>=0因此此语句也无输出
print(i)
print('---------')
for i in range(1): #此语句有输出[0,1)
print(i)
# 打印偶数
for i in range(0, 10):
if i % 2 == 0 :
print(i)
for i in range(0, 10, 2):
print(i)
# 打印奇数
for i in range(0, 10):
if i % 2 != 0 :
print(i)
for i in range(1, 10, 2):
print(i)
使用逻辑与来判断奇偶数:
for i in range(0,10):
if i & 1: #与1逐位与运算并且为真的数必然为奇数
print(i)
#continue用法
for i in range(0,10):
if i & 1: #先匹配出奇数
continue #遇到奇数则跳过
else:
print(i) #成功输出偶数
#break用法
count=0
for i in range(7,1000,7):
print(i)
count+=1
if count>=20:
break #直接结束循环
for i in range(10):
print(i)
break ##在输出第一个数字0之后立即退出循环,因此本程序只输出一个0
for i in range(20):
print(i)
if i>=10:
break #break虽然在if条件语句下,但是break在执行时的生效对象是for循环
注意:continue和break只对循环有效,即使他们放在了条件判断语句下,生效对象也是其上层的循环