Hi I would like to request a time from the user in the format "HH:MM" using the input()
function.
Do you have an idea with which function I can ensure that the user only enters numbers and only the special character ":" and not e.g. ";".
I create a funtion:
def checkElements(time):
symbole = ":"
res_list = []
allowedKeys = ["0","1","2","3","4","5","6","7","8","9"]
sizeAllowedKeys = len(allowedKeys)
if symbole in time:
res_list.append(symbole)
for i in range(sizeAllowedKeys):
if allowedKeys[i] in time:
res_list.append(allowedKeys[i])
elif allowedKeys[i] not in time:
#print("false input")
pass
if len(res_list) == 5:
keyStatus = 0
elif len(res_list) != 5:
print("false input")
keyStatus = 1
else:
print("false input")
keyStatus = 1
return keyStatus
But here I have the problem that it does not recognize already recognized digits twice. Also I think that the solution is not very clean.
Thank you and best regards
Try this:
def check(time):
# time = 12:20
# time.split(":") -> [12, 20]
# "".join(time.split(":")) -> 1220
if ":" in time and "".join(time.split(":")).isdigit():
print("Great time")
else:
print("Wrong time")
check("12:20")