f=open('food.dat','w+')
rates=0
rate=0
print"Menu is:"
print""" 1.Starters
2.Main Courses
3.Snacks
4.Drinks
5.Desserts"""
hotel_food1={1:'Starters',
2:'Main Courses',
3:'Snacks',
4:'Drinks',
5:'Desserts'}
while True:
food=input("Enter the food type:")
if(hotel_food1.has_key(food)==1):
print"Menu is:"
print"""1.Salmon Devilled Eggs
2.Baked Parika Cheese
3.Ricotta and Parmesan Fritters
4.Traditional Welsh Cawl
5.Summer Ratatouille Salad"""
hotel_starter={1:'Salmon Devilled Eggs',
2:'Baked Parika Cheese',
3:'Ricotta and Parmesan Fritters',
4:'Traditional Welsh Cawl',
5:'Summer Ratatouille Salad'}
fd=input("ENter the food type")
if(hotel_starter.has_key(fd)==1):
rate=rate+234
elif(hotel_starter.has_key(fd)==2):
rate=rate+345
elif(hotel_starter.has_key(fd)==3):
rate=rate+200
elif(hotel_starter.has_key(fd)==4):
rate=rate+110
elif(hotel_starter.has_key(fd)==5):
rate=rate+334
ch=raw_input("Do you want to continue? yes/no??")
if(ch=='no'):
break
rates=rates+rate
f.write(str(rates))
f.seek(0,0)
x=f.read()
print x
f.close()
你好,在上面的程序中,当我给食物的输入为1而fd为1时,我必须得到值234打印。但是当我运行程序时,我得到的值为0.是否有缩进的错误?字典是否正确实现?请帮忙!谢谢!
答案 0 :(得分:0)
has_key
返回布尔值,即==1
,因此只要用户输入字典中存在的键,第一个测试将始终评估为真,因为has_key(fd)
== True和True == 1
。所以你需要修改你的逻辑。
我认为你这样做是错误的,因为当你可以通过嵌套字典来更恰当地处理这个问题时,它会快速转入if / elif / else语句的意大利面条代码。这也有助于提高可读性。
您可以正确地初始化和嵌套词典,并将费率作为词典的一部分。这只是一个例子:
hotel_starters = {1:{'item':'Salmon Devilled Eggs', 'rate':234},
2:{'item':'Baked Parika Cheese', 'rate':345},
3:{'item':'Ricotta and Parmesan Fritters', 'rate':'456'}
}
hotel_main_courses = {1:{'item':'Filet Mignon', 'rate':678},
2:{'item':'Vegetarian Lasagna', 'rate':567},
3:{'item':'Halibut', 'rate':'890'}
}
hotel_menu = {1:hotel_starters,
2: hotel_main_courses}
使用这种数据结构,您可以轻松地按键查询:
hotel_menu[1] # returns the entire 'hotel_starters' dictionary
hotel_menu[1][1] # returns the dictionary for hotel_starters[1]
hotel_menu[1][1]['rate'] # returns the rate associated with that item, etc.
此外,打印菜单:
for k, v in hotel_menu['starters'].items():
print k, v['item'], v['rate']
所以在一个例子中你可以这样做:
# initialize your menu dictionaries
hotel_starters = {1:{'item':'Salmon Devilled Eggs', 'rate':234},
2:{'item':'Baked Parika Cheese', 'rate':345},
3:{'item':'Ricotta and Parmesan Fritters', 'rate':'456'}
}
hotel_main_courses = {1:{'item':'Filet Mignon', 'rate':678},
2:{'item':'Vegetarian Lasagna', 'rate':567},
3:{'item':'Halibut', 'rate':'890'}
}
hotel_menu = {1:hotel_starters,
2: hotel_main_courses}
rates=0
menu = input('1 for starters, 2 for main courses:')
if menu in hotel_menu:
print 'menu is:\n'
for k, v in hotel_menu[menu].items():
print k, v['item'], v['rate']
food = input('enter your food item:\n')
if food in hotel_menu[menu]:
rates += hotel_menu[menu][food]['rate']