How do I create an alarm with nested alarms from 2 arrays

28 Views Asked by At

I am trying to create a code in python that plays an alarm based on times from two separate arrays.

Timer 1 would play 1 beep and timer 2 would play 2 beeps. The times are not exclusive and everything needs to be based on one main time.

import time
import datetime
import winsound

def sound_alarms(timer_1, timer_2):
    
    alarm = 0
    
    for i in timer_1 and timer_2:
        
        while alarm <= i:
            
            break_timer = datetime.timedelta(seconds = alarm)
            
            print(break_timer, end="\r")
            
            time.sleep(1)
            
            alarm += 1

            if  alarm == i in timer_1:
                winsound.Beep(234, 1500)
            
            if alarm == i in timer_2:
                winsound.Beep(234, 500)
                winsound.Beep(234, 500)


timer_1 = [10 , 20 , 30]
timer_2 = [15, 25, 35]
sound_alarms(timer_1, timer_2)
1

There are 1 best solutions below

0
Nicholas Waslander On

The problem is in the for loop - it's creating confusing behaviour. You can actually take it out entirely with a couple modifications. This code worked when I was testing it:

import time
import datetime
import winsound

def sound_alarms(timer_1, timer_2):
    
    alarm = 0
    maximum_value = max(timer_1+timer_2)
        
    while alarm <= maximum_value:
        
        break_timer = datetime.timedelta(seconds = alarm)
        
        print(break_timer, end="\r")
        
        time.sleep(1)
         
        alarm += 1

        if alarm in timer_1:
            winsound.Beep(234, 1500)
            
        if alarm in timer_2:
            winsound.Beep(234, 500)
            winsound.Beep(234, 500)


timer_1 = [10 , 20 , 30]
timer_2 = [15, 25, 35]
sound_alarms(timer_1, timer_2)

What I've done is found the maximum value to count up to, and had it simply check every second if the current time was in either list.