我正在尝试测试用户输入,但它似乎只是第一次工作。如果我第一次提供正确的数据,它可以工作,但如果我最初提供错误的数据,然后在重新提示后使用正确的数据,它永远不会认为它是正确的。知道为什么它第一次工作但不是之后的任何时间吗?这是代码,
testDate = open("Sales.txt")
def DateTest(Date, Position):
firstTry = True
validSyntax = False
Done = False
while Done == False:
while validSyntax == False:
if firstTry == True:
print "debug 2"
try:
Date = Date.strip().split(',')
Year = int(Date[0])
Month = int(Date[1])
Day = int(Date[2])
Date = (Year, Month, Day)
except:
print "That is invalid input."
firstTry = False
else:
validSyntax = True
print "ok got it"
elif firstTry == False:
NewDate = raw_input("Please input the desired %s date in the form YYYY,MM,DD: " % Position)
try :
NewDate = startDate.strip().split(',')
Year = int(NewDate[0])
Month = int(NewDate[1])
Day = int(NewDate[2])
NewDate = (Year, Month, Day)
except:
print "That is invalid input."
else:
validSyntax = True
print" ok got it"
if validSyntax == True:
for line in testDate:
line = line.strip().split(',')
yearTest = int(line[0])
monthTest = int(line[1])
dayTest = int(line[2])
dateTest = (yearTest, monthTest, dayTest)
if Year == yearTest:
if Month == monthTest:
if Day == dayTest:
Done = True
print "success"
答案 0 :(得分:0)
要解决目前无效的原因:您从未设置startDate
,因此strip().split()
的尝试无效:
NewDate = raw_input("Please input the desired %s date in the form YYYY,MM,DD: " % Position)
try :
NewDate = startDate.strip().split(',') // startDate isnt set
你可以尝试
startDate = raw_input("Please input the desired %s date in the form YYYY,MM,DD: " % Position)
try :
NewDate = startDate.strip().split(',')
我同意评论者的意见,你可以尝试重构代码以整合重复的部分。
答案 1 :(得分:0)
以下是重构版本:
import time
DATE_FORMAT = '%Y,%m,%d'
def parse_date(date_str, fmt=DATE_FORMAT):
try:
return time.strptime(date_str.strip(), fmt)
except ValueError:
return None
def get_date(adj='', fmt=DATE_FORMAT, prompt='Please enter the {}date (like {}): '):
prompt = time.strftime(prompt.format(adj.strip()+' ' if adj.strip() else '', fmt))
# repeat until a valid date is entered
while True:
inp = raw_input(prompt)
res = parse_date(inp, fmt)
if res is None:
print('Invalid input')
else:
return res
def get_test_date(date, adj='', fmt=DATE_FORMAT):
return parse_date(date, fmt) or get_date(adj, fmt)
def find_date_in_file(fname, date_str='', adj=''):
test_date = get_test_date(date_str, adj)
with open(fname) as inf:
for line in inf:
if test_date == parse_date(line):
print('Found!')
return test_date
def main():
find_date_in_file('Sales.txt', '2012,01,05', 'closing')
if __name__=="__main__":
main()