2016-06-22 493 views
-5

我试图使用一种替代方法来使while循环遍历列表而不是常见列表,但由于某种原因它不会工作。这里是我的代码:while while循环

lists = ["Lion","Tiger","Cheetah","Panther"] 
    while x <= len(lists): 
    print lists[x] 
    x += 1 
+0

正确缩进您的代码,并发布您正在获取的错误以及预期的输出。 – Blorgbeard

+0

它'行不通'是非常模糊的。你的意思是'不起作用'? – Li357

+0

顺便说一句,在Python中缩进是有意义的,你的代码将不能用于它的当前缩进。 – Blorgbeard

回答

1

你的循环是不正确的缩进,你永远X为0尝试初始化:

lists = ["Lion","Tiger","Cheetah","Panther"] 
x = 0 
while x < len(lists): 
    print lists[x] 
    x += 1 

另外,我觉得你通常会使用更多的东西一样

for animal in lists: 
    print animal 
+0

在原始代码中,它全部缩进,我只是无法在此缩进。 –

+0

这是我得到的错误:\ Traceback(最近调用最后一个): 文件“script.py”,第3行,在 while x <= len(lists): NameError:name'x'is not defined –

+1

@Prune作为附注,由于列表的零索引,为避免出现IndexError:列表索引超出范围,您将要使用while x davedwards