XYZ
XYZ

Reputation: 162

Strange behavior for loop in python

I am writing this code to read a text file and then print the line number after each line here is my code

with open("newfile.txt") as f:
 for line in f:
  x=1
  y=str(x)
  print(line)
  print(x)
  x=x+1
f.close()

I should expect some thing like that

Line one

1

Line two

2

Line three

3

but instead I am getting

Line one

1

Line two

1

Line three

1

Why is that !?

Upvotes: 0

Views: 85

Answers (4)

Snowman
Snowman

Reputation: 110

The issue with the code would be the x=1 inside of the loop. By moving that outside and initializing that before you should get the result you want. For example:

 x=1
 with open("newfile.txt") as f:
 for line in f:
 y=str(x)
 print(line)
 print(x)
 x=x+1

This should work

Upvotes: 0

Marcellinov
Marcellinov

Reputation: 301

The problem is that you are initializing x to 1 inside the loop and before the print statement.

try:

x = 1
with open("newfile.txt") as f:    
  for line in f:
    y = str(x)
    print(line)
    print(x)
    x += 1 

Upvotes: 1

BioGeek
BioGeek

Reputation: 22827

Adding comments to your code will help you see why you always print out 1.

with open("newfile.txt") as f:
  for line in f:
   x=1            # x is now equal to 1
   y=str(x)       # x is still 1, y is now equal to '1'
   print(line)    # prints out the line
   print(x)       # 1 is printed
   x=x+1          # you now add 1 to x, but don't do anything with this 
                  # updated value, because in the next loop x is again
                  # initialised to 1
 f.close()

Upvotes: 1

Kasravnd
Kasravnd

Reputation: 107287

You can just use enumerate() :

with open("newfile.txt") as f:
 for num,line in enumerate(f,1):
      print line,'\n',num

Also note that you don't need to close the file when you use the with statement. It will automatically does it for you.

And about the x variable in your code, you shouldn't initialized it in your loop, you need to put x=1 out of the loop.

Upvotes: 3

Related Questions