Python 在我的程序';什么是背景?

Python 在我的程序';什么是背景?,python,datetime,Python,Datetime,我想在调用日期后立即验证输入,这样用户就不会输入所有三个,然后再次收到错误/日期提示,但我想不出一种方法。我需要重组吗,还是我缺少了一条路 我有一个类对象任务定义如下: class task: def __init__(self, name, due, category): self.name = name self.due = datetime.strptime(due, '%B %d %Y %I:%M%p') self.category

我想在调用日期后立即验证输入,这样用户就不会输入所有三个,然后再次收到错误/日期提示,但我想不出一种方法。我需要重组吗,还是我缺少了一条路

我有一个类对象
任务
定义如下:

class task:
    def __init__(self, name, due, category):
        self.name = name
        self.due = datetime.strptime(due, '%B %d %Y %I:%M%p')
        self.category = category
    def expand(self): # returns the contents of the task
        return str(self.name) + " is due in " + str((self.due - datetime.now()))
def addTask(name, due, category):
    newTask = task(name, due, category)
    data.append(newTask)
    with open('./tasks.txt', 'wb') as file:
        pickle.dump(data, file)
    load_data()
    list_tasks()
该类是通过函数
addTask
创建的,该函数定义如下:

class task:
    def __init__(self, name, due, category):
        self.name = name
        self.due = datetime.strptime(due, '%B %d %Y %I:%M%p')
        self.category = category
    def expand(self): # returns the contents of the task
        return str(self.name) + " is due in " + str((self.due - datetime.now()))
def addTask(name, due, category):
    newTask = task(name, due, category)
    data.append(newTask)
    with open('./tasks.txt', 'wb') as file:
        pickle.dump(data, file)
    load_data()
    list_tasks()
收集的输入如下所示:

def ask():
    while True:
        arg = input("").lower()
        if arg == "add":
            addTask(input("What is the task? "),input("When's it due? "),input("What's the category? "))
        elif arg =="help":
            help()
        elif arg =="list":
            list_tasks()
        else:
            print("Command not recognized. Type 'help' for a list of commands.")

一种方法是在try/except块中将datetime传递给
addTask
之前验证它

def ask():
    while True:
        arg = input("").lower()
        if arg == "add":
            task = input("What is the task? ")
            due = input("When's it due? ")
            category = input("What's the category? "))
            try:
                due = datetime.strptime(due, '%B %d %Y %I:%M%p')
            except ValueError:
                raise ValueError("Incorrect date format")
            addTask(task, due, category)
        elif arg =="help":
            help()
        elif arg =="list":
            list_tasks()
        else:
            print("Command not recognized. Type 'help' for a list of commands.")
有更可靠的方法进行验证,例如使用棉花糖库,但对于您正在进行的工作来说,这可能是过分的