标签:常见 color edit bin 输入 列表 break odi 循环
控制流分为顺序,分支,循环。
我们平时写的从上到下就是顺序结构,这个最常见。
当if后的条件为真时,执行if语句
当if的条件不为真时,执行else语句
if语句为真,执行if语句,之后的语句不执行。if语句不为真,看elif语句是否为真,为真执行;不为真看下一个elif。都不为真执行else语句。
1 #!/usr/bin/python3 2 # -*- coding: utf-8 -*- 3 # @Time :2018/11/26 13:58 4 # @Author :yosef 5 # @Email :wurz529@foxmail.com 6 # @File: :class7.py 7 # @Software :PyCharm Community Edition 8 number = 23 9 guees = int(input("请输入一个整数:")) 10 if number == guees: 11 print("恭喜你猜对啦") 12 elif number > guees: 13 print("抱歉,猜小了") 14 else: 15 print("抱歉,猜大了")
循环条件为真时,会执行循环条件下的语句。否则结束循环
for循环可以用来遍历字符串,元组,列表,字典的key,value。
1 #!/usr/bin/python3 2 # -*- coding: utf-8 -*- 3 # @Time :2018/11/26 14:11 4 # @Author :yosef 5 # @Email :wurz529@foxmail.com 6 # @File: :class8.py 7 # @Software :PyCharm Community Edition 8 str1 = "python is the best" 9 list1 = [1, 1.36, ‘a‘, ‘python‘, (1,), [1, 2], {‘age‘: 18}] 10 tuple1 = (1, 1.36, ‘a‘, ‘python‘, (1,), [1, 2], {‘age‘: 18}) 11 dict1 = {"Name": "yosef", 12 "Sex": "man", 13 "Age": 22, 14 "City": "Shanghai"} 15 for a in str1: 16 print(a, end=" ") 17 print("\n") 18 for b in list1: 19 print(b, end=" ") 20 print("\n") 21 for c in tuple1: 22 print(c, end=" ") 23 print("\n") 24 for d in dict1.values(): 25 print(d, end=" ") 26 print("\n") 27 for e in dict1.keys(): 28 print(e, end=" ") 29 print("\n")
运行结果:
range函数的结果是序列
range(m,n,k) 在[m,n)中,步长为k的整数序列
range(m,n) 在[m,n)中,步长为1的整数序列
range(m) 在[0,m)中,步长为1的整数序列
1 #!/usr/bin/python3 2 # -*- coding: utf-8 -*- 3 # @Time :2018/11/26 14:48 4 # @Author :yosef 5 # @Email :wurz529@foxmail.com 6 # @File: :class9.py 7 # @Software :PyCharm Community Edition 8 for a in range(2, 8, 2): 9 print(a, end=" ") 10 print("\n") 11 for i in range(1,9): 12 print(i, end=" ") 13 print("\n") 14 for j in range(10): 15 print(j, end=" ")
结果:
1 list1 = [1, 1.36, ‘a‘, ‘python‘, (1,), [1, 2], {‘age‘: 18}] 2 for item in range(len(list1)): 3 print(list1[item], end=" ")
结果:
1 list1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 2 for i in range(len(list1)): 3 for j in range(len(list1[i])): 4 print(list1[i][j], end=" ")
while循环当条件为真时,会执行代码,为假时退出代码循环。
break可以打破循环。常用于循环语句,强制循环停止,然后退出循环。
continue强制停止循环中此次执行,跳到下一次执行。
1 #!/usr/bin/python3 2 # -*- coding: utf-8 -*- 3 # @Time :2018/11/26 15:20 4 # @Author :yosef 5 # @Email :wurz529@foxmail.com 6 # @File: :class11.py 7 # @Software :PyCharm Community Edition 8 number = 56 9 while True: 10 guees = int(input("请输入一个整数:")) 11 if number == guees: 12 print("恭喜你猜对啦") 13 break 14 elif number > guees: 15 print("抱歉,猜小了") 16 continue 17 else: 18 print("抱歉,猜大了") 19 continue
break就是直接跳出该层循环
continue就是直接进入该层循环的下一次迭代.
标签:常见 color edit bin 输入 列表 break odi 循环
原文地址:https://www.cnblogs.com/wlyhy/p/10020589.html