How can I improve the Boilerplate Time Calculator

I have just completed the Boilerplate Time Calculator in Python. How did I do please and what can I improve on? Always looking to better my work

I think I used a lot of if/else if statements - how could I have reduced my usage of them?

Having everything working it’s really a good time to take another look to see what can be improved.

Parts with many if/else is indeed a nice place to start. These can be hard to read and may quickly improve complexity. The goal would be here to try to find parts that don’t really depend on the conditions and to move them out of the if/else. And also try to find repeated part, and see if there’s way to cut down the repeating.

I’ve copied below, from the last if/else, what is later returned by function.

str(hour)+':0'+str(minn)+" "+str(ampm)+", "+str(thisdict.get(dayposition))+" (next day)"
str(hour)+':'+ str(minn)+" "+str(ampm)+", "+str(thisdict.get(dayposition))+" (next day)"
str(hour)+':0'+str(minn)+" "+str(ampm)+" "+dayneeded +"(next day)"
str(hour)+':'+ str(minn)+" "+str(ampm)+" "+dayneeded +"(next day)"
str(hour)+':0'+str(minn)+" "+str(ampm)+", "+thisdict.get(dayposition)+" ("+str(newday)+" days later)"
str(hour)+':'+ str(minn)+" "+str(ampm)+", "+thisdict.get(dayposition)+" ("+str(newday)+" days later)"
str(hour)+':0'+str(minn)+" "+str(ampm)+" ("+str(newday)+" days later)"
str(hour)+':'+ str(minn)+" "+str(ampm)+" ("+str(newday)+" days later)"
str(hour)+':0'+str(minn)+" "+str(ampm)+", "+day
str(hour)+':'+ str(minn)+" "+str(ampm)+", "+day
str(hour)+':0'+str(minn)+" "+str(ampm)
str(hour)+':'+ str(minn)+" "+str(ampm)

Does looking at all those options in a bit simplified matter give you some ideas what can be done here?

Thanks for the reply. Although I’m a little unsure how you would go about simplifying it? Do you use functions?

I wouldn’t say adding functions is necessary at this point. It might help further along the refactoring.

This part repeats for each case:

str(hour)+':0'+str(minn)+" "+str(ampm)
str(hour)+':'+ str(minn)+" "+str(ampm)

This means it can be moved outside of this if/else, to get part of the returned string ready a bit sooner. That way each case isn’t additionally split to determine, how returned string should start, because that’s done before.

And instead of 12 different returned cases, you end up with half of that. Roughly concatenating to the partial string:

+", "+str(thisdict.get(dayposition))+" (next day)"
+" "+dayneeded +"(next day)"
+", "+thisdict.get(dayposition)+" ("+str(newday)+" days later)"
+" ("+str(newday)+" days later)"
+", "+day
# nothing added in last case

That’s one step, there are some other places that could be looked at, and likely some additional potential improvements will reveal themselves after each step.

ah gotcha thanks that was so obvious :man_facepalming:

No need to feel bad. When focusing on little details mind has tendency to skip the bigger picture, and the other way around.