艰苦学习python练习20

艰苦学习python练习20,python,Python,我不明白“line_count”的值在哪里传递给这个变量。如果你能解释给我听,我会非常感激的!!输出打印每个连续行。我理解它是如何增加行号(1、2、3、4)的,但它如何真正知道从哪里获取数据来打印每个字符串,这让我感到困惑 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

我不明白“line_count”的值在哪里传递给这个变量。如果你能解释给我听,我会非常感激的!!输出打印每个连续行。我理解它是如何增加行号(1、2、3、4)的,但它如何真正知道从哪里获取数据来打印每个字符串,这让我感到困惑

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 + 1
print_a_line(current_line, current_file)

current_line = current_line + 1
print_a_line(current_line, current_file)

行计数
是函数的一个参数;它通过调用函数时调用方传递参数来获取其值。在这种情况下,参数是
当前\u行
全局变量的值。

倒带后,文件指针回到文件的开头。 每次调用
f.readline()
都将从
f
读取一行。 在此之后,
f
的文件指针将位于下一行的开头。
因此,程序会连续读取这些行。

如果您查看这段代码:

current_line = 1
print_a_line(current_line, current_file)

您可以看到,当前_行被传递给print_a_行函数,变量定义在函数调用的正上方。在函数“打印行”中,“行计数”指的是当前行的值。

您定义了此函数:

def print_a_line(line_count, f):
    print line_count, f.readline()
在这些行中称之为:

current_line = current_line + 1
print_a_line(current_line, current_file)

全局变量
current\u line
的值作为第一个参数传递给函数
print\u line
,它绑定到局部变量
current\u line

我希望您了解函数如何工作的概念

如果你不这样做,请在“艰苦学习”中重新阅读该部分

但是,您应该知道,在创建这样的函数时:

def print_a_line(line_count, f):
    print line_count, f.readline()
您可以看到,有两个参数或也称为参数的参数被传递给函数,以逗号分隔。在函数中,它们被打印出来

因此,当在此处使用该函数时:

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

    # the variable current_line is passed into the function, in that first parameter 
    # as a result, 1 is printed

current_line = current_line + 1 # here the variable is assigned its own value + 1
    print_a_line(current_line, current_file)

    # now it will print 2 and that new value in the variable is passed into the function

current_line = current_line + 1
    print_a_line(current_line, current_file)
您需要了解,即使函数位于文档的顶部,您也可以调用它,或者稍后使用它并传递用于执行函数所执行的打印操作的值

(答案只是打印出你在哪一行(应该是在哪一行),但它实际上只是硬编码的,所以在我看来有点草率)

我对此有一些问题,所以看看这个函数,我似乎觉得行数是您想要读取的行,但事实上,这个函数实际上只打印您硬编码的行,然后调用f.readline(),它在调用时一次读取每一行

我想如果我把print_称为line(line_count,f)

例如,print_a_line(6,current_file)会给我当前_file的第6行,但实际上它会随着调用f的次数而变化。readline()似乎每次调用它时,该函数中都有一个计数器,它会计算调用了多少次

因此,如果您调用了f.readline()两次,那么下一步应该在第3行

如果使用f.seek(0)并在之后将其倒带,则当调用f.readline()时,它会返回到第1行。并取决于有多少f.readline()将读取哪一行


希望这对其他人有所帮助,因为我试图添加到此文件,询问用户您要写入哪一行,然后调用此函数打印出该行。。。这并没有做到,所以我想我可以做的一个方法是做一个for循环来调用f.read(),不管我从用户输入中得到了什么,然后打印出那一行。。。。但是您需要检查文件中的行数,并确保用户输入的行数少于总行数

啊哈!这很好地回答了我的问题。非常感谢。@user2512132:我回答了我认为是你的问题。但是,你没有直接问。很难猜出你真正的问题是什么。正如你所看到的,我的答案与其他答案有很大的不同(正因为如此)。