2016-06-22 192 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