语法
for ‘variable’ in ‘sequence’
…代码块 # . 为空格,缩进很重要
else:
…代码块
实例①:
>>> fruits = ['apple','banana','mango']
>>> for x in fruits:
print(x)
apple #输出
banana #输出
mango #输出
实例②:
sites = ["Baidu", "Google","IE","firefox"]
i=1 #i为循环的次数
for site in sites:
if site == "IE":
print("%s IE浏览器!"%i)
break #跳出当前循环
print("循环数据%s :"%i + site)
i += 1
else:
print("没有循环数据!")
print("完成循环!")
语法:
while 判断条件(condition):
执行语句(statements)……
实例①:
#利用while循环遍历1到100并求其和
n = 100
sum = 0
counter = 1
while counter <= n:
sum = sum + counter
counter += 1
print("1 到 %d 之和为: %d" % (n, sum))
#②通过设置条件表达式永远不为 false 来实现无限循环
var = 1
while var == 1: # 表达式永远为 true,一直执行该循环语句
num = int(input("输入一个数字 :"))
print("你输入的数字是: ", num)
print("Good bye!")
#重复打印循环语句,CTRL+C 来退出当前的无限循环
flag = 1
while (flag): print('循环语句!')
print("Good bye!")
语法:
while ‘expr’:
…# .代表空格缩进
else:
…# .代表空格缩进
实例①:
#while循环计数并比较大小
count = 0
while count < 3:
print (count, " 小于 3")
count = count + 1
else:
print (count, " 不小于 3")
列表推导式在逻辑上等价于一个循环语句,只是在形式上更加简洁
实例①:
>>> aList = [x*x for x in range(10)] # 列表推导式
>>> aList
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> bList = []
>>> bList = []
>>> for x in range(10): # for循环
bList.append(x*x)
>>> bList
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
实例②:
嵌套列表的平铺:
>>> v = [[1,2,3],[4,5,6],[7,8,9]]
>>> [num for elem in v for num in elem]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
外循环+内循环,结果同上:
>>> v = [[1,2,3],[4,5,6],[7,8,9]]
>>> result = []
>>> for elem in v:
for num in elem:
result.append(num)
>>> result
[1, 2, 3, 4, 5, 6, 7, 8, 9]