【发布时间】: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