如有意见或其他问题可在下方写下评论或加QQ:1693121186
欢迎一起讨论技术问题!
# -*- coding: utf-8 -*-
the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
#第一类for循环遍历了一个列表(this first kind of for-loop goes through a list)
for number in the_count:
print "This is count %d" % number
# aove一样(same as aove)
for fruit in fruits:
print "A fruit of type: %s" % fruit
# 我们也可以通过混合列表(also we can go through mixed lists too)
# 注意,我们必须使用%r因为我们不知道里面有什么(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 = []
#然后使用范围函数执行0到5项(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
习题重点
- 怎样创建列表:先用创建变量的方式写个变量名与单等号,单等号右边的便是重点了——以[开头,里面输入你要循环的值,切记!值后要有逗号!并且要输入的不是数字,要加单引号。最后以]来结束。
- 怎样在代码中使用for循环:具体的形式便是这样的:for + 现创的变量名 + in +之前所创的有列表的变量名
- range()函数的功能:因为这是附加练习,我在这说明一下:range()函数会从第一个数到最后一个数,但不包含最后一个数。像这样“range(0, 6)”它就不会有6
- elements.append()的功能: 它的功能是在列表的尾部追加元素,我不懂,所以大家自己去探寻吧!
就这样了,再见!
切记:本文谨作提示,切勿复制代码!