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.
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. (for posterity 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)
If you have any other questions or comments please let me know.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.