我正在尝试创建代码,以计算两种不同产品尺寸之间的更好价值
(例如,每10克黄油10美元,每20克黄油15美元)
现在,我只知道如何收集信息,但是我对如何显示与其他产品相比具有更好的价值,更差的价值或同等价值的物品一无所知。 到目前为止,这是我的代码:
a = int(input('Cost of first product($): '))
b = int(input('Cost of second product($): '))
c = int(input('Mass of first product(grams): '))
d = int(input('Mass of second product(grams): '))
谢谢!
答案 0 :(得分:2)
这是代码的最后一部分,将显示结果:
s = (a/c)
r = (b/d)
if (s>r):
print('Product two is better value at', r,'$/g.')
elif (s<r):
print('Product one is better value at', s,'$/g.')
else:
print('These products are the same value.')
因此,总的来说,您的代码应如下所示:
a = int(input('Cost of first product($): '))
b = int(input('Cost of second product($): '))
c = int(input('Mass of first product(grams): '))
d = int(input('Mass of second product(grams): '))
s = (a/c)
r = (b/d)
if (s>r):
print('Product two is better value at', r,'$/g.')
elif (s<r):
print('Product one is better value at', s,'$/g.')
else:
print('These products are the same value.')
答案 1 :(得分:1)
您需要比较比率price/mass
if (a / c) < (b / d):
print("first product better")
else:
print("first product better")
要概括这个想法,您可以将成对的price-mass
保存在数组中,然后找出其中的最小值
nb = 3
products = []
for i in range(nb):
price = int(input(f'Cost of product n°{i + 1}($): '))
mass = int(input(f'Mass of product n°{i + 1} ($): '))
products.append((price, mass))
better = min(products, key=lambda pm: pm[0] / pm[1]) # pm is tuple price-mass
print(better)
答案 2 :(得分:0)
使用+-%/进行计算,例如python一切皆有可能:
result = ((a + b) / 12 ) * 20 #.... Whatever you want to calculate
要打印供用户使用的东西:
print(f" text to display {vriable_to_display}")
也许最好阅读一些文档并对变量进行简单的练习,然后再跳回到该练习
祝你好运
答案 3 :(得分:0)
当您拥有具有多个属性的特定事物时,通常将其作为元组中的一组值进行跟踪比作为多个变量来进行跟踪更为容易,如果使用NamedTuple
(甚至可以更容易)您为每个名称都赋予了一个值,因此您无需按它们出现的顺序来跟踪它们。)
类似地,当您要跟踪多个事物时,在集合(通常是列表,有时是字典)中跟踪它们比较容易。
from typing import NamedTuple
class Product(NamedTuple):
"""Data about a particular product."""
name: str
cost: float # cost in dollars
mass: float # mass in grams
# Get a list of products to compare.
products = [
Product(
str(i+1),
float(input(f"Cost of product {i+1} ($): ")),
float(input(f"Mass of product {i+1} (g): ")),
)
for i in range(int(input("How many products do you want to compare? ")))
]
# Sort by cost per mass ratio and print results.
products.sort(key=lambda p: p.cost / p.mass)
for p in products:
print(f"{p.name}: ${p.cost} for {p.mass}g = ${p.cost/p.mass:.2f}/g")
答案 4 :(得分:0)
您也可以只做:
a = int(input('Cost of first product($): '))
b = int(input('Cost of second product($): '))
c = int(input('Mass of first product(grams): '))
d = int(input('Mass of second product(grams): '))
if ((a/c) > (b/d)):
print('Product 1 has better value at', (b/d), '$/g.')
elif ((a/c) < (b/d)):
print('Product 2 has better value at', (a/c), '$/g.')
else:
print('Both these products have the same value.')