当我使用选项2打印“客户”字典键时,即使我已经添加了客户,它也显示为[]
。谁能帮助我了解问题出在哪里?
def main():
import sys
Clients = {}
choice = input(" Click 1 to add another client\n Click 2 to Check a Clients Balance\n Click 3 to change a Clients Balance ")
if choice == "1":
name = input('Add a Client\'s name : ')
Clients.update({name.rstrip("\n"):0})
print(name)
print(Clients.keys())
main()
elif choice == "2":
print(Clients.keys())
main()
elif choice == "3":
print('Do it later')
main()
else:
print('Please choose again')
main()
main()
答案 0 :(得分:2)
您一次又一次地使用新字典来调用main
,这称为递归。在这里,您应该使用while循环。
def main():
clients = {}
while True:
choice = input("Click 1 to add another client\n Click 2 to Check a Clients Balance\n Click 3 to change a Clients Balance ")
if choice == "1":
name = input("Add a Client's name : ")
clients[name.rstrip()] = 0
print(name)
print(clients.keys())
elif choice == "2":
print(clients.keys())
elif choice == "3":
print('Do it later')
else:
print('Please choose again')
main()