ex32 for循环

这是一个关于for循环的简单练习

the_count = [1,2,3,4,5]
fruits = ['apples','oranges','pears','bananas']
change = [1,'pennies',2,'dimes',3,'quarters']

#for循环输出
for number in the_count:
    print("The number is %d." %number)
for fruit in fruits:
    print("Do you like %s?" %fruit)
#如果输出列表的包含多种格式,使用%r
for i in change:              #i在这里指的是列表change里面的所有元素
    print("I got %r." %i)

#创建一个空列表,使用range和append将列表元素添加到空列表中去
elements = []                 #空列表
for i in range(0,6):
    print("Adding %d to the list." %i)
    elements.append(i)        #添加0-6的元素到elements中,注意元素顺序是包头不包尾

for i in elements:            #经过append之后,elements现在是[0,1,2,3,4,5]
    print("Elements is %d." %i)

运行结果

PS E:\tonyc\Documents\Vs workspace> cd ‘e:\tonyc\Documents\Vs workspace’; ${env:PYTHONIOENCODING}=‘UTF-8’; ${env:PYTHONUNBUFFERED}=‘1’; & ‘D:\Anboot\Python\python.exe’ ‘c:\Users\tonyc.vscode\extensions\ms-python.python-2019.3.6558\pythonFiles\ptvsd_launcher.py’ ‘–default’ ‘–client’ ‘–host’ ‘localhost’ ‘–port’ ‘58107’ ‘e:\tonyc\Documents\Vs workspace\The Hard Way\ex32(for循
环).py’
The number is 1.
The number is 2.
The number is 3.
The number is 4.
The number is 5.
Do you like apples?
Do you like oranges?
Do you like pears?
Do you like bananas?
I got 1.
I got ‘pennies’.
I got 2.
I got ‘dimes’.
I got 3.
I got ‘quarters’.
Adding 0 to the list.
Adding 1 to the list.
Adding 2 to the list.
Adding 3 to the list.
Adding 4 to the list.
Adding 5 to the list.
Elements is 0.
Elements is 1.
Elements is 2.
Elements is 3.
Elements is 4.
Elements is 5.

思考

  1. range的用法
    range可以对一个列表进行从头到尾的迭代,具体使用格式是range(start:stop,[step]),步长为可选选项
  2. 可以可以直接将 elements 赋值为 range(0,6),而无需使用 for 循
    环,也即
elements = []                 #空列表
for i in range(0,6):

可以写成

elements = range(0,6)                 #空列表
for i in elements: