如何获取用户输入以引用字典Python

时间:2016-05-02 16:49:50

标签: python dictionary

我在尝试Python任务时遇到了一些麻烦。在作业中,我需要为杂货店创建一个信用计划。这很容易,我在上一部分遇到麻烦。因此,我们需要3个用户输入来决定他们想要购买的商品。有了这些输入,我需要把这个人输入的内容转换成一个价格。另外,我一直在使用print('''''')来跳过线路,我找到了几种方法来解决这个问题,但是对于正确的方法并不确定。

到目前为止,这是我的任务:

prices = {}  

aa = 5.  
bb = 4.  
cc = 10.  
dd = 3.  
ee = 5.  
ff = 4.  

prices[aa] = 'shrimp'
prices[bb] = 'groundbeef'
prices[cc] = 'tuna'
prices[dd] = 'sodapop'
prices[ee] = 'fruitplate'
prices[ff] = 'spicerack'

print("Hello and welcome to Lakeside Market:") #generic greeting

print('''''') #skip line

deposit = input("How much would you like to deposit into your account?")      #asks for a amount to deposit

print('''''') #skip line

deposit = int(deposit) #makes deposit variable an integer # turns deposit into an integer

bonus = 10 #creates $10 bonus if $20+ is taken from input

accountbalance = deposit + bonus # will be used when the user has entered a correct deposit amount

if deposit < 20: #basic if/else statement. If you put less than 20 it will tell you

    print("I'm sorry that doesn't meet the minimum requirement of $20")

    exit()

else: #if 20+ is entered

    print("Thank you, your funds have been deposited into your account.")

    print('''''') 

    print("Your balance is $",accountbalance) #balance is printed with first-time bonus of 10 added

    print('''''')

    print("We offer: shrimp, groundbeef, tuna, sodapop, fruitplate and spicerack") # here are the different items that can be input
    print("Please enter items as they appear above...") #item1 input

    print('''''')

    item1 = input("To begin, please enter an item name:") #item2 input

    item2 = input("Now, add a second item:")

    item3 = input("Finally, add your last item:") #item3 input

要完成分配,我需要将用户输入结束(item1item2item3)到{{1}的项目的实际价格中dict。然后我会添加这些项目,并从prices中减去该金额,这将为我提供帐户的新总额。我知道这是非常基本的东西,但我对Python很新,这是我必须采取的第一个实际课程。感谢您的时间和提前回复

1 个答案:

答案 0 :(得分:3)

您可能希望以不同方式组织商品和价格,原因有两个。第一个,正如@ rajah9指出的那样,当使用价格作为您的钥匙时,您将无法将多个商品映射到相同的价格:

prices = {}
prices[1] = 'apple'
print prices[1]
''' output '''
'apple'

prices[1] = 'orange'
print prices[1]
''' output '''
'orange'

其次,您可能希望轻松访问特定商品的价格。如果您使用价格作为密钥,这将更加困难。如果您将项目设置为关键字段并将价格设置为字典中的值,则可以通过调用prices[item]来访问每个项目的价格。

prices = {}  

aa = 5.  
bb = 4.  
cc = 10.  
dd = 3.  
ee = 5.  
ff = 4.  

prices['shrimp'] = aa
prices['groundbeef'] = bb
prices['tuna'] = cc
prices['sodapop'] = dd
prices['fruitplate'] = ee
prices['spicerack'] = ff

# other stuff here ...

item1 = input("To begin, please enter an item name:") #item2 input

price1 = prices[item1]

item2 = input("Now, add a second item:")

price2 = prices[item2]

item3 = input("Finally, add your last item:") #item3 input

price3 = prices[item3]