John Rogerson
John Rogerson

Reputation: 1183

Python Nested Loop Problems With Validation

I'm creating a work log where a user can input a task or lookup a task by dates.

When looking up task by date, the user is presented with a list of dates. The user can then select from the list by entering a number. The list of tasks should then display for that specific date.

I'm just having a problem if the user enters a number not in the list of dates. You can see else statement at the end of method which is commented out---which had been causing a few issues. Everything works fine otherwise. So question--how do i provide error message if input from user is not in index list without printing out the message every time it loops through the list?

def search_by_date(self):
    for i, d in enumerate(self.tasklist.dates()):
        enum_list = [(i+1,d) for i,d in enumerate(self.tasklist.dates())]
        print(i+1, ':', d)
    while True:
        datereq = input("Select Number To See Tasks For A Date: ").strip()
        try:
            datereq = int(datereq)

        except ValueError:
            print("Invalid Entry")
            continue

        else:
            for i, d in enum_list:
                for task in self.tasklist.task_list:
                    if datereq == i:
                        if task.date == d:
                            print("Date :", task.date,
                                  " Task:", task.task,
                                  " Minutes:", task.minutes,
                                  " Notes: ", task.notes
                                  )
                            continue

                    #else:
                        #print("Invalid Entry. Please try again")
                        #continue

Upvotes: 1

Views: 371

Answers (1)

Julien
Julien

Reputation: 5729

Is this what you're looking for?

def search_by_date(self):
    for i, d in enumerate(self.tasklist.dates()):
        enum_list = [(i+1,d) for i,d in enumerate(self.tasklist.dates())]
        print(i+1, ':', d)
    while True:
        datereq = input("Select Number To See Tasks For A Date: ").strip()
        try:
            datereq = int(datereq)

        except ValueError:
            print("Invalid Entry")
            continue

        else:
            found = False
            for i, d in enum_list:
                for task in self.tasklist.task_list:
                    if datereq == i and task.date == d:
                        found = True
                        print("Date :", task.date,
                              " Task:", task.task,
                              " Minutes:", task.minutes,
                              " Notes: ", task.notes
                              )
            if not found:
                print("Invalid Entry. Please try again")

Upvotes: 2

Related Questions