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()
它并且确实调用了它,但问题是它不会停止并且用户必须不断输入账户名称、账户号码和账户余额。它应该在第 5 个名字之后停止。我该如何解决?
解决方案
这是因为PopulateAccounts()
完成后while
循环不断迭代,因为choice
is 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()
推荐阅读
- sharepoint - 作为使用 SPO REST API 的一部分,要为“ViewFields”参数发送的有效负载是什么?
- c++ - 如何从另一个 UNICODE_STRING 创建一个 UNICODE_STRING
- javascript - 如何在此 if 语句中不返回任何内容而不是空格?
- javascript - 如何在不更新列表兄弟的情况下更新映射列表中的值?
- c++ - std::async 执行顺序保证
- python - 将深度反投影到原始网格上
- swift - SwiftUI - 将删除操作(带索引)添加到警报按钮
- python - GPUtil.showUtilization 突然不起作用
- reactjs - 在 .env 中隐藏我的 MongoURI 变量会破坏我在 Heroku 上的应用
- firebase - Flutter Firebase - 未能正确删除经过 Google 身份验证的用户