Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 767
MishraS Avatar asked Mar 07 '26 02:03

MishraS


1 Answers

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
like image 163
Taztingo Avatar answered Mar 09 '26 16:03

Taztingo