r/learnpython • u/mo_10 • 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()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()again2
2
2
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 -2That's why I prefer the name "floor division" instead of "int division" for the // operator.
8
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
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!
2
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
1
1
1
-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
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
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 usemain()or__init__orselfor 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