【问题标题】:Printing dynamic lines in Python with "for line in file"使用“for line in file”在 Python 中打印动态行
【发布时间】:2017-11-15 02:06:28
【问题描述】:

我正在编写一个程序,用户可以在其中输入开始年份和结束年份,该程序将打印出图书奖获奖者之间所有年份的信息。这是我目前所拥有的:

ui = input("Enter a beginning year('q' or 'Q' to quit): ")
ui2 = input("Enter an ending year: ")
file = open("bookListFile.txt", "r")



def getBook(user, user2):
    yearsBetween = int(ui2) - int(ui)
    yearCount = 0
    for line in file:
        while user in line and user.isdigit() and yearCount < yearsBetween:
            print(line)
            yearCount += 1



    getBook(ui, ui2)

这里的问题是当我打印该行时,它会一遍又一遍地打印同一行。例如,当我输入 1985 作为开始年份和 2000 作为结束年份时,它将打印同一行 15 次而不是中间的年份。

我可以在这里寻求帮助吗?如果可能的话,你能解释一下你是怎么做到的吗?

【问题讨论】:

  • 请发布您的文件,或它的sn-p,以及程序输出。 :) 从表面上看,看起来你可能有点搞砸了你的循环和变量声明,试着用伪代码和你的测试用例的期望值来评论每一行,如果你把它发回去,那么我们就会知道错误之间的区别语法或错误的期望

标签: python function file loops for-loop


【解决方案1】:

看起来 while 循环正在被赶上,据我所见,我认为 range 函数会更好地服务这个程序。 (留给后人Python’s range() Function Explained

def get_book(user, user2):
    year_range = range(user, user2)
    #Instead of manually counting up through the numbers a list is automatically 
    #created through range of the numbers. Starting at user, ending at user2 and auto 
    # stepping up by 1.
    for line in file:
        for i in year_range:
            #Instead of using a while loop and a manual count the for loop auto 
            #counts through the range
            if str(i) in line:
                print(line)

如果您有任何其他问题或 cmets,请告诉我。

【讨论】:

    猜你喜欢
    • 2016-10-02
    • 1970-01-01
    • 2015-10-16
    • 2014-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    • 2011-01-08
    相关资源
    最近更新 更多