我一直在努力学习"以艰难的方式学习Python",到目前为止它已经很顺利,但我有几个问题:
the_count = [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 the_count:
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
Run Code Online (Sandbox Code Playgroud)
在这些for循环中,"数字","水果"和"我"这两个词的含义是否重要?感觉python中的所有内容都需要定义,但如果有意义,我们从未真正"定义"数字.我不确定如何正确地说出这个问题= /
不,你用这些名字并不重要.您可以为这些标识符选择任何名称,只要它们是有效的python标识符即可.
它们命名foo,bar,vladiwostok,等等.这是一个好主意,选择一个名字就是有点更具描述性的,当然,所以fruit还是number在上下文伟大的名字,他们正在使用.
在任何情况下,以下所有内容都是等效的:
for foo in fruits:
print "A fruit of type: %s" % foo
for bar in fruits:
print "A fruit of type: %s" % bar
for vladivostok in fruits:
print "A fruit of type: %s" % vladivostok
Run Code Online (Sandbox Code Playgroud)