为什么我的循环没有停在我设定的数字上?

2024-10-01 07:42:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python为一个使用数组和函数的银行应用程序编写一个程序。这是我的密码:

NamesArray=[]
AccountNumbersArray=[]
BalanceArray=[]
def PopulateAccounts():
    for position in range(5):
        name = input("Please enter a name: ")
        account = input("Please enter an account number: ")
        balance = input("Please enter a balance: ")
        NamesArray.append(name)
        AccountNumbersArray.append(account)
        BalanceArray.append(balance)
def SearchAccounts():
    accounttosearch = input("Please enter the account number to search: ")
    for position in range(5):
        if (accounttosearch==NamesArray[position]):
            print("Name is: " +position)
            break
    if position>5:
        print("The account number not found!")

print("**** MENU OPTIONS ****")
print("Type P to populate accounts")
print("Type S to search for account")
print("Type E to exit")
choice = input("Please enter your choice: ")
while (choice=="E") or (choice=="P") or (choice=="S"):
    if (choice=="P"):
        PopulateAccounts()
    elif (choice=="S"):
        SearchAccounts()
    elif (choice=="E"):
        print("Thank you for using the program.")
        print("Bye")

当用户输入“p”时,应该调用def PopulateAccounts(),但问题是它没有停止,用户必须不断输入帐户名、帐号和帐户余额。它应该在第五个名字之后停止。我该怎么解决这个问题?你知道吗


Tags: tonamenumberforinputdefpositionaccount
3条回答

这是因为在PopulateAccounts()完成while之后,循环继续迭代,因为choice仍然是P。如果你想让用户做另一个动作,只需再次要求他输入。你知道吗

choice = input("Please enter your choice: ")
while (choice=="E") or (choice=="P") or (choice=="S"):
    if (choice=="P"):
        PopulateAccounts()
    elif (choice=="S"):
        SearchAccounts()
    elif (choice=="E"):
        print("Thank you for using the program.")
        print("Bye")
    choice = input("Please enter another action: ")

另外,我建议您使用无限循环来不断询问用户输入,并在用户输入“E”时中断,这样您还可以跟踪无效的输入。你知道吗

while True:
    choice = input("Please enter your choice: ")
    if choice == "P":
        PopulateAccounts()
    elif choice == "S":
        SearchAccounts()
    elif choice == "E":
        print("Thank you for using the program.")
        print("Bye")
        break
    else:
        print("Invalid action \"{}\", avaliable actions P, S, E".format(choice))
    print()

在循环开始之前,您的代码只要求用户选择一次。因为它永远不会改变,所以这个循环将坚持用户的选择,进行无限次的迭代。你知道吗

choice = input("Please enter your choice: ")
while (choice=="E") or (choice=="P") or (choice=="S"):
    if (choice=="P"):
        PopulateAccounts()
    elif (choice=="S"):
        SearchAccounts()
    elif (choice=="E"):
        print("Thank you for using the program.")
        print("Bye")
    # here at the end of this loop, you should 
    # get the user to enter another choice for the next 
    # iteration. 

你的while循环没有计数器使它停在第5个名称处,而position只在它所在的函数执行期间存在。而且,position永远不会大于4。range(5)从0开始到4结束。你知道吗

相关问题 更多 >