Hello again everyone, I'm currently working on the CS50 Python course's working.py assignment, and while I've figured it out for the most part, I have a silly problem I would like some advice on.
First, here is my code:
import re
def main():
print(convert(input("Hours: ")))
def convert(s):
if time := re.search(r"(\d{1,2}):?(\d{2})? (AM|PM) to (\d{1,2}):?(\d{2})? (AM|PM)", s, re.IGNORECASE):
h1, h2 = (int(time.group(1)), int(time.group(4)))
m1, m2 = (int(time.group(2)), int(time.group(5)))
p1, p2 = (time.group(3), time.group(6))
if any((h1, h2)) > 12 and any((m1, m2)) >= 60:
raise ValueError
if h1 < 12 and p1 == "PM":
h1 += 12
if h2 < 12 and p2 == "PM":
h2 += 12
if h1 == 12 and p1 == "AM":
h1 -= 12
if h2 == 12 and p2 == "AM":
h2 -= 12
if m1 == None:
m1 = ":00"
if m2 == None:
m2 = ":00"
return f"{h1:02d}:{m1:02d} to {h2:02d}:{m2:02d}"
else:
raise ValueError
if __name__ == "__main__":
main()
The assignment calls for a time prompt in the 12-hour format, for example: 9 AM to 5 PM, 9:30 AM to 3:30 PM etc and the output is on the 24-hour format, like 09:00 to 17:00. The problem I'm experiencing is that when the minutes are declared as time.group(2) and time.group(5) respectively but omitted from the prompt, the AM|PM value takes the minute's group position and results in disarray. What would be the best and most efficient way to approach this? And also, if you have any other advice on how to shorten / optimize my code, any advice would be really appreciated as I am still learning, thank you!