大家好,我是绝对的初学者,我需要为我的课程创建简单的数据库。 我正在尝试修改我们收到的示例代码,但是有很多可能性,我迷失了它。
我的想法是,我可以添加/删除数量和价格的产品。 在修改列表中已有的产品数量时,我感到困惑。
我有以下代码用于输入并显示列表功能。
def entry():
global base
name=raw_input('Name of the product: ')
quantity=raw_input('Quantity: ')
price=raw_input('Price per unit: ')
if name not in base.keys():
base[name]=[int(quantity),int(price)
print "Saved."
elif name in base.keys():
首先给出[name]
超过1的值的问题,我可以稍后打印,但我认为这是不正确的..
def articles():
global base
print 'List of articles in magazine'.center(50)
print '-'*50
print '|'+'name'.center(15)+'|'+'Quantity'.center(15)+'|'+'Price'.center(15)+'|'
print '-'*50
for name,quantity in base.items():
print "|%14s |" % name,'%13s' % quantity[0],'|' '%13s' % quantity[1],'|' </code> ### When I use here price instead of quantity[1] it shows error.
答案 0 :(得分:0)
也许这个例子可以帮助你重构代码?
import shelve
global base
global magazine_base
def load_data():
global base
global magazine_base
magazine_base = shelve.open('magazine_base')
if magazine_base.has_key('base'):
base = magazine_base['base']
if not base:
base = [{'name': 'Apple', 'price': 10, 'quantity': 1}] # example one element base
# base = [] # it can be also just empty list at the beginning
else:
base = [{'name': 'Apple', 'price': 10, 'quantity': 1}]
# base = []
magazine_base['base'] = base
def entry():
global base
global magazine_base
load_data()
name = raw_input('Name of the product: ')
quantity = raw_input('Quantity: ')
price = raw_input('Price per unit: ')
is_new_entry = True
# entry is element of base list
for entry in base:
if name.lower() == entry['name'].lower(): # checking if name already exist in base list
is_new_entry = False
if is_new_entry: # adding new list element
base += [{
'name': name,
'quantity': int(quantity),
'price': float(price)
}]
magazine_base['base'] = base
magazine_base.close()
print 'Saved.' # confirmation message
else:
print 'Element with the name {} already exist!'.format(name) # error message
magazine_base.close()
def articles():
global base
print 'List of articles in magazine'.center(50)
print '-'*50
print '|'+'Name'.center(15)+'|'+'Quantity'.center(15)+'|'+'Price'.center(15)+'|'
print '-'*50
for entry in base:
print "|%14s |" % entry['name'],'%13s' % entry['quantity'],'|' '%14s' % entry['price'],'|'
print '-'*50
# testing by running functions
entry()
articles()
entry()
articles()
使用shelve
进行了更新。
检查了你,它工作正常。
希望这有帮助。