我使用以下代码打开了一个搁置:
#!/usr/bin/python
import shelve #Module:Shelve is imported to achieve persistence
Accounts = 0
Victor = {'Name':'Victor Hughes','Email':'victor@yahoo.com','Deposit':65000,'Accno':'SA456178','Acctype':'Savings'}
Beverly = {'Name':'Beverly Dsilva','Email':'bevd@hotmail.com','Deposit':23000,'Accno':'CA432178','Acctype':'Current'}
def open_shelf(name='shelfile.shl'):
global Accounts
Accounts = shelve.open(name) #Accounts = {}
Accounts['Beverly']= Beverly
Accounts['Victor']= Victor
def close_shelf():
Accounts.close()我能够将值附加到搁置中,但无法修改这些值。我定义了一个函数shelve.But (),我想从它修改shelve.But中的数据,它给了我以下错误:
Traceback (most recent call last):
File "./functest.py", line 16, in <module>
Deposit()
File "/home/pavitar/Software-Development/Python/Banking/Snippets/Depositfunc.py", line 18, in Deposit
for key in Accounts:
TypeError: 'int' object is not iterable这里是我的函数:
#!/usr/bin/python
import os #This module is imported so as to use clear function in the while-loop
from DB import * #Imports the data from database DB.py
def Deposit():
while True:
os.system("clear") #Clears the screen once the loop is re-invoked
input = raw_input('\nEnter the A/c type: ')
flag=0
for key in Accounts:
if Accounts[key]['Acctype'].find(input) != -1:
amt = input('\nAmount of Deposit: ')
flag+=1
Accounts[key]['Deposit'] += amt
if flag == 0:
print "NO such Account!"
if __name__ == '__main__':
open_shelf()
Deposit()
close_shelf()如果我错了,我是Python.Please help.Correct me的新手,我需要有人来解释一下这个代码的功能,我很困惑。
发布于 2010-10-25 20:13:17
首先,不要为Accounts使用全局,而是来回传递它。使用全局导致您的错误。如下所示:
def open_shelf(name='shelfile.shl'):
Accounts = shelve.open(name) #Accounts = {}
...
return Accounts
def close_shelf(Accounts):
Accounts.close()
def Deposit(Accounts):
...
if __name__ == '__main__':
Accounts = open_shelf()
Deposit(Accounts)
close_shelf(Accounts)第二,不要重新定义内置函数。在Deposit()中,将raw_input的结果赋值给一个名为input的变量
input = raw_input('\nEnter the A/c type: ')四行之后,您尝试使用内置的input函数:
amt = input('\nAmount of Deposit: ')但是这是行不通的,因为input已经被重新定义了!
第三,当迭代被搁置的项目时,遵循以下模式: 1)抓取搁置项目;2)变异项目;3)将突变项写回货架。就像这样:
for key, acct in Accounts.iteritems(): # grab a shelved item
if val['Acctype'].find(input) != -1:
amt = input('\nAmount of Deposit: ')
flag+=1
acct['Deposit'] += amt # mutate the item
Accounts[key] = acct # write item back to shelf(这第三条建议是从hughdbrown的回答中提炼出来的。)
发布于 2010-10-25 19:07:55
我想你会有更多这样的运气
for key, val in Accounts.iteritems():
if val['Acctype'].find(input) != -1:
amt = input('\nAmount of Deposit: ')
flag+=1
val['Deposit'] += amt
Accounts[key] = valhttps://stackoverflow.com/questions/4017733
复制相似问题