gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:56:25 24 4
gpt4 key购买 nike

我在尝试执行 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)转换为实际价格prices 字典中的项目。然后,我会将这些项目相加,并从 accountbalance 中减去该金额,这将为我提供帐户的新总计。我知道这是非常基础的东西,但我对 Python 很陌生,这是我必须参加的第一堂实际类(class)。感谢您的宝贵时间和提前回复

最佳答案

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

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

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

其次,您可能希望轻松访问给定商品的价格。如果您使用价格作为 key ,这会困难得多。如果您将商品设置为字典中的键,将价格设置为字典中的值,则可以通过调用 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]

关于python - 如何获取用户输入以引用Python字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36987522/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com