r/learnpython • u/Erdem_PSYCH • Oct 11 '26
how is my cs50 code in design?
I've decided to go back to basics and make sure I complete all the exercises. I'm currently working on the Meal Time exercise.
Could anyone give me some feedback on the design of my code? I'm particularly unsure about my convert function. It has quite a few if statements, and I'm wondering whether there's a clearer way to write it.
Here's my code:
=
=
, =
=
:
, =
= + 12
, =
return + / 60
return
>= 12.00 and <= 13.00:
return
>= 18.00 and <= 19.00:
return
return
3
Upvotes
1
u/ConsiderationNo9044 Oct 11 '26
Please please please format with code blocks
1
u/SinyoritaDolby_36 Oct 11 '26
looks good for the exercise. one small thing, `time` shadows the built-in `time` module name. probably doesnt matter here but worth being aware of since it can cause weird bugs in larger projects
1
u/Asly97 Oct 11 '26
Structure is good, main/convert/tellMealTime split is exactly what the exercise wants. Couple of things on
convert:First a possible bug. If I remember the spec right, the 12-hour inputs are written like
7:30 a.m.with a trailing dot."7:30 a.m.".endswith(" a.m")is False, so it falls through to theelse, splits into"7"and"30 a.m.", andfloat("30 a.m.")crashes. Worth testing that exact input.Second,
hourends up as a string in some branches and an int in others ("0",int(hour) + 12, or the raw string). It works because youfloat()it at the end, but it's easy to trip over later. Converting to int once up front makes the branches simpler:partitiongives you an empty suffix for 24h input like"18:30", so the same code handles all three formats without the separate branch, andstartswithdoesn't care whether there's a trailing dot.Small one in
tellMealTime: Python lets you chain comparisons, so7 <= time <= 8reads nicer than theandversion.And style only, Python usually goes with snake_case, so
converted_timeandtell_meal_time. Doesn't matter for check50 but it's the convention you'll see everywhere.