Python Forum
repeated statements when using for and if
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
repeated statements when using for and if
#3
The standard way to handle this is to break when you find the book, and then have an else statement on the for loop:

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
Reply


Messages In This Thread
RE: repeated statements when using for and if - by ichabod801 - Mar-29-2019, 03:29 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020