现在你应该有能力写更有趣的程序出来了。如果你能一直跟得上,你应该已经看出将“if 语句”和“布尔表达式”结合起来可以让程序作出一些智能化的事情。

    然而,我们的程序还需要能很快地完成重复的事情。这节习题中我们将使用 for-loop (for 循环)来创建和打印出各种各样的列表。在做的过程中,你会逐渐明白它们是怎么回事。现在我不会告诉你,你需要自己找到答案。

    在你开始使用 for 循环之前,你需要在某个位置存放循环的结果。最好的方法是使用列表(list),顾名思义,它就是一个按顺序存放东西的容器。列表并不复杂,你只是要学习一点新的语法。首先我们看看如何创建列表:

hairs = ['brown', 'blond', 'red']
eyes = ['brown', 'blue', 'green']
weights = [1, 2, 3, 4]

    你要做的是以 [ (左方括号)开头“打开”列表,然后写下你要放入列表的东西,用逗号隔开,就跟函数的参数一样,最后你需要用 ] (右方括号)结束右方括号的定义。然后 Python 接收这个列表以及里边所有的内容,将其赋给一个变量。

Warning

    对于不会编程的人来说这是一个难点。习惯性思维告诉你的大脑大地是平的。记得上一个练习中的 if 语句嵌套吧,你可能觉得要理解它有些难度,因为生活中一般人不会去像这样的问题,但这样的问题在编程中几乎到处都是。你会看到一个函数调用另外一个包含 if 语句的函数,其中又有嵌套列表的列表。如果你看到这样的东西一时无法弄懂,就用纸币记下来,手动分割下去,直到弄懂为止。

    现在我们将使用循环创建一些列表,然后将它们打印出来。

 1 the_count = [1, 2, 3, 4, 5]
 2 fruits = ['apples', 'oranges', 'pears', 'apricots']
 3 change = [1, 'pennies', 2, 'dimes', 3, 'quarters']
 4 
 5 # this first kind of for-loop goes through a list
 6 for number in the_count:
 7     print "This is count %d" % number
 8 
 9 # same as above
10 for fruit in fruits:
11     print "A fruit of type: %s" % fruit
12 
13 # also we can go through mixed lists too
14 # notice we have to use %r since we don't know what's in it
15 for i in change:
16     print "I got %r" % i
17 
18 # we can also build lists, first start with an empty one
19 elements = []
20 
21 # then use the range function to do 0 to 5 counts
22 for i in range(0, 6):
23     print "Adding %d to the list." % i
24     # append is a function that lists understand
25     elements.append(i)
26 
27 # now we can print them out too
28 for i in elements:
29     print "Element was: %d" % i
View Code

相关文章:

  • 2022-12-23
  • 2021-04-15
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-12-29
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案