所有编程语言在编写时都要遵循语言结构和流程控制,它们控制了整个程序运行的步骤。流程控制包括顺序控制、条件控制和循环控制。所谓控制顺序,就是按照正常的代码执行顺序,从上到下、从文件头到文件尾依次指定每条语句。
1. if判断
1.1 if语句
1.1.1 if语法
语法:
if 表达式:
语句1(4个空格)
语句2
x = True
if x:
print("It's True") # It's True
1.1.2 条件是数字
x = 18
if x:
print("x is: ", x) # x is: 18
# 只有数字为0时是False
x = 0
if x:
print("x is not zero")
1.1.3 条件是字符串
x = "Hello"
if x:
print("x is: ", x) # x is: Hello
# 只有字符串为空时是False
x = ""
if x:
print("x is: ", x)
1.1.4 条件是列表、元组、字典
列表、元组、字典类型的数据,当他们不包含任何元素时,条件测试结果是 “False”;含有任意元素时,条件测试结果是 “True”
x1 = []
x2 = [1, 2]
if x1:
print("x1")
if x2:
print("x2") # x2
x3 = ()
x4 = (1, 2)
if x3:
print("x3")
if x4:
print("x4") # x4
x5 = {}
x6 = {"Hello": "World"}
if x5:
print("x5")
if x6:
print("x6") # x6
1.2 else语句
x = 0
if x:
print("x is not zero")
else:
print("x is zero")
# x is zero
1.3 elif语句
有的时候可能需要多个条件,这时可以使用 elif
x = 89
if x > 90:
print("优")
elif x > 80:
print("良")
elif x > 60:
print("及格")
# 良
x = 49
if x > 90:
print("优")
elif x > 80:
print("良")
elif x > 60:
print("及格")
else:
print("不及格")
# 不及格
2. 循环
Python中主要有两种循环结构:while循环和for循环
2.1 while循环
语法:
while 语法:
while 表达式:
语句1
语句2
x = 1
while x <= 10:
print(x)
x += 1
# 1
# 2
# 3
# ...
# 10
2.2 for循环
2.2.1 语法
for 语法:
for 变量 in 序列:
语句1
语句2
for x in (1, 2, 3, 4, 5, 6, 7, 8, 9, 10):
print(x)
# 1
# 2
# 3
# ...
# 10
2.2.2 range
rang 函数作为迭代条件
for x in range(10):
print(x)
# 1
# 2
# 3
# ...
# 9
rang 定义开始和结尾:不包含结尾
for x in range(1, 10):
print(x)
# 1
# 2
# 3
# ...
# 9
range 定义步长
for x in range(1, 10, 2):
print(x)
# 1
# 3
# 5
# 7
# 9
2.3 break和continue
break 的作用是立即退出循环
for i in range(10):
if i > 5:
break
print(i)
# 0
# 1
# 2
# 3
# 4
# 5
continue 作用是跳过当前循环体,执行下次循环
for i in range(10):
if i == 5:
continue
print(i)
# 0
# 1
# 2
# 3
# 4
# 6
# 7
# 8
# 9
3. pass语句
在Python中的pass语句是空语句,其作用是保持结构的完整性。pass不做任何操作,一般用作占位语句
for i in range(10):
if i == 3:
pass
else:
print(i)
# 0
# 1
# 2
# 3
# 4
# 6
# 7
# 8
# 9
x = 35
if x == 35:
# TODO
pass
else:
print("x 不是 35")
4. 循环中的else
在Python中,不只if可以和else组合,while和for也可以和else组合出现
4.1 while+else
count = 0
while count < 5:
print(count, " is less than 5")
count = count + 1
else:
print(count, " is not less than 5")
# 0 is less than 5
# 1 is less than 5
# 2 is less than 5
# 3 is less than 5
# 4 is less than 5
# 5 is not less than 5
4.2 while+else+break
如果中途break退出while循环,不会执行else后的代码块
count = 0
while count < 5:
print(count, " is less than 5")
if count == 3:
break
count = count + 1
else:
print(count, "is not less than 5")
# 0 is less than 5
# 1 is less than 5
# 2 is less than 5
# 3 is less than 5
4.3 for+else
for count in range(5):
print(count, " in for segment")
else:
print(count, " in else segment")
# 0 in for segment
# 1 in for segment
# 2 in for segment
# 3 in for segment
# 4 in for segment
# 4 in else segment
4.4 for+else+break
如果中途break退出for循环,不会执行else后的代码块
for count in range(5):
print(count, " in for segment")
if count == 3:
break
else:
print(count, " in else segment")
# 0 in for segment
# 1 in for segment
# 2 in for segment
# 3 in for segment