流程控制语句
判断语句
- if语句
# if 后面的条件为真则执行,否则不执行
if 1 + 2 == 3:
print("1 + 2 == 3")
if 1 + 2 == 4:
print("1 + 2 == 4")
1 + 2 == 3
- if … else …
# if 后面的条件为真则执行,否则else执行
if 1 + 2 == 3:
print("1 + 2 == 3")
else:
print("1 + 2 != 3")
if 1 + 2 == 4:
print("1 + 2 == 4")
else:
print("1 + 2 != 4")
1 + 2 == 3
1 + 2 != 4
- if … elif … else
# if 后面的条件为真则执行,否则elif判断,都不为真执行else
if 1 + 2 == 4:
print("1 + 2 == 4")
elif 1 + 3 == 4:
print("1 + 3 == 4")
else:
print("~77~")
1 + 3 == 4
- and、or、not
# and 前后两个条件都为真是结果为真
# 表达式1 and 表达式2
# True and True # 结果为 True
# True and False # 结果为 False
# False and True # 结果为 False
# False and False # 结果为 False
if 1 == 1 and 1 == 2:
print("it's True")
if 1 == 1 and 2 == 2:
print("it's all True")
it's all True
# 表达式1 or 表达式2
# 两个表达式有一个为真,就为真
# True or True # 结果为 True
# True or False # 结果为 True
# False or True # 结果为 True
# False or False # 结果为 False
if 1 == 1 or 1 == 2:
print("it's True")
if 1 == 2 or 1 == 2:
print("it's all FALSE")
it's True
# not 表达式
# not True # 结果为 False
# not False # 结果为 True
if not (1 == 1):
print("it's true")
if not (1 == 2):
print("it's false")
it's false
循环语句
- while
# while 表达式:
# 循环体
# 只要表达式为真,就执行循环体
a = 4
while a > 0:
print("a = ",a)
a = a - 1
a = 4
a = 3
a = 2
a = 1
- for语句
cols = ['red', 'yellow', 'blue']
# 循环遍历列表
for col in cols:
print(col)
red
yellow
blue
- range() 函数
内置函数 range() 常用于遍历数字序列
for i in range(5):
print("i = ",i)
i = 0
i = 1
i = 2
i = 3
i = 4
- break、continue、else
# break 跳出循环
for i in range(5):
if i == 3:
break
print("i = ",i)
i = 0
i = 1
i = 2
# continue跳过本次循环,执行下一次
for i in range(5):
if i == 2:
continue
print("i = ",i)
i = 0
i = 1
i = 3
i = 4
# else for循环不满足执行else
for i in range(2,8):
for x in (2,i):
if i % x == 0:
print(i, 'equals', x, '*', i//x)
else:
print(i, 'is a prime number')
2 equals 2 * 1
2 equals 2 * 1
2 is a prime number
3 equals 3 * 1
3 is a prime number
4 equals 2 * 2
4 equals 4 * 1
4 is a prime number
5 equals 5 * 1
5 is a prime number
6 equals 2 * 3
6 equals 6 * 1
6 is a prime number
7 equals 7 * 1
7 is a prime number