r/learnpython • • Jul 18 '20

after 2 ish weeks of learning python I've made an Alarm clock

ive made a very basic alarm clock could you guys asses it?

import time, winsound




def main():
    global maininp
    maininp = input("Hours mins or sec").lower()
    timelist = ("hours","mins" ,"sec")
    if maininp in timelist:
        times(maininp)
    else:
        print("try again")
        main()


def times(userinp):
    if userinp == "hours":
        timewanted = int(input("how many hour: "))
        waitingtime= (timewanted*60)*60
        alarm(waitingtime)

    elif userinp == "mins":
        timewanted = int(input("how many mins: "))
        waitingtime= timewanted*60
        alarm(waitingtime)

    elif userinp == "sec":
        timewanted = int(input("how many sec: "))
        waitingtime= timewanted
        alarm(timewanted)


def alarm(thetime):
    if maininp == "hours":
        s = str((thetime/60)/60)
        items = s.split(".")
        if thetime ==1:
            print(f"Your alarm is set for {int((thetime/60)/60)} Hour")
            time.sleep(thetime)
            sound()
        elif thetime != 1:
            print(f"Your alarm is set for {int((thetime/60)/60)} Hours")
            time.sleep(thetime)
            sound()

    elif maininp == "mins":
        test = float((thetime / 60))
        twodp = float("{:.2f}".format(test))
        s = str(twodp)
        items = s.split(".")
        if test >60:
            print(f"Your alarm is set for {items[0]} Hours and {items[1]} mins")
            time.sleep(thetime)
            sound()

        else:
            print(f"Your alarm is set for {int(thetime/60)} mins")
            time.sleep(thetime)
            sound()


    elif maininp == "sec":
        print(f"Your alarm is set for {thetime} seconds")
        time.sleep(thetime)
        sound()



def sound():
    for i in range(2):
        for j in range (3):
            winsound.MessageBeep(-1)
            time.sleep(0.3)
        time.sleep(1)


main()
401 Upvotes

65 comments sorted by

195

u/TechnologyStreet Jul 18 '20

Bro you're two weeks into python and you're already using main()? I've been learning 3 years and I still don't know why i should use main() or __init__ or self or any of that other jazz.

I'm not really one who has a right to critique your code (it looks great to me), but I just wanted to say you're on your way to being a wizard

24

u/Haymzer Jul 18 '20

Main is just the name of the entire function. He could have done

def myalarm() :

All of his other code

myalarm()

6

u/mo_10 Jul 18 '20

yeah this is right ahaha

1

u/WebNChill Jul 18 '20

I also look at it like main contains all the main logic for the program.

You build out the other parts, and then build the logic that runs the code in main. Which in turn contains logic for other parts of the code.

1

u/r-_-mark Jul 19 '20

It’s better to name the function something more meaningful after that add another main() that the program start from and call all the chains of func you want

7

u/mo_10 Jul 18 '20

bro im no where near good yet ahah but you should keep on going you got this man

54

u/[deleted] Jul 18 '20 edited Jul 18 '20

After using python for a year I have seen that many people have this issue. main() is used because it helps people who learned to code on Java or C run code, its how its done on C but its not required on Python. __init__ is a user defined class constructor:

class shape(object):

  def __init__(self, sides, name, area):

        self.sides = sides

        self.name = name

        self.area = area

  def getName(self):
        return self.name

