Python 同样提供了现代编程语言都支持的两种基本流程控制结构,分支结构和循环结构:
Python 使用 if 语句提供分支支持,提供了 while、 for-in 循环,也提供了 break 和 continue 控制程序的循环结构。
if 判断语句:
[root@kube control]# cat demo.py #coding:utf-8 s_age = input(‘you age number:‘) age = int(s_age) if age > 20: # : 分号表示一个代码块的开始,代码块必须有内容否则报错 print(‘you age > 20,you know‘) #缩进是标识python 代码块的非常重要的东西,不能随意缩进 [root@kube control]# py demo.py you age number:22 you age > 20,you know [root@kube control]# py demo.py you age number:11 [root@kube control]#
if else 判断语句:
[root@kube control]# cat demo.py #coding:utf-8 s_age = input(‘you age number:‘) age = int(s_age) if age > 20: print(‘you age > 20,you know‘) else: # else也要用 : 起始 print(‘you age <20 ,you know‘) [root@kube control]# py demo.py you age number:22 you age > 20,you know [root@kube control]# py demo.py you age number:11 you age <20 ,you know [root@kube control]#
从前面的示例可以看到,Python 执行 if 语句时,会判断 if 表达式的值是 True 还是 False 。那么是不是只能使用 bool 类型的表达式呢?
不是。表达式可以是任意类型,当下面的值作为 bool 表达式时,会被解释器当作 False 处理:
False、None、0、""、()、[]、{}
从上面介绍可以看出,除了 False 本身,各种代表“空”的 None、空字符串、空元组、空列表、空字典都会被当成 False 处理。
[root@kube control]# cat demo1.py a = ‘‘ if a : print(‘a is not none string‘) else: print(‘a is none string‘) b = {} if b : print(‘b is not none string‘) else: print(‘b is none string‘) [root@kube control]# py demo1.py a is none string b is none string [root@kube control]#
if 语句嵌套:
[root@kube control]# cat demo2.py #coding:utf-8 num = int(input(‘you test score:‘)) if num > 80: print(‘you Good!!!‘) else: if 60 < num < 80 : #if 语句嵌套最重要的就是缩进,确认每个代码块的分界 print(‘you Bad!!!!‘) else: print(‘you so bad!!!‘) [root@kube control]# py demo2.py you test score:88 you Good!!! [root@kube control]# py demo2.py you test score:78 you Bad!!!! [root@kube control]# py demo2.py you test score:56 you so bad!!! [root@kube control]#
很多程序都提供了“空语句”支持,Python 也不例外,Python 的 pass 语句就是空语句。
有时候程序需要占一个位、放一条语句,但又不希望这条语句做任何事情,此时就可通过 pass 语句来实现。通过使用 pass 语句,可以让程序更完整。
如下程序示范了 pass 作为空语句的用法:
[root@kube control]# cat demo3.py #coding:utf-8 num = int(input(‘you test score:‘)) if num > 80 : pass else: print(‘you so bad‘) [root@kube control]# py demo3.py you test score:88 [root@kube control]# py demo3.py you test score:55 you so bad [root@kube control]#
assert 断言语句和 if 分支有点类似,它用于对一个 bool 表达式进行断言,如果该 bool 表达式为 True,该程序可以继续向下执行;否则程序会引发 AssertionError 错误。
有读者可能会问,明明 assert 会令程序崩溃,为什么还要使用它呢?这是因为,与其让程序在晚些时候崩溃,不如在错误条件出现时,就直接让程序崩溃。通常,assert 语句用在检查函数参数的属性(是参数是否是按照设想的要求传入),或者作为初期测试和调试过程中的辅助工具。
[root@kube control]# cat demo4.py #coding:utf-8 s_age = int(input(‘you age num:‘)) assert 20 < s_age < 80 #assert 的作用就是出现不符合预期的情况就中断程序的执行 print(‘you age is range 20 - 80‘) [root@kube control]# py demo4.py you age num:56 you age is range 20 - 80 [root@kube control]# py demo4.py you age num:11 Traceback (most recent call last): File "demo4.py", line 5, in <module> assert 20 < s_age < 80 AssertionError [root@kube control]#
[root@kube control]# cat demo5.py #coding:utf-8 #price 为原价,discount 为折扣力度 def apply_discount(price, discount): #定义一个价格和折扣力度的函数 updated_price = price * (1 - discount) #计算折扣后的价格 assert 0 <= updated_price <= price #assert 判断是否在合理区间,合理就就继续执行,返回折扣价格,不合理就assert 退出 #‘折扣价应在 0 和原价之间‘ return updated_price print(apply_discount(100,0.2)) print(apply_discount(100,1.1)) [root@kube control]# py demo5.py 80.0 Traceback (most recent call last): File "demo5.py", line 11, in <module> File "demo5.py", line 7, in apply_discount AssertionError [root@kube control]#
Python中for循环和while循环本质上是没有区别的,但是在实际应用上,针对性不太一样。
while循环适用于未知循环次数的循环,for循环适用于已知循环次数的循环 。
while 语句执行的具体流程为:首先判断条件表达式的值,其值为真(True)时,则执行代码块中的语句,当执行完毕后,再回过头来重新判断条件表达式的值是否为真,若仍为真,则继续重新执行代码块...如此循环,直到条件表达式的值为假(False),才终止循环。
[root@kube control]# cat demo6.py #coding:utf-8 # while cycle test num = 1 while num < 10: #while 循环要注意循环体的结束,不能无限循环了,给定结束循环的条件,都用: 号开始代码块 print(num) num += 1 print(‘while cycle end!‘) [root@kube control]# py demo6.py 1 2 3 4 5 6 7 8 9 while cycle end! [root@kube control]#
[root@kube control]# cat demo6.py #coding:utf-8 # while cycle test num = 1 while num < 10: print(num,‘\t‘,end=‘|‘) #换一个输出方法 num += 1 print(‘while cycle end!‘) [root@kube control]# py demo6.py 1 |2 |3 |4 |5 |6 |7 |8 |9 |while cycle end! [root@kube control]#
由于列表和元组的元素都是有索引的,因此程序可通过 while 循环、列表或元组的索引来遍历列表和元组中的所有元素。
[root@kube control]# cat demo7.py #coding:utf-8 a_tuple = (‘tom‘,‘jojo‘,‘zela‘,‘bob‘) #定义一个元组 i = 0 #定义 i = 0 ,是因为通过索引来获取元素是从0 开始的 print(len(a_tuple)) #长度为4 while i < len(a_tuple) : #获取长度是从1 开始,那么索引0 对应第一个值,索引比len 小1 print(a_tuple[i]) i += 1 print(‘while cycle end!‘) [root@kube control]# py demo7.py 4 tom jojo zela bob while cycle end! [root@kube control]#
[root@kube control]# cat demo8.py #coding:utf-8 #使用了pop() 函数和 append 的函数将匹配的元素添加到新的列表中 src_list = [12, 45, 34,13, 100, 24, 56, 74, 109] a_list = [] # 定义保存整除3的元素 b_list = [] # 定义保存除以3余1的元素 c_list = [] # 定义保存除以3余2的元素 # 只要src_list还有元素,继续执行循环体 while len(src_list) > 0: # 弹出src_list最后一个元素 ele = src_list.pop() # 如果ele % 2不等于0 if ele % 3 == 0 : a_list.append(ele) # 添加元素 elif ele % 3 == 1: b_list.append(ele) # 添加元素 else: c_list.append(ele) # 添加元素 print(" %3:", a_list) print(" %3 - 1:",b_list) print(" %3 - 2:",c_list) [root@kube control]# py demo8.py %3: [24, 45, 12] %3 - 1: [109, 100, 13, 34] %3 - 2: [74, 56] [root@kube control]#
原文:https://www.cnblogs.com/zy09/p/11624890.html