04 流程控制

1.1 顺序结构

1.1.1 if分支结构

1
2
3
4
5
6
7
8
9
10
11
12
def order_1():
a = int(input("请输入一个整数:"))
if a > 0:
print("大于零")
elif a == 0:
print("等于零")
else:
print("小于零")


if __name__ == '__main__':
order_1()
1
2
请输入一个整数:1
大于零

当下面的值作为if语句的条件时,或被当做False处理:

False,None,0,””,(),[],{}

1.1.2 断言

用于对一个bool表达式进行断言,如果该表达式为True,程序可以继续执行;如果为False,程序会引发AssertionError错误

1
2
3
4
5
6
7
def order_1():
a = int(input("请输入一个在20(包含)到80(不包含)之间的整数:"))
# 断言,如果不符合条件则报AssertionError错误
assert 80 > a >= 20

if __name__ == '__main__':
order_1()
1
2
3
4
5
6
7
请输入一个在20(包含)到80(不包含)之间的整数:10
Traceback (most recent call last):
File "List_Tuple_Dict.py", line 8, in <module>
dict_1()
File "List_Tuple_Dict.py", line 4, in dict_1
assert 80 > a >= 20
AssertionError

1.2 循环结构

1.2.1 while循环

1
2
3
4
5
6
7
8
9
def cycle_1():
a = 10
while a > 0:
print(a, end=" ")
a -= 1


if __name__ == '__main__':
cycle_1()
1
10 9 8 7 6 5 4 3 2 1 

1.2.2 for-in循环

遍历列表(元组)

1
2
3
4
5
6
7
8
def cycle_1():
a = list(range(1, 10))
for i in a:
print(i, end=" ")


if __name__ == '__main__':
cycle_1()
1
1 2 3 4 5 6 7 8 9 

遍历字典

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def cycle_1():
dict_1 = {'语文': 89, '数学': 90, '英语': 100}
for key, value in dict_1.items():
print(key, value)

for key in dict_1.keys():
print(key)

for value in dict_1.values():
print(value)


if __name__ == '__main__':
cycle_1()
1
2
3
4
5
6
7
8
9
语文 89
数学 90
英语 100
语文
数学
英语
89
90
100

1.2.3 循环使用else

Python的循环都可以定义else代码块(其他编程语言通常不支持)

为while循环定义else:

1
2
3
4
5
6
7
8
9
10
11
def cycle_1():
a = 10
while a > 0:
print(a, end=" ")
a -= 1
else:
print(-1)


if __name__ == '__main__':
cycle_1()
1
10 9 8 7 6 5 4 3 2 1 -1

为for循环定义else:

1
2
3
4
5
6
7
8
9
10
def cycle_1():
a = list(range(1, 10))
for i in a:
print(i, end=" ")
else:
print(-1)


if __name__ == '__main__':
cycle_1()
1
1 2 3 4 5 6 7 8 9 -1

1.2.4 for表达式

用于利用其他可迭代对象(列表,元组等)创建新的列表.

1
2
3
4
5
6
7
8
9
10
11
12
13
def cycle_1():
a = list(range(10))
print(a)
# 将a中的所有元素扩大两倍,生成新的列表list_a
list_a = [i * 2 for i in a]
# 可以在后面加上if条件
list_b = [i * 2 for i in a if i % 2 != 0]
print(list_a)
print(list_b)


if __name__ == '__main__':
cycle_1()
1
2
3
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
[2, 6, 10, 14, 18]

for表达式最终返回的是列表,所以for表达式也被称为列表推导式

评论

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×