`

The __init__ allows you to create a shape object by saying Shape_Square = Shape(4, 16, 'Square') Note when 'self' is used it is referencing the object passed in. Like if I said getName(Shape_Square) the 'self' will reference "Shape_Square" which is a shape object and return self.name or in other words Shape_Square.name

0

u/[deleted] Jul 18 '20

[deleted]

16

u/blahreport Jul 18 '20

That is not the case. ”__main__” is the __name__ of the Python process. No function needs to be called main for your program to be exportable or executable.

1

u/__nickerbocker__ Jul 19 '20

I went back to using it because it's real easy to forget that everything under the import guard is in the global namespace. I had a situation where I wrote a bug in one of my functions and a variable was referenced before assignment but everything kind of worked and the linter didn't complain because I accidentally shadowed the variable like 200 lines down the page under the import guard in the global namespace. Do you have to use a main? No. Should you use a main? IMO, fuck yes.

1

u/blahreport Jul 19 '20

I think you may have missed the point of my comment. I’m not commenting on whether you should or should not use a “main” import guard in your script. That of course depends on the intended function of the script. Rather I just made the point that no function needs to be called “main” to ensure any kind of Python functionality.

1

u/__nickerbocker__ Jul 19 '20

My bad... that wasn't really directed at you, rather, a general word of warning to the public at large. I should have been more explicit.

1

u/blahreport Jul 19 '20

How pythonic of you!

0

u/TangibleLight Jul 18 '20

It is still better IMO to put the "main" logic of your program in its own function. All I would usually put in the if __name__ == '__main__' block is a call to argparse, maybe some simple validation, and then a call to a main function or whatever else might be the entrypoint to my program. I think it's best to keep that block small.

1

u/blahreport Jul 19 '20

Perhaps but that is unrelated to my comment.

1

u/TangibleLight Jul 19 '20

It's possible to simply include the logic of your script directly in the body of the if block. This seems to be what you're advocating. I argue that although it's not required, it's still better practice to create a main function for such scripts.

1

u/blahreport Jul 19 '20

Reread my comment and the person I was replying to, and that should clear things up for you.

1

u/TangibleLight Jul 19 '20

Here's how I interpreted the thread:

"main() is used to make a module importable and executable"

"Technically not, it's the if __name__ == '__main__' part"

"True, but it's still a good idea to use a main function"

2

u/blahreport Jul 19 '20

Indeed I agree that it is good practice to call a function that contains the meat of your script after the call blocker but the user I was responding to understood that the function being called must be named "main". Nevertheless, In the spirit of python, I don't think that function should be called "main". It should be named according to its function. I hope that clears things up. Though I don't think we're in disagreement as far as I can tell.

0

u/[deleted] Jul 18 '20

[deleted]

21

u/blahreport Jul 18 '20

Not so! Just putting it out there to set it straight. Almost everyone has some misunderstanding about some aspect of a complex system.

1

u/blabbities Redux FTW Jul 18 '20

Lmao. Probably using main() because is certain more restricted languages than Python it's the default entry point. So it breeds familiarity for this guy to have a function he can call into that is the main program.

1

u/Xahra_Hime Jul 19 '20

They probably have coding background

1

u/MLMoonShots Sep 22 '20

I've been learning 3 years and I still don't know why i should use main() or init or self or any of that other jazz.

Is this hyperbole or serious?

0

u/[deleted] Jul 18 '20

[deleted]

3

u/caifaisai Jul 18 '20

This sub is called learnpython for a reason. Its not look at how great my python skills are. Everyone learns at a different pace, and we have no idea how much time that commenter is able to spend on learning python. Maybe he has very little free time to devote to learning it, or a myriad of other reasons.

It's obviously fine to critique and give advice on someone's code or answer a question, since thats basically what the sub is for. But the commenter you replied to simply gave OP a compliment and didn't ask for help or anything, so there's no need to be rude and insult him for not having knowledge on something, particularly in a sub about learning python.

32

u/BAG0N Jul 18 '20

Here I've made some changes, you should really take advantage of integer division:

int(4 / 2)

is the same as

4 // 2

I've noticed that you were using the int function a lot of times because you didn't know about int division. Also you're calling other function many times from if statements, that's unnecessary, you can just do the calculations in if statements and then call the function at the bottom. I've removed the global and instead added another parameter to alarm (it's good practice to avoid global variables). You had a problem converting minutes to hours, it wasn't working but I fixed it and formatted most of the code according to PEP 8.

Nonetheless, this project is pretty damn cool and nicely done, your progress is great keep it up. Cheers.

Code:

import time
import winsound


def main():  # Try avoiding globals
    maininp = input("Hours mins or sec: ").lower()
    timelist = ("hours", "mins", "sec")
    if maininp in timelist:
        times(maininp)
    else:
        print("try again")
        main()


def times(userinp):
    if userinp == "hours":
        timewanted = int(input("how many hour: "))
        waitingtime = timewanted * 60 * 60
    elif userinp == "mins":
        timewanted = int(input("how many mins: "))
        waitingtime = timewanted * 60
    else:
        timewanted = int(input("how many sec: "))
        waitingtime = timewanted

    alarm(waitingtime, userinp)  # You can just call this once at the end of the function


def alarm(thetime, maininp):
    if maininp == "hours":
        s = str((thetime // 60) // 60)  # Integer division is pretty cool
        if thetime // (60 * 60) == 1:
            print(f"Your alarm is set for {thetime // (60 * 60)} Hour")
        else:
            print(f"Your alarm is set for {thetime // (60 * 60)} Hours")

    elif maininp == "mins":
        test = thetime // 60
        if test > 59:  # test > 59 because minutes can't be 60 (or test >= 60)
            print(f"Your alarm is set for {test // 60} Hours and {test % 60} mins")
        else:
            print(f"Your alarm is set for {thetime // 60} mins")

    else:
        print(f"Your alarm is set for {thetime} seconds")

    time.sleep(thetime)  # Same here, just call this once at the end of the function
    sound()


def sound():
    for i in range(2):
        for j in range(3):
            winsound.MessageBeep(-1)
            time.sleep(0.3)
        time.sleep(1)


if __name__ == "__main__":
    main()

7

u/mo_10 Jul 18 '20

what exactly is the difference between the // and / ? like what is int division but thank you for your response

10

u/BeastCoder Jul 18 '20

Integer division is like normal decimal division, but the decimal becomes truncated. Doing

int(5/2) is the same as 5//2

Sorry for the unformatted code, I’m on mobile right now.

3

u/BAG0N Jul 18 '20

Correct, it's nothing complicated just a division to make sure that you get an integer so you don't have to use int() again

2

u/mo_10 Jul 18 '20

ohhh this made a lot more sense thank you!

2

u/mo_10 Jul 18 '20

rightt i understand now thank you

18

u/Ketogamer Jul 18 '20

Just a tiny nit-pick, it doesn't really truncate the number. It just gives the floor, so
-5 // 2 gives -3
5 // 2 gives 2
math.trunc(-5 / 2) gives -2

That's why I prefer the name "floor division" instead of "int division" for the // operator.

8

u/BeastCoder Jul 18 '20

Ah, yep. Good catch :)

3

u/jarvis125 Jul 18 '20

// returns the quotient (an integer), while % returns the remainder.

/ returns the exact float division

10

u/ReflectedImage Jul 18 '20

So here's my go at the problem: https://pastebin.com/CrLutwkp

So to go through your code. You should grab the amount and units at the same time e.g. 5 seconds rather than grabbing 5 then grabbing seconds. For this you need to know about the .split(' ') function that splits up a string into parts based on the seperator in this case space.

Next is don't call main() to reset the program. Use a while True loop. Then you can use continue to reject the input and break to end the program. Another issue if you repeatly call main like that eventually the program will crash with "RecursionError: maximum recursion depth exceeded" after about a 1000 resets so it's bad practice.

In the times() function you have the amount and units so print out the waiting time there rather than dividing to get the amount back in the alarm() function.

maininp doesn't relate to a global thing like a UI window on screen or a database or anything persistent like that so it shouldn't be a global variable

4

u/mo_10 Jul 18 '20

damn i had a read and your code is a lot more advanced than mine! thank you for your feedback

1

u/Zephyr5967 Jul 19 '20

Would there be a way to modify this such that it could take an input such as “3 hours 1 minute 19 seconds”? I feel like that would massively complicate things and involve stuff such as finding the number of words in the string and having enough variables to make .split() work regardless of the length.

2

u/ReflectedImage Jul 19 '20
UNITS_TO_MULTIPLYERS = {
    'sec': 1,
    'min': 60,
    'hou': 3600
}

DISPLAY_NAMES = {
    'hou': 'Hour',
    'min': 'Minute',
    'sec': 'Second',
}


def get_alarm_duration():
    alarm_duration = input("How long until the alarm goes off?\ne.g. 2 hours 12 mins 3 seconds\n")

    alarm_duration_tokens = alarm_duration.lower().split(' ')
    values = [alarm_duration_tokens[i] for i in range(len(alarm_duration_tokens)) if i % 2 == 0]
    modifiers = [alarm_duration_tokens[i] for i in range(len(alarm_duration_tokens)) if i % 2 == 1]

    total_time_in_seconds = 0
    text_desc_tokens = []

    for value, modifier in zip(values, modifiers):
        value = int(value)
        modifier_short = modifier[0:3]
        if modifier_short not in UNITS_TO_MULTIPLYERS:
            raise ValueError

        total_time_in_seconds += value * UNITS_TO_MULTIPLYERS[modifier_short]

        text_desc_tokens.append(str(value))
        if value == 1:
            text_desc_tokens.append(DISPLAY_NAMES[modifier_short])
        else:
            text_desc_tokens.append("{}s".format(DISPLAY_NAMES[modifier_short]))

    alarm_duration_text = ' '.join(text_desc_tokens)

    return alarm_duration_text, total_time_in_seconds


text_description, total_time_in_seconds = get_alarm_duration()
print(text_description)
print(total_time_in_seconds)

1

u/Zephyr5967 Jul 19 '20

Thanks for taking the time to do that! Legend 👌🏻

1

u/r-_-mark Jul 19 '20

You could also do


 if modifier.lower() not in ["sec", "secs", "seconds", "min", "mins", "minutes", "hour", "hours"]:

With lower() fi make sure you are checking correctly User might type Sec for example you don’t want them to repeat themselves again

++

Use f-strings instead of format they are nicer

Other then that your code is dope

4

u/raivomittari Jul 18 '20

Whoa, nice...

I've been studying python for one month or something (self-teaching) and this is overwhelming.. I'll get there some day.

2

u/mo_10 Jul 18 '20

same man but ive been learing for maybe 2-3 weeks ish now i stared just after the beginning of july. that being said tho im sure you can get to a very good level within weeks you just have to put in the hours

2

u/Fearless_Process Jul 18 '20

This is actually really good for only two weeks of learning, I actually don't believe it. Do you have experience with other programming languages?

The only thing I would change is calling main() recursively, a while True: loop would be better. After 999 recursive calls python will throw an exception (no tail call optimization, but you can change the limit of calls). Also recursion isn't needed here unless I'm overlooking something.

2

u/mo_10 Jul 18 '20

Ahahha I started like literally beginning of July so just over 2 weeks now but before that I did have like very LITTLE python knowledge as I took compsci at gcse but we didn’t really learn much except the basics. And thank you for the feedback I’ve heard this a few times alresdy and I have changed the code a bit to use a if nsme = main and to add a loop too

1

u/StressedSalt Jul 19 '20

How and where did you learn :)?

Books websites apps?

1

u/mo_10 Jul 19 '20

Mainly YouTube playlists and when I didn’t understand the lesson I would research a bit more about it

2

u/egehurturk Jul 18 '20

So, my comment is you should avoid using global variables. And, use EAFP instead of LBYL (use try/except statements).

1

u/r-_-mark Jul 19 '20 edited Jul 20 '20

Why global are bad ??? Is a security thingy were you don’t want others to miss with your variables

1

u/egehurturk Jul 20 '20

Global variables can be accessed from any file, so be modified from everywhere. This can create bugs in your code.

1

u/r-_-mark Jul 20 '20

I still don’t get why Guido didn’t make private variables to be a thing in python Why there are no private, protected and public ..etc

I remember him saying something like “we are all adults”

2

u/Hillo111 Jul 18 '20

Great program! If this is only 2 weeks of learning, then you are definitely on a path to become really good programmer.
A few suggestions though:
- Instead of ifing to check if the number of hours and find if you need to put the s or not, you could instead have:
print(f'Your alarm is set for {int((thetime / 60) / 60)} {'Hours' if thetime != 1 else 'Hour'})
- As another comment mentioned, you should use integer division (//) instead of regular division (/). Regular division is more taxing on the CPU (I think)

- A small thing that you understandably missed is that you will always call sound your alarm. To maybe make the code a little bit easier to read, I suggest getting rid of all the sounds in the ifs and just putting it at the end of the function. Same thing with time.sleep(thetime)

In terms of user interface:
- I recommend having the user input [amount] [unit] instead of [unit] [ENTER] then [amount] to avoid potential confusion
- Another thing that might cause confusion is printing "try again". The user might have slightly misspelled a unit or written a unit differently and might be confused about what you mean by "try again". I recommend instead writing f'Invalid time unit the only available time units are {', '.join(timelist)}'
- Do a try: and except ValueError: when getting the amount of time. This helps prevent potential errors but doesn't get rid of the ones that you might want to look at

A few nit-picks:
- I would not recommend using articles before variable names. In my opinion, this just adds confusion, especially if you have a variable that is just the word without the prefix. If you want to have two variables that represent similar but different things, I recommend using something like var_1 and var_2
- When you compare the amount of time to find if you need an s or not, wouldn't you want to compare s instead of thetime, since thetime contains the number of seconds?

Anyways, if you read this, you did a great job, and good luck with learning more python!

1

u/IamaRead Jul 18 '20

Cool! Besides the other hints I would suggest you dealing with something pretty advanced, which is "asyncio" (under What is new > asyncio).

Then you can run your tool without it blocking your operating device.

1

u/print_your_user_name Jul 18 '20

I ran this code, after this i recieved this string in cmd:

Hours mins or sec

I entered:10:13

After this i recieved string:

try again

When i made mistake in using your programm?

1

u/Avaholic92 Jul 18 '20

You’re not supposed to enter an actual time you’re just supposed to enter an amount of time, for example 2 hours or 60mins

1

u/SweetJinx Jul 18 '20

Amazing 🔥🔥

1

u/[deleted] Jul 18 '20

Can anyone explain the working of this code ? I m a beginner in coding.

1

u/[deleted] Jul 18 '20

That's a really great achievement, good job!

1

u/Redditor728292 Jul 19 '20

You could could make custom exceptions, current code is great though.

-14

u/GreymanGroup Jul 18 '20

Terrible. There are ways to manage functions, time, and waiting. Sure it's fun to make things with the skillset you already have, but it's also important to recognize when you don't have the tools for the job so you don't waste your time doing things the "wrong" way. Also so that way you learn the right way to do things.

But that's sort of a meta analysis of learning in general. Good creativity on rigging the dings.

Keep learning. And try to make your user input branches less needlessly verbose.

7

u/mo_10 Jul 18 '20

This is something I actually understand. Like I know my code is nowhere near amazing and knowing this I try to make it so it’s less code but the same thing but I just don’t know how to do that and how to go more advanced. Do you have any tips?

2

u/GreymanGroup Jul 18 '20 edited Jul 18 '20

DON'T REPEAT LINES! That's what loops and functions are for!

0

u/GreymanGroup Jul 18 '20

Just to learn the language and the base concepts. When you get familiar with more and more of the core concepts it'll be more natural to make more readable and to the point code.

0

u/[deleted] Jul 18 '20

[deleted]

6

u/mo_10 Jul 18 '20

thank you! im not exaclty sure how to use if name == main its something I wasn't too keen on but now after I did a bit more research I've changed my code to this:

if __name__=="__main__":
    try:
        usernumber = int(input("What number would you like to use: "))
        find_fact(usernumber)
    except ValueError:
        print("That was not a number")
        main()

would this be better?

and mIight need to look into argparse and pep 8 linter etc. but thank you for the feedback

3

u/mo_10 Jul 18 '20

shit i realised i sent the code for another project I'm trying but I guess it has the same concept