How to run loop only once in python?

Viewed 581

I'm new to python and coding in general, I have developed a small program that checks for double booking in google calendar. My problem is if I chose to check the 26 June, it will check for the 26 AND for the 27.

I think it's because I did a for i in range(1) (So it loops twice, (0,1))

How do i change it to make it run only once ?

here is the code :

        for i in range(1):

            startStrip = datetime.datetime.strptime(event_start, "%Y-%m-%dT%H:%M:%S")
            endStrip = datetime.datetime.strptime(event_end, "%Y-%m-%dT%H:%M:%S")
            dayOfWeek = startStrip + datetime.timedelta(days=i)
            # les bons formats
            currentStart = str(startStrip + datetime.timedelta(days=i)).replace(" ", "T")
            currentEnd = str(endStrip + datetime.timedelta(days=i)).replace(" ", "T")
            calendarEnd = str(endStrip + datetime.timedelta(days=i + 1)).replace(" ", "T")

            events_result = service.events().list(calendarId='primary', timeMin=currentStart + "-00:00",
                                                  maxResults=30, timeMax=calendarEnd + "-00:00",
                                                  singleEvents=True, orderBy='startTime').execute()
            events = events_result.get('items', [])

            currentEmployees = []
            for event in events:
                currentEmployees.append(event['summary'])

            #for i in range(1):
            #event_done = False
            if employee in currentEmployees:
                event_done = False
                event['summary'] = employee
                #if employee not in currentEmployees:
                    #event_done = True
                #else:
                for event in events:
                   # if employee == event['summary']:
                   if str2datetime(currentStart) <= str2datetime(event['end']['dateTime'].split('+')[0]) and str2datetime(currentEnd) >= str2datetime(event['start']['dateTime'].split('+')[0]):
                    event_done = False
                    print(employee + ' est occupé')
                    break
                   else:
                      event_done = True
                      break

            if employee not in currentEmployees:
                event_done = True

            if event_done:
                option = show_message_box(QMessageBox.Critical,
                                      "Confirmation",
                                      "Voulez-vous bloquer cette plage horraire?"\
                                      "L'employé : \"" + employee + "\" sera marqué comme indisponible en raison de : " + reason, \
                                      "Nom de l'employé: " + employee + "\n" \
                                      "Raison: " + reason + "\n" \
                                      "À partir du : " + currentStart + "\n" \
                                      "À ce jour " + currentEnd + "\n"
                                      )

                if option == QMessageBox.Yes:
                    event_done = True
                else:
                    print("Événement ignoré!")
                    event_done = False
                    break

                if event_done:
                    event = {
                        'summary': employee,
                        'location': location,
                        'description': reason,
                        'start': {
                            'dateTime': currentStart,
                            'timeZone': 'America/New_York',
                        },
                        'end': {
                            'dateTime': currentEnd,
                            'timeZone': 'America/New_York',
                        #},
                        #'attendees': [
                         #   {'email': event_email},
                        #],
                        #'reminders': {
                         #   'useDefault': True,
                        },
                    }
                    register_event(service, event)

            else:
                second_message_box(QMessageBox.Critical,
                                      "ATTENTION!",
                                      "L'inspecteur " + employee + " est déjà occupé à ce moment-là.""\n" \
                                      "Veuillez essayer une autre plage horraire.", QMessageBox.Ok)
2 Answers

Your first loop is fine , it will iterate only once I don't know your requirement logic but what I can see is your calander_end you are making it with +1 which is besically taking one date ahead I guess you have to check and rectify according to your requirement

Firstly, the range() function calls values up to the 'stop' input, meaning you don't get 0 and 1, you only get 0 for i, secondly, if you are only going to go through the code once, you don't need the loop at all? If you don't want to erase it though, you can put a 'break' at the end of the loop block, which would cut the loop from running again

Related