对于我的学校,我正在制作ATM。我用它的功能创建了它的基础:存款,取款和支票余额。 我做了这样,所以用户被保存到文件“用户”,其名称,余额和图钉。我可以让它正确地写入字典并保存到文件中但是当代码运行时它不会按照我需要的顺序读取它们。
代码:
users = {}
pin = 0
balance = 0
with open("N:\users") as f:
for line in f:
(key, val) = line.split() #Reads the file like ('Ben:[0,', 0): '1234]'
users[key, pin] = val**
print users
上面的代码是将文件写入字典,然后将其放入字典中,并且我不知道如何修复它
def Login():
if name in users:
pin = raw_input("Enter your pin:")
if pin == users[pin]:
print "Welcome back", name
else:
print "Wrong pin"
elif name == "join":
bal = 0
pcor = 0
nname = raw_input("Welcome new user, enter your name.")
while pcor != 1:
npin = int(raw_input("Enter a 4 digit pin."))
if len(str(npin)) != 4:
print "Please enter another FOUR digit pin eg: 1234."
else:
pcor = 1
users[nname] = [bal,npin] #Writes to dictionary: Ben:[0, 1234]
print users
with open("N:\users", 'a') as f:
for key, val in users.items():
f.write('{}:[{},{}]\n'.format(key, bal, npin)) #Saves to the file like I want: Ben:[0, 1234]. However When you add a new user, it saves all existing users again
elif name == "exit":
exit()
else:
print "Unrecognised response."
exit()
def Deposit():
add = int(raw_input("How much would you like to deposit?"))
users[key] = int(users[key]) + int(add)
print "Your balance is now", users[key]
f1 =open('N:\users', 'w+')
print >> f1,name,users[key]
f1.close()
def Withdraw():
minus = int(raw_input("How much would you like to withdraw?"))
if minus > int(users[key]):
print "You do not have enough in your account."
else:
users[key] = int(users[key]) - int(minus)
print "Your balance is now", users[key]
f1 =open('N:\users', 'w+')
print >> f1,name,users[key]
f1.close()
def CheckFunds():
print "You have £"+users[key], "in your account."
name = raw_input("If you are have an account, enter your name, \
if you would like to make an account enter 'join', \
if you want to exit the ATM type 'exit'.")
Login()
action = raw_input("What would you like to do? A)Deposit B)Withdraw C)Check Balance D)Exit")
if action == "a" or action == "A":
Deposit()
elif action == "b" or action == "B":
Withdraw()
elif action == "c" or action == "C":
CheckFunds()
else:
exit()
感谢您的帮助,Ben。