我对编码非常陌生,我正在尝试创建一个包含商品和价格的商店列表。 也就是说,一旦键入所有项目,该函数应计算总和并在您超出预算时停止。 所以我写了类似的东西:
def shoplist():
list={"apple":30, "orange":20, "milk":60......}
buy=str(input("What do you want to purchase?")
If buy in list:
While sum<=budget:
sum=sum+??
shoplist ()
我真的不知道如何将项目的输入与列表中的价格相匹配...... 我的第一个想法是使用'if',但当你在列表中有超过10个项目和随机输入时,这有点不切实际。 我迫切需要帮助......所以任何建议都会很好! (或者如果你有一个更好的解决方案,并认为我用这种方式写它是完全垃圾......请让我知道那些更好的解决方案是什么
答案 0 :(得分:1)
您发布的代码不会在python中运行。 list
是一个内置函数,不应该用于变量名,因为它引用了一个dict对象,所以它会引起双重困惑。 input()
已经返回一个str,因此强制转换没有效果。 if
和while
应该是小写的,并且没有缩进,因此我们无法知道这些语句的限制。
有太多错误,请看一下:
def shoplist(budget):
prices = {"apple":30, "orange":20, "milk":60}
# Initialise sum
sum = 0
while sum <= budget:
buy = input("What do you want to purchase?")
# Break out of the loop if the user hts <RETURN>
if not buy: break
if buy in prices:
sum += prices[buy] # This gets the price
else:
print("Invalid item", buy)
shoplist(142)
那我改变了什么?预算必须来自某个地方,所以我把它作为一个参数传递(142,我做了这个)。我将总和初始化为零,然后将while
循环移到外面。
注意很多空格 - 它使代码更容易阅读,对性能没有影响。
要做出很多改进。应向用户显示可能的项目和价格列表,以及每次购买剩余的预算。另请注意,可以超出预算,因为我们可能只有30个预算,但我们仍然可以购买牛奶(60个) - 我们需要另一个检查(if
声明)在那里!
我会把改进留给你。玩得开心!
答案 1 :(得分:0)
以此为例:
# this is a dictionary not a list
# be careful not using python reserved names as variable names
groceries = {
"apple":30,
"orange":20,
"milk":60
}
expenses = 0
budget = 100
cart = []
# while statements, as well as if statements are in lower letter
while expenses < budget:
# input always returns str, no need to cast
user_input = input("What do you want to purchase?")
if user_input not in groceries.keys():
print(f'{user_input} is not available!')
continue
if groceries[user_input] > budget - expenses:
print('You do not have enough budget to buy this')
user_input = input("Are you done shopping?Type 'y' if you are.")
if user_input == 'y':
break
continue
cart.append(user_input)
# this is how you add a number to anotherone
expenses += groceries[user_input]
print("Shopping cart full. You bought {} items and have {} left in your budget.".format(len(cart), budget-expenses))
答案 2 :(得分:0)
我已对您的代码进行了一些更改以使其正常工作,并解释说明包括使用#
符号指示的注释。
最重要的两件事是所有括号都需要关闭:
fun((x, y) # broken
fun((x, y)) # not broken
和Python中的关键字都是小写的:
if, while, for, not # will work
If, While, For, Not # won't work
您可能会对True
和False
感到困惑,这可能应该是小写的。他们已经这么久了,现在改变它们为时已晚。
budget = 100 # You need to initialize variables before using them.
def shoplist():
prices = { # I re-named the price list from list to prices
'apple' : 30, # because list is a reserved keyword. You should only
'orange' : 20, # use the list keyword to initialize list objects.
'milk' : 60, # This type of object is called a dictionary.
} # The dots .... would have caused an error.
# In most programming languages, you need to close all braces ().
# I've renamed buy to item to make it clearer what that variable represents.
item = input('What do you want to purchase? ')
# Also, you don't need to cast the value of input to str;
# it's already a str.
if item in prices:
# If you need an int, you do have to cast from string to int.
count = int(input('How many? '))
cost = count*prices[item] # Access dictionary items using [].
if cost > budget:
print('You can\'t afford that many!')
else:
# You can put data into strings using the % symbol like so:
print('That\'ll be %i.' % cost) # Here %i indicates an int.
else:
print('We don\'t have %s in stock.' % item) # Here %s means str.
shoplist()
许多初学者在StackOverflow上发布了破坏的代码而没有说他们会得到错误或者错误是什么。发布错误消息总是有帮助的。如果您有更多问题,请与我们联系。