for statement
The Python for loop can traverse any sequence of items, such as a list or a string.
The general format of the for loop is as follows:
for <variable> in <sequence>: <statements> else: <statements>
Example 1: Simple for statement
#!/usr/bin/python3
#-*- coding: utf-8 -*-
lauguages = ["c","java","asp","python"]
for i in lauguages:
print(i)
Example 2: for...else
#!/usr/bin/python3
#-*- coding: utf-8 -*-
lauguages = ["c","java","asp","python"]
for i in lauguages:
print(i)
if i == "python":
print("终于找到java")
break
print("继续循环" +i)
else:
print("没有循环数据")
print("循环完成")
Example 3: range() function
If you need to traverse a sequence of numbers, you can use the built-in range() function. It will generate a sequence of numbers, for example:
#!/usr/bin/python3
#-*- coding: utf-8 -*-
for i in range(100):
i=i+1
print(i)
#!/usr/bin/python3
#-*- coding: utf-8 -*-
language = ["c","java","asp","python"]
for i in language:
print(i)
for c in range(len(language)):
print(c,language[c])
#使用range指定区间的值:
for d in range(10,15):
print(d)
#使range以指定数字开始并指定不同的增量(甚至可以是负数,有时这也叫做'步长'):
for d in range(10,20,2):
print("开始",d)