开发者

Iteration WAS working in my script, now I cant get python to iterate - what happened?

Did my python ide break or something?

import sys

i = 0
sample = ("this", "is", "Annoying!")

for line in sample:
    print i, line
    i + 1

Now gives me...

0 this 
0 is 
0 Annoyin开发者_如何学JAVAg!

I THOUGHT, it would give me:

1 this 
2 is 
3 Annoying

I had other scripts that I was working on and it they all just broke - they all have the same line number when they print numerous iterations using the for statement - can someone PLEASE tell me what the heck is going on - very frustrated lol... did Python break? Do I need sleep? What is wrong here?


While the other answers are correct, this is how you usually do this in python:

sample = ("this", "is", "Annoying!")

for i, line in enumerate(sample):
    print i, line

The enumerate function does exactly what you want: Iterating through your tuple, while at the same time giving you (line) numbers.


You are calculating i+1 but are not storing the result of that anywhere. Specifically you are not updating i to contain the new value. Use i = i + 1 or i += 1 instead.


This works just fine for me:

>>> import sys
>>> i = 0
>>> sample = ("abc", "def", "ghi")
>>> for line in sample:
...   i = i + 1
...   print i, line
... 
1 abc
2 def
3 ghi

Are you sure you're incrementing and storing the value i? (Your sample omits this, but in another answer you say you did put i = i + 1.) Remember, Python is whitespace-sensitive, so if you did something like this, the result won't be what you expect:

>>> for line in sample:
...   print i, line
... i = i + 1 # <-- This is not part of the loop!


I suspect you have an indentation problem, that perhaps the i = i + 1 statement is somehow not part of the for-loop.

But Instead of doing your own counter incrementing, better practice is to use enumerate:

for i,line in enumerate(sample):
    print i,line


The problem is you're doing "i + 1", not "i=i+1"


You're not incrementing the variable i in your code, you'd need to do something like:

for line in sample:
    i = i + 1
    print i, line


The result that you expect would be obtained by using enumerate:

sample = ("this", "is", "Annoying!")
for index, line in enumerate(sample):
    print index, line

I don't see how the code that you posted ever would have worked in any version of Python.


Just step through debugger to see the execution.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