MishraS
MishraS

Reputation: 77

Line printing in Python

This exercise is from chapter 20 of Zed Shaw's book.

I am trying to understand a behavior of line number.

When I use the following code, the line number from the text file gets printed as 4, which is wrong. It is in the 3rd line.

current_line += current_line

However, the line number shows correct when I use the following

current_line = current_line + 1

Can someone kindly explain what is the difference in the above two lines, which looks same to me and why it is making a difference.

Following is the full code:

from sys import argv
script, input_file = argv

def print_all(f):
    print f.read()

def rewind(f):
    f.seek(0)

def print_a_line(line_count, f):
    print line_count, f.readline()

current_file = open(input_file)

print "First let's print the whole file:\n"

print_all(current_file)

print "Now let's rewind, kind of like a tape."

rewind(current_file)

print "Let's print three lines:"

current_line = 1
print_a_line(current_line, current_file)

current_line += current_line
print_a_line(current_line, current_file)

#current_line = current_line + 1
current_line += current_line
print_a_line(current_line, current_file)

Upvotes: 3

Views: 137

Answers (2)

ospahiu
ospahiu

Reputation: 3525

You're not increasing the value of of current_line by a constant factor of 1, instead you're increasing by a geometric progression.

current_line += current_line assigns the value of current_line to be itself + itself:

current_line = 5
current_line = current_line + current_line
>>> current_line
>>> 10

current_line = current_line + 1 or current_line += 1 (+=1 is syntactic sugar for increasing a value by 1) increases the value of current_line by 1.

current_line = 5
current_line = current_line + 1
current_line += 1
>>> current_line
>>> 7

Since current_line is a counter for the line number, += 1 should be used in this case.

Upvotes: 0

Taztingo
Taztingo

Reputation: 1945

current_line += current_line expands out to

current_line = current_line + current_line

So lets take a look at what you did, by expanding it out (We will ignore the print statements).

current_line = 1
current_line = current_line + current_line # (1 + 1 = 2)
#current_line = 2
current_line = current_line + current_line # (2 + 2 = 4)
#current_line = 4

I think you meant to use

current_line += 1

Upvotes: 2

Related Questions