Mar-29-2019, 03:29 PM
(This post was last modified: Mar-29-2019, 03:29 PM by ichabod801.)
The standard way to handle this is to break when you find the book, and then have an else statement on the for loop:
If you haven't covered else statements for loops yet, the old fashioned way to do this is with a flag (a boolean variable):
for i in range(len(book_name)): if book_issue_years [i] > = interval_start and book_issue_years [i] <= interval_end: print (book_name [i], book_issue_years [i]) break else: print ("no books in that interval")The else statement on a loop triggers if the loop exits without a break. So in this case it only triggers if the book was not found.
If you haven't covered else statements for loops yet, the old fashioned way to do this is with a flag (a boolean variable):
found = False for i in range(len(book_name)): if book_issue_years [i] > = interval_start and book_issue_years [i] <= interval_end: print (book_name [i], book_issue_years [i]) found = True if not found: print ("no books in that interval")Note that it is better to loop directly over the list, rather than the indexes of the list. It makes your code cleaner and less prone to errors. In this case, you have two lists you are trying to track, so you would zip them together. The zip function takes two or more lists, and returns tuples of items from those lists in order (a tuple of the first item from each list, a tuple of the second items, and so on):
for book, issue_year in zip(boo_name, book_issue_years): if issue_year > = interval_start and issue_year <= interval_end: print (book, issue_years) break else: print ("no books in that interval")
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures