三.python条件循环
1.if语句
1.1.简介
- if语句可以实现条件执行,如果条件判定为真,则后面的语句块执行,如果条件为假,语句块就不会被执行。
1.2.语法
1.2.1.单重条件判断(单分支)
1 >>> a = 1 2 >>> if a==1: 3 ... print("True") 4 ... 5 True 6 >>>
1.2.2.多重条件判断(单分支)
1 >>> a = 1 2 >>> b = 2 3 >>> 4 >>> if a==1 and b==2: 5 ... print("True") 6 ... 7 True 8 >>>
1.2.3.多分支条件判断(if...else...)
1 >>> a = 1 2 >>> if a==1: 3 ... print("True") 4 ... else: 5 ... print("False") 6 ... 7 True 8 >>>
1.2.4.多分支条件判断(if....elif....else)
1 >>> a = 10 2 >>> if a > 10: 3 ... print("a > 10") 4 ... elif a == 10: 5 ... print("a == 10") 6 ... else: 7 ... print("a < 10") 8 ... 9 a == 10 10 >>>
2.for语句
2.1.简介
- for是循环可以遍历任何序列的,如列表,元组,字典,字符串,主要作用是迭代。(迭代:每次操作都基于上一次的结果)
2.2.语法
2.2.1.通过序列索引迭代
#列表迭代 >>> a = [1,2,3,4,5,6] >>> for i in a: ... print(i) ... 1 2 3 4 5 6 >>> #字典迭代 >>> Info = {'name':'All is well','age':23} >>> for k,v in Info.items(): ... print(k,v) ... age 23 name All is well #序列索引迭代 >>> a [1, 2, 3, 4, 5, 6] >>> a = [1, 2, 3, 4, 5, 6] >>> for i in range(len(a)): ... print("index %s is %s"%(i,a[i])) ... index 0 is 1 index 1 is 2 index 2 is 3 index 3 is 4 index 4 is 5 index 5 is 6 #enumerate >>> for i,j in enumerate(a): ... print("index %s is %s"%(i,a[i])) ... index 0 is 1 index 1 is 2 index 2 is 3 index 3 is 4 index 4 is 5 index 5 is 6 >>>
2.2.2.break,continue
#break(跳出本层循环) >>> a = [1,2,3,4,5,6] >>> for num in a: ... print(num) ... if num == 3: ... break ... 1 2 3 >>> #continue(跳出本次循环) >>> for num in a: ... if num == 3: ... continue ... print(num) ... 1 2 4 5 6
2.2.3.使用else语句
#在大多数语言中条件循环是没有else的,但在python中是个例外。 #else语句只会在循环完成后执行,因刚刚说的break是跳出循环,break跳出并没有执行完成,所以break语句会跳过else块的内容 #例:break跳出不会执行else >>> a = [1, 2, 3, 4, 5, 6] >>> for num in a: ... print(num) ... if num == 3: ... break ... else: ... print("end...........") ... 1 2 3 >>> #例:正常循环结束会执行else >>> a = [1, 2, 3, 4, 5, 6] >>> for num in a: ... print(num) ... else: ... print("end...........") ... 1 2 3 4 5 6 end........... #例:continue数据正常结束,也会执行else >>> a = [1, 2, 3, 4, 5, 6] >>> for num in a: ... if num == 3: ... continue ... print(num) ... else: ... print("end............") ... 1 2 4 5 6 end............
3.while语句
3.1.简介
- Python 编程中 while 语句用于循环执行程序,即在某条件下,循环执行某段程序。(条件:根据特定的条件循环)
3.2.语法
3.2.1 计数循环
1 >>> n = 0 2 >>> while n < 10: 3 ... print('n is %s' %n) 4 ... n+=1 5 ... 6 n is 0 7 n is 1 8 n is 2 9 n is 3 10 n is 4 11 n is 5 12 n is 6 13 n is 7 14 n is 8 15 n is 9 16 >>>
3.2.2 无限循环
1 >>> import time 2 >>> 3 >>> n = 0 4 >>> 5 >>> while True: 6 ... print('n is %s' %n) 7 ... time.sleep(1) 8 ... n+=1 9 ... 10 n is 0 11 n is 1 12 n is 2 13 n is 3 14 n is 4 15 n is 5 16 n is 6 17 n is 7 18 n is 8 19 n is 9
3.2.3 continue,break,else
- 与for语句的用法相同,原理相同。