简体   繁体   English

使用“ for file in file”在Python中打印动态行

[英]Printing dynamic lines in Python with “for line in file”

I'm writing a program where a user can enter a beginning year and an end year, and the program will print out the winners of a book award for all the years in between. 我正在编写一个程序,用户可以输入起始年和结束年,并且该程序将打印出这两年之间所有图书奖的获奖者。 Here is what I have so far: 这是我到目前为止的内容:

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)

The problem here is when I print the line, it prints the same line over and over. 这里的问题是当我打印行时,它一遍又一遍地打印同一行。 For example, when I enter 1985 as the beginning year and 2000 as the end year, it will print the same line 15 times instead of the years in between. 例如,当我输入1985年作为开始年份,输入2000年作为结束年份时,它将打印同一行15次而不是两次之间的年份。

Can I get some help here? 我可以在这里得到帮助吗? If possible, could you explain how you did it too? 如果可能的话,您能解释一下您是如何做到的吗?

It looks like the while loop is getting caught up and from what I see I think this program would be better served by the range function. 看起来while循环陷入了困境,从我的看来,我认为使用range函数可以更好地为该程序提供服务。 (for posterity Python's range() Function Explained ) (对于后代Python的range()函数解释

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)

If you have any other questions or comments please let me know. 如果您还有其他问题或意见,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM