Skip to content
Advertisement

Loop keeps running code inside even when condition is false

import datetime
from pydub.playback import play
currentDate = datetime.datetime.now()
times = [12, 19, 23] 
minutes = [53, 52, 51]
while True:
        for i in times:
            for j in minutes:
                if(currentDate.hour == i and currentDate.minute == j):
                    # print(os.getcwd())
                    index = minutes.index(j)+1;
                    print(index)
                    announce = AudioSegment.from_mp3(
                        f'{os.getcwd()}\audios\announcement_{index}.mp3')
                    play(announce)

This code keeps on playing “announce” even when the condition inside the if block is untrue can anyone please tell me what’s the wrong logic i am applying in here.. any kind of help would be really helpful

“Times And Minutes both are lists”

Advertisement

Answer

So the issue is that you are not updating the CurrentDate variable. This results in an infinite loop if you are running the program when the condition is True.

So to solve that, you just have to update that variable :

times = [12, 19, 23] 
minutes = [53, 52, 51]
while True:
    # Updating the date every frame
    currentDate = datetime.datetime.now()
            for i in times:
                for j in minutes:
                    if(currentDate.hour == i and currentDate.minute == j):
                        # print(os.getcwd())
                        index = minutes.index(j)+1;
                        print(index)
                    announce = AudioSegment.from_mp3(
                        f'{os.getcwd()}\audios\announcement_{index}.mp3')
                    play(announce)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement