Python基础之流程控制
本节将介绍Python中的流程控制,包括顺序,判断,循环。
几乎任何编程语言都有三种程序执行流程,顺序,判断和循环。概念都是一样,唯一不同的只是语法。关于三种流程的概念这里不做太多介绍,记住语法即可。
顺序
顺序是最简单的一种流程,程序从上到下按行依次执行,例如:
a = 1
print(a)
b = a + 1
print(b)
print("Hello world!")
运行结果:
D:\work\python_workspace\python_study\venv\Scripts\python.exe D:/work/python_workspace/python_study/basic_05/01.py
1
2
Hello world!
Process finished with exit code 0
判断
相关的关键字:if, elif, else。
相关的运算符:
- 比较运算符>, >=, <, <=, ==, !=
- 逻辑运算符:and, or, not
注意:Python中没有switch,无法像其它语言如Java等,可以用switch来代替多个if-elif。
示例:
name = 'xiaoming'
age = 20
sex = 'M'
if age < 20:
print('Age is less than 20.')
elif age == 20:
print('Age is 20.')
else:
print('Age is great than 20.')
if age >= 20 and sex == 'M':
print("Age >= 20 and sex is 'M'")
if name != 'xiaoming':
print('Name is not xiaoming.')
else:
print('Name is xiaoming.')
运行结果:
D:\work\python_workspace\python_study\venv\Scripts\python.exe D:/work/python_workspace/python_study/basic_05/02.py
Age is 20.
Age >= 20 and sex is 'M'
Name is xiaoming.
Process finished with exit code 0
循环
Python中有两种循环,while,for。for循环一般用于对容器(list,tuple,dict)元素的遍历,while循环则用于for以外的其它循环。while和for都支持 break 和 continue,break用于跳出当前整个循环体,continue用于跳过当前循环变量,执行下一次循环。
while循环示例:
index = 0
num = 10
while index <= num:
index += 1
if index == 3:
continue
if index == 6:
break
print(index * 2)
运行结果:
D:\work\python_workspace\python_study\venv\Scripts\python.exe D:/work/python_workspace/python_study/basic_05/while.py
2
4
8
10
Process finished with exit code 0
需要注意的是不能忘记对循环变量index的累加,否则可能会出现死循环。
for循环示例:
l = [i ** 2 for i in range(10)]
print(l)
for i in l:
if i == 49:
print("i is 49, then break.")
break
if i == 4:
print("i is 4, then continue")
continue
print(i)
运行结果:
D:\work\python_workspace\python_study\venv\Scripts\python.exe D:/work/python_workspace/python_study/basic_05/for.py
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
0
1
i is 4, then continue
9
16
25
36
i is 49, then break.
Process finished with exit code 0
对for和while循环,可以配合使用else关键字,当循环不是因为break退出时执行else中的语句。很多人会问为什么Python中会有如此语法,其它语言中似乎不存在这个用法。不管怎样,Python既然设计了这个语法,肯定有一定的道理,有一种场景使用的比较多,那就是判断一个容器中是否存在某个元素。例如:
l = [i ** 2 for i in range(10)]
print(l)
def check_num(num):
for i in l:
if i == num:
print("%d is in list." % num)
break
else:
print("%d is not in list." % num)
def check_num2(num):
index = 0
while index < len(l):
if l[index] == num:
print("%d is in list." % num)
break
index += 1
else:
print("%d is not in list." % num)
check_num(9)
check_num(19)
check_num2(9)
check_num2(19)
运行结果:
D:\work\python_workspace\python_study\venv\Scripts\python.exe D:/work/python_workspace/python_study/basic_05/for-while-else.py
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
9 is in list.
19 is not in list.
9 is in list.
19 is not in list.
Process finished with exit code 0
如果不使用else,那么在函数内部就需要定义一个额外的局部变量来标识是否找到指定元素。