在python中处理一个场景,要求我显示名称和价格(从高到低),最便宜的商品是免费的,

e7arh2l6  于 2021-09-08  发布在  Java
关注(0)|答案(1)|浏览(292)

这就是我所看到的场景,我正在努力完成它,因为我在python方面没有太多的经验
“你必须为网上商店交易创建一个程序,如果客户购买五件商品,他们将获得第五件免费商品。该程序应考虑五种产品及其成本,然后按价格(从高到低)显示它们。然后,它应计算扣除最便宜物品的总成本,并显示欠款总额。”
这是我目前的代码:

def products():
    for counter in range(5):
        product_name = input("Please enter product name:")
        product_price = float(input("Please enter product price:"))
        return

def sort(product_price):
    product_price = sorted(product_price, reverse=True)
    print(product_price)

products()
sort(product_price)

如果有人能帮我做这件事,那将意义重大

okxuctiv

okxuctiv1#

首先,在函数内部创建变量,然后尝试在函数外部访问它们,这在python中是不起作用的。而且,对于这么短的一些东西,函数对我来说似乎有点不必要。试着这样做:


# Create an empty list

items = []

# Get user input for 5 items

for _ in range(0, 5):
    name = input("Item name: ")
    price = float(input("Item price: "))
    items.append({
        "name": name,
        "price": price
    })

# Sort the items by price in reverse

sorted_items = sorted(items, key=lambda k: k["price"], reverse=True)

# Calculate total of 4 most expensive items

total_cost = 0
for index in range(0, 4):
    total_cost += sorted_items[index]["price"]

# Print the total

print(total_cost)

有很多方法可以解决这个问题,但使用一系列字典对我很有吸引力。希望这有意义!我将把价格和小数的四舍五入留给你来打印。

相关问题