索引,字符串,列表

时间:2013-05-30 03:39:39

标签: jython

浏览水果列表并在字符串“我将其添加到我们的产品中”中打印每个水果。参数是“作物名称(字符串)列表,没有返回值。

测试用例

crops = [‘apple’, ‘orange’, ‘banana’, ‘strawberry’]
daysWork(crops)

I added this apple to our produce
I added this orange to our produce
I added this banana to our produce
I added this strawberry to our produce

我的代码:

def daysWork(crops):
  for crop in crops:
    produce = crops[n]
  print 'I added this ' + str(produce) + ' to our produce'

我得到的错误是“错误是:n全局未找到名称。”

是否n没有为每个元素编制索引?

1 个答案:

答案 0 :(得分:1)

Python的for loop 语句实际上是for-each语句,which differs from what you're used to in C or Java. for crop in crops使用变量crops引用crop中的每个元素。

你想要的是:

for crop in crops:
    produce = crop