首页 > 解决方案 > 为什么我的循环没有在我设置的数字处停止?

问题描述

我正在为使用数组和函数的银行应用程序编写一个 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()它并且确实调用了它,但问题是它不会停止并且用户必须不断输入账户名称、账户号码和账户余额。它应该在第 5 个名字之后停止。我该如何解决?

标签: python

解决方案


这是因为PopulateAccounts()完成后while循环不断迭代,因为choiceis still 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()

推荐阅读