尝试为格式为YYYY-MM-DD的日期创建输入验证。我有两种方法可以做到这一点。
第一种方法似乎有效,并且每次出现错误时都会循环返回以获取输入。
第二种方法中的函数导致无限循环,但第一种方法中几乎相同的函数不会。
如果我在第二种方法中输入了正确格式的日期,它将按预期进行打印,但是对于其他任何输入,都会创建无限循环。
我不确定这在哪里分解?
我已经查看了许多Google搜索结果,并且有很多日期验证,但我还没有找到一个明确地解决如何环回并重试的验证。
我不确定在不重写方法一的情况下还要尝试什么。
import datetime as dt
#METHOD 1 - This is the first method for validating date input, which takes in individual blocks and validates each one individually.
def get_date(year_prompt, month_prompt, day_prompt):
#Year Input
while True:
try:
year = int(input(year_prompt))
except ValueError:
print("Sorry, I didn't understand that.\n")
continue
if year in range(2000,3000,1):
break
else:
print("Sorry, your response must be in YYYY format and later than the year 2000.\n")
continue
#Month Input
while True:
try:
month = int(input(month_prompt))
except ValueError:
print("Sorry, I didn't understand that.\n")
continue
if month in range(1,13,1):
break
else:
print("Sorry, needs to be MM and between 1-12\n")
continue
#Day Input
while True:
try:
day = int(input(day_prompt))
except ValueError:
print("Sorry, I didn't understand that.\n")
continue
if day in range(1,32,1):
break
else:
print("Sorry, needs to be DD and between 1-31\n")
continue
#Takes the three inputs and puts them together into a date
date = dt.datetime(year, month, day)
#Returns the date
return date
#Runs the first method of getting and validating a date.
date = get_date("\nYYYY: ", "\nMM: ", "\nDD: ")
#Prints the validated date.
print("\nThe date you entered is: ", date, "\n")
#METHOD 2 - This is the second method for validating date, which takes in the whole date in one input, and attempts to validate it against the YYYY-MM-DD format.
def input_validation(date):
while True:
try:
dt.datetime.strptime(date, '%Y-%m-%d')
break
except ValueError:
print("\nSorry, this does not appear to be a valid date in format YYYY-MM-DD")
continue
return date
#Prints the validated date.
print("\nThe date you entered is: ", input_validation(input("Enter a date in format YYYY-MM-DD: ")), "\n")
我对第二种方法的预期结果是格式为YYYY-MM-DD的日期,或者是错误消息,然后再次要求输入。
答案 0 :(得分:0)
您可以摆脱无限循环while True
,然后根据正确格式的日期返回True
或False
def input_validation(date):
#Flag to check date format
flag = False
try:
#If date is of correct format, set flag to True
dt.datetime.strptime(date, '%Y-%m-%d')
flag = True
except ValueError:
print("\nSorry, this does not appear to be a valid date in format YYYY-MM-DD")
#Return flag
return flag
print(input_validation('2019-01-31'))
print(input_validation('2019-001-31'))
print(input_validation('2019-01-311'))
输出将为
True
Sorry, this does not appear to be a valid date in format YYYY-MM-DD
False
Sorry, this does not appear to be a valid date in format YYYY-MM-DD
False
您可以将此功能包装在while True
周围,以继续接受用户的输入
while True:
date_str = input('Enter Date')
if input_validation(date_str):
break