2
\$\begingroup\$

Report time at whole hours

#!/usr/bin/python3
import time
from datetime import datetime
from pydub import AudioSegment
from pydub.playback import play

bell_sound = AudioSegment.from_wav("/home/me/Music/audio/bell.wav")

while True:
    now = datetime.now()
    # repeats = 1 if now.hour % 3 == 0 else now.hour % 3
    repeats = now.hour % 3 + 1

    if now.hour < 6:
        break
    # report on whole hour
    if now.minute == 0:
        for _ in range(repeats):  # bell the hours
            play(bell_sound)
        time.sleep(60 * 58)  # save the computation
    if now.minute != 0:
        time.sleep(10)
    # quit 23 later
    if now.hour == 23:
        break

Any ideas to improve it?

\$\endgroup\$
0
\$\begingroup\$

I would have the now.minute != 0 as an else since the if above is the exact opposite case.

I would also assign a 'sleep_time' value inside both branches and call the sleep function after the if - else to emphasize that sleep is always done.

I also don't like while True since it means I have to search the code for the exit condition. I would have the now = datetime.now() line twice, one before the while and once at the end of the block and make the condition while now.hour != 23:. This is personal, some people are more against the duplicated line than the while True:.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.