One way to break an outer loop from an inner loop without adding an extra variable to keep track of is to use else: continue
followed by a break
:
while True:
user = input("Enter: ")
if "/" not in user:
if "," in user:
date = user.replace(",", "")
date = date.split(" ")
date = list(date)
for i in range(len(date)):
if date[i] in month:
mnth = month[f"{date[i]}"]
if int(date[1]) < 10:
date[1] = "0" + date[1]
print(f"{date[2]}-{mnth}-{date[1]}")
break
else:
continue # continue if the for loop wasn't broken
break # break the while if we didn't continue
As explained in the comments, the trick is that the else
of the for
executes if there was no break
-- we can therefore continue
the while
if and only if there was no break
inside the for
, and explicitly break
the while
otherwise.
Not directly related to that, I'd suggest battling some of that indentation by using continue
elsewhere in the loop, and getting rid of all the unnecessary string manipulation (note the use of {date[1]:0>2}
to zero-pad to two digits without needing the int math -- neat, eh?):
while True:
user = input("Enter: ")
if "/" in user:
continue
date = user.replace(",", "").split(" ")
for mm in date:
if mm not in month:
continue
print(f"{date[2]}-{mm}-{date[1]:0>2}")
break
else:
continue
break
and since your code seems to assume that date[2]
is always the year and date[1]
is always the day of the month, I'm going to go out on a limb and guess that you can also safely assume the month is always date[0]
if it's anything at all, which means you can skip that whole inner loop and just do:
while True:
user = input("Enter: ")
if "/" in user:
continue
mm, dd, yyyy = user.replace(",", "").split(" ")[:3]
if mm not in month:
continue
print(f"{yyyy}-{mm}-{dd:0>2}")
break