【问题标题】:Python while loop user input until result found in sqlPython while循环用户输入,直到在sql中找到结果
【发布时间】:2021-04-19 01:54:00
【问题描述】:

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

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

首先,我定义调用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!")

还有更多,但我无法获得所需的输出。我希望这里有人会知道我做错了什么。感谢您的帮助!

【问题讨论】:

  • 您拥有的代码不会做任何事情来删除错误信息。因此,while 循环条件始终返回 True 并永远运行。您需要如何处理accountno 中的数字?你弹出并使用它们还是打印成功?如果你只需要打印'successful',然后删除代码,试试del accountno[0]
  • 如果需要从最后删除,请改用accountno.pop()。
  • @anvoice 我需要使用它。现在只打印“成功”,以便更容易查明错误,因为我做了很多。我对python很陌生。我可以知道我应该在代码中的哪个位置使用accountno.pop()吗?
  • 让我写这个作为答案。这占用的空间比预期的要多。

标签: python visual-studio-code input while-loop


【解决方案1】:

您可以使用accountno.pop()。在if accountno 之后。通过使用 pop 方法而不是 del,您可以稍后使用该值,例如saveUserID = accountno.pop()。另一种方法是在print("Successful") 部分之后使用break 语句。但是,您的另一个问题是您没有将用户 ID 附加到 accountno,而是使用 if 检查 accountno,而不是 userid 的新输入。最后,您应该将accountno 作为函数参数传递给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))

【讨论】:

    猜你喜欢
    • 2014-04-12
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    • 1970-01-01
    • 2018-05-03
    • 1970-01-01
    • 2019-12-07
    • 2020-09-29
    相关资源
    最近更新 更多