0

我正在尝试测试用户输入,但它似乎只在第一次通过。如果我第一次给出正确的数据,它会起作用,但如果我最初给出错误的数据,然后在重新提示后使用正确的数据,它永远不会识别它是正确的。知道为什么它第一次起作用,但在那之后的任何时候都不起作用吗?这是代码,

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"
4

2 回答 2

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()
于 2012-06-18T16:10:06.970 回答
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(',')

我同意评论者的观点,即您可以尝试重构代码以合并重复的部分。

于 2012-06-18T01:21:38.907 回答