Search code examples
pythonif-statementalarmpython-webbrowser

Very basic alarm clock does not open webbrowser


I'm totally new to programming. Wanted to write this basic alarm clock with Python but the webbrowser just doesn't open. I think it is probably my if statement that doesn't work. Is that correct?

from datetime import datetime
import webbrowser

name = raw_input("What's your name?")
print ("Hello %s! Let me set an alarm for you. Please answer the following questions about when you want to wake up.")%(name)
alarm_h = raw_input("--> Please enter the hour when I should wake you up:")
alarm_m = raw_input("--> Please enter the exact minute of the hour:")
alarm_sound = raw_input("--> Please enter the Youtube-URL of your favorite song:")

now = datetime.today()

print ("It's now %s h : %s m. We'll wake you up at %s h : %s m." %(now.hour,   now.minute, alarm_h, alarm_m))

if now.hour == alarm_h and now.minute == alarm_m:
    webbrowser.open(alarm_sound, new=2)   

Solution

  • Your current code looks like it is checking the current time against the set alarm time. However, you currently have just one check, but you need to either loop and continuously compare the current time with the set alarm time or use another method of continuously checking.

    The webbrowser line does work. Its not executing because the current time never reaches the alarm time (since you are not continuously comparing the current time with the set alarm time).

    Try:

    from datetime import datetime
    import webbrowser
    
    name = raw_input("What's your name?")
    print ("Hello %s! Let me set an alarm for you. Please answer the following questions about when you want to wake up.")%(name)
    alarm_h = raw_input("--> Please enter the hour when I should wake you up:")
    alarm_m = raw_input("--> Please enter the exact minute of the hour:")
    alarm_sound = raw_input("--> Please enter the Youtube-URL of your favorite song:")
    
    now = datetime.today()
    
    print ("It's now %s h : %s m. We'll wake you up at %s h : %s m." %(now.hour, now.minute, alarm_h, alarm_m))
    
    webbrowser.open(alarm_sound, new=2) #Added temporarily to test webbrowser functionality
    
    if str(now.hour) == alarm_h and str(now.minute) == alarm_m: #Converted integer type to string type to match datatype of alarm_h and alarm_m
        webbrowser.open(alarm_sound, new=2)
    

    This should open the webbrowser so you can test its functionality.

    I also converted now.hour and now.minute to type string to match the datatypes of alarm_h and alarm_m. They were both integers and which can't be directly compared to a string datatype.

    Definitely look into looping or threads for continuously updating the current time and checking if it equals the current thread.