Python的流程控制
Python的流程控制:
-
判断
可以通过下图来简单了解条件语句的执行过程:
语法:
# 用法1 if 判断条件: 执行语句 else: 执行语句 # 用法2 if 判断条件1: 执行语句1 elif 判断条件2: 执行语句2 elif 判断条件3: 执行语句3 else: 执行语句4
实例:
# 方法一实例: >>> candition = bool(True) >>> if candition : ... print("Yes") ... else: ... print("No") ... Yes >>> candition = bool(False) >>> if candition : ... print("Yes") ... else: ... print("No") ... No # 方法二实例: >>> def judge(number): ... if number == 0 : ... print("zero") ... elif number == 1 : ... print("one") ... elif number == 2 : ... print("two") ... else : ... print("Error") ... >>> judge(0) zero >>> judge(1) one >>> judge(5) Error
-
循环
while循环
Python 编程中 while 语句用于循环执行程序,即在某条件下,循环执行某段程序,以处理需要重复处理的相同任务。
语法:
# 用法
while 判断条件: 执行语句
else:
执行语句
实例:
>>> n = 0 >>> while n <= 10 : ... print("number is %d: " %n) ... n += 1 ... else : ... print("while end in: %s" %n) ... number is 0: number is 1: number is 2: number is 3: number is 4: number is 5: number is 6: number is 7: number is 8: number is 9: number is 10: while end in: 11
for
Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串。
语法:
for 项目 in 集合: 执行语句 “项目”为遍历集合内的元素
实例:
# 实例1: >>> sequence_list = ["itme-1","item-2","item-3","itme-4"] >>> for item in sequence_list : ... print("Itme is: %s" %item) ... Itme is: itme-1 Itme is: item-2 Itme is: item-3 Itme is: itme-4 # 实例2: >>> sequence_str = "ABCD" >>> for item in sequence_str : ... print("Str is: %s" %item) ... Str is: A Str is: B Str is: C Str is: D >>>
# 实例3:
>>> for num in range(5):
... print("Number is: %d" %num )
...
Number is: 0
Number is: 1
Number is: 2
Number is: 3
Number is: 4
-
跳出循环
- break
- continue
* break跳出整个循环,而continue 语句是跳出本次循环。
break
break语句用来终止循环语句。break语句用在while和for循环中将停止执行最深层的循环,并开始执行下一行代码。
实例:
# 实例: >>> sequence_str = "ABCD" >>> for item in sequence_str : ... print("Itme is: %s" %item) ... if item == "C" : ... break ... Itme is: A Itme is: B Itme is: C
continue:
continue语句用在while和for循环中,用来告诉Python跳过当前循环的剩余语句,然后继续进行下一轮循环。
实例:
# 实例: >>> sequence_str = "ABCD" >>> for item in sequence_str : ... if item == "B": ... continue ... print("Itme is: %s" %item) ... Itme is: A Itme is: C Itme is: D