首页 > 解决方案 > 如何进行双重验证?

问题描述

我对 Python 编码有一个疑问。

想象以下情况:

我想对一个我有一个必须检查的接口的数据库进行 2 次验证,首先是用户字段是否不同于 0,然后它应该出现一条消息,例如“请填写字段”,然后如果用户输入是是否在数据库中(例如,如果数据库中存在材料 X,如果不存在,则应出现另一个错误)。

在这种情况下,这样做的好方法是什么?创建2个不同的def函数?或者也许做两个“如果”?

我是 Python 和编程的新手。

谢谢和亲切的问候

标签: python

解决方案


你可以试试这个

database = ["","Wood","Steel","Iron",""]

def InFillCheck(database):
    sizeBool = False
    index = 0
    innerCounter = 0
    while sizeBool == False:
        for material in database:
            if material == "":
                try:
                    userInput = input("Please enter new material: ")
                    if userInput in database:
                        raise Exception
                    index = database.index(material)
                    database[index] = userInput
                    print(database)
                except:
                    print("It is already in the database")
        innerCounter = innerCounter + 1
        if innerCounter == len(database):
            sizeBool = True


InFillCheck(database)

有关更多详细信息,您可以查看以下链接,

https://www.w3schools.com/python/python_try_except.asp
https://docs.python.org/3/tutorial/errors.html
https://www.datacamp.com/community/tutorials/exception-handling-python

你也可以改进我的代码,我试着给你一个想法和起点。


推荐阅读