《 笨方法学 Python 》_ 习题 32 - 34

习题 32:循环和列表
the_coount = [1, 2, 3, 4]
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 the_coount:
    print("This is count %d" % number)
    
# same as above
for fruit in fruits:
    print("A fruit of types: %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)


常见问题回答:

为什么 for 循环可以使用未定义的变量?

循环开始时这个变量就被定义了,当然每次循环它都会被重新定义一次。

range() 函数可创建一个整数列表,一般用在 for 循环中,会从第一个数到最后一个数,但不包含最后一个数。

append() 函数在列表尾部添加元素。


习题 33while 循环
i = 0
numbers = []

while i < 6:
    print("At the top i is %d" % i)
    numbers.append(i)
    
    i = i + 1
    print("Numbers now:", numbers)
    print("At the bottom i is %d" % i)
    
print("The numbers:")

for num in numbers:
    print(num)

附加练习:

使用 for 循环和 range 把这个脚本再写一遍。

numbers = []

for i in range(6):
    print("At the top i is %d" % i)
    numbers.append(i)
    
    print("Numbers now:", numbers)
    print("At the bottom i is %d" % i)
习题 34:访问列表的元素
animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']

for i in range(len(animals)):
    print(animals[i])

Python 列表从 0 开始。

猜你喜欢

转载自blog.csdn.net/yz19930510/article/details/80552165