python循环
loop
for in
#!/usr/bin/python3
sites = ["Baidu", "Google","Runoob","Taobao"]
for site in sites:
if site == "Runoob":
print("菜鸟教程!")
break
print("循环数据 " + site)
else:
print("没有循环数据!")
print("完成循环!")
range() function
>>>for i in range(5):
... print(i)
...
0
1
2
3
4
>>>for i in range(5,9) :
print(i)
5
6
7
8
>>>
>>>for i in range(0, 10, 3) :
print(i)
0
3
6
9
>>>
>>>for i in range(-10, -100, -30) :
print(i)
-10
-40
-70
>>>
组合循环
>>>a = ['Google', 'Baidu', 'Runoob', 'Taobao', 'QQ']
>>> for i in range(len(a)):
... print(i, a[i])
...
0 Google
1 Baidu
2 Runoob
3 Taobao
4 QQ
>>>
List Comprehension
List comprehensions are one of Python's most beloved and unique features. The easiest way to understand them is probably to just look at a few examples:
squares = [n**2 for n in range(10)]
squares
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Here's how we would do the same thing without a list comprehension:
squares = []
for n in range(10):
squares.append(n**2)
squares
We can also add an if
condition:
short_planets = [planet for planet in planets if len(planet) < 6]
short_planets
['Venus', 'Earth', 'Mars']