for 循环
theCount = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
# this first kind of for-loop goes through a list
for number in theCount:
print("This is count %d" % number)
# same as above
for fruit in fruits:
print("A fruit of type:%s" % fruit)
# also we can go through mixed lists too
# notice we have to use %r since we don't know what's in it
for i in change:
print("I got %r" % i)
# we can also build lists,first start with an empty one
elements = []
# then use the range function to do 0 to 5 counts
for i in range(0, 6):
print("Adding %d to the list." % i)
# append is a function that lists understand
elements.append(i)
# now we can print them out too
for i in elements:
print("Element was:%d" % i)
start: 计数从 start 开始。默认是从 0 开始。例如range(5)等价于range(0, 5);
stop: 计数到 stop 结束,但不包括 stop。例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5
step:步长,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1)
range 用法
>>>range(10) # 从 0 开始到 10
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11) # 从 1 开始到 11
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5) # 步长为 5
[0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3) # 步长为 3
[0, 3, 6, 9]
>>> range(0, -10, -1) # 负数
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range(0)
[]
>>> range(1, 0)
[]
打印runoob 的每个字符
注意字符也可以当做是列表
x = 'runoob'
for i in range(len(x)):
print(x[i])
elements = []
# then use the range function to do 0 to 5 counts
for i in range(0, 6):
print("Adding %d to the list." % i)
# append is a function that lists understand
elements.append(i)
# now we can print them out too
for i in elements:
print("Element was:%d" % i)