繁体   English   中英

Python while 循环用户输入,直到在 sql 中找到结果

[英]Python while loop user input until result found in sql

我想让我的代码要求用户输入用户 ID。 如果在 SQL 数据库中找到用户 ID,则系统将打印成功。 否则,它会一直要求用户输入用户 ID。 现在,如果我先输入一个有效的用户 ID (U0020),代码运行良好。

问题是,如果我先输入了错误的用户 ID(ewehri),即使我之后输入了一个有效的用户 ID,output 仍然是“对不起,数据库中没有这样的记录。请重试”并提示用户输入再次。 我不确定如何解决这个问题。

首先,我定义调用 sql 数据库从用户 ID 获取帐号:

conn=create_connection()
def getacct(userid): 
    query = """\
        select Account_Number
        from User_Account
        where UserID = '{}'
        """ .format(userid)

    return (execute_read_query (conn, query))

这工作正常。 之后,我这样做是将结果放入列表中:

userid = input("Please enter your user id:")
acct_no = getacct(userid)

accountno = []
for i in acct_no:
    accountno.append(i[0])

然后是有问题的部分。 我检查列表 [accountno] 是否为空。 如果为空,则表示用户 ID 不在数据库中,因此无法返回任何帐号。 如果它不为空,那么它应该打印“成功”并退出循环。 但是,如前所述,它不会退出循环。

def User():
    while accountno:
        print("successful")
        break
    else:
        print ("Sorry, no such record in the database. Please try again")
        userid = input("Please enter your user id:")

我还尝试了此代码的多次迭代,例如将代码的“将结果放入列表”部分放在 def User() 中,或者这样:

def User():
    while not accountno:
        print ("Sorry, no such record in the database. Please try again")
        userid = input("Please enter your user id:")
        
        if accountno:
            print ("Successful!")

还有更多,但我无法得到我需要的 output。 我希望这里有人会知道我做错了什么。 谢谢你的帮助!

您可以使用accountno.pop() if accountno之后。 通过使用 pop 方法而不是 del,您可以稍后使用该值,例如saveUserID = accountno.pop() 另一种方法是在print("Successful")部分之后使用 break 语句。 但是,您的另一个问题是您没有 append 将 userid 设置为accountno ,而是使用 if 来检查accountno ,而不是新输入的userid 最后,您应该将accountno作为 function 参数传递给User()并将其用作返回类型。 这是一个更好的例子:

def User(userid):
    while not userid:
        print ("Sorry, no such record in the database. Please try again")
        userid = input("Please enter your user id:")

    print ("Successful!")
    return userid

这样,您的accountno变量将包含一个成功输入的用户 ID。 您的打印应该在 while 循环之后进行,因为无论如何它只会在成功时打印。

要使用,请说以下内容:

accountno.append(User(accountno))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM