tags:

views:

113

answers:

8

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 Annoying!

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?

+2  A: 

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
watain
sorry I was doing that - I had that in my script forgot to copy it over, I fixed the pasted code. Still same problem...
Nascent_Notes
You're only doing `i + 1`? I guess you still need to assign the new value, like `i = i + 1` :)
watain
yeah was only doing i + 1, I see why that was not working now.Also, I was told I could do print i+1, line, but that didn't work either.... what am I doing wrong or does that not work?
Nascent_Notes
+3  A: 

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

mothis
+7  A: 

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.

sth
+4  A: 

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!
John Feminella
+10  A: 

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.

balpha
+1 for the Pythonic approach.
FogleBird
+2  A: 

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.

Adam Crossland
+4  A: 

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
Paul McGuire
A: 

Just step through debugger to see the execution.

Kugel