首页 > 解决方案 > 如何添加具有多个变量的多个 if 条件

问题描述

我刚开始使用 pycharm 学习编码。所以一切对我来说都是新的。我必须编写几个简单易行的程序,其中我已经编写过并且只是坚持使用这个程序。

问题:设计一个程序来计算代表 JCU 布里斯班体育俱乐部的 3 名新板球运动员的设备总成本。新物品如下: - 每个新玩家都会获得护膝和击球手套。- 用户将被询问每位新玩家的 T 恤尺寸,并在此基础上将 T 恤价格添加到总价格中。- 此外,球队还获得 3 个新板球和 5 个新球棒。

板球每个售价 20 美元,球棒 45 美元,护膝 70 美元,一副击球手套售价 130 美元。T 恤尺码为 S(45 美元)、M(55 美元)、L(65 美元)和 XL(75 美元)。

该程序应返回设备的总成本。

我无法做的是如何为每个特定玩家定义每个特定尺寸的价值。我是新手,卡住了。如果有人可以帮忙请。

这是我到目前为止所做的:

# practise for coding challenge


psize = input("enter the size of the player1(s/m/l/xl): ")
#psize2 = input("enter the size of the player:")

cricBall = 20
cricBat = 45
kPad = 70
batGlove = 130
tsmall = 45
tmed = 55
tlar = 65
txl = 75

if psize == "s":
    total = (3 * kPad) + (3 * batGlove) + 45 + (3 * cricBall) + (5 * cricBat)
    print("The total cost of equipment is:", total)
if psize == "m":
    total = (3 * kPad) + (3 * batGlove) + 55 + (3 * cricBall) + (5 * cricBat)
    print("The total cost of equipment is:", total)
if psize == "l":
    total = (3 * kPad) + (3 * batGlove) + 65 + (3 * cricBall) + (5 * cricBat)
    print("The total cost of equipment is:", total)
if psize == "xl":
    total = (3 * kPad) + (3 * batGlove) + 75 + (3 * cricBall) + (5 * cricBat)
    print("The total cost of equipment is:", total)

标签: pythonvariablesif-statement

解决方案


你已经有了一个好的开始。我宁愿不提供任何代码,因为您可以通过自己的帮助来了解更多信息。但是,如果您真的无法弄清楚,我可以稍后添加它。

首先if-statements,您可以使用不同的而不是使用if, elif and perhaps an else-statement. 就像下面的假代码:

if statement:
  do this
elif statement:
  do this
elif statement:
  do this
else:
  do this

至于您的问题:您已经预定义了每种尺寸的价格,并根据输入打印了一个变量。您所要做的就是将每个尺寸添加到total正确的语句中。例如,在下面的代码中,我们添加价格:

if psize == "s":
    total = (3 * kPad) + (3 * batGlove) + 45 + (3 * cricBall) + (5 * cricBat) + tsmall
    print("The total cost of equipment is:", total)

现在以类似的方式处理其他语句。不过还有一件事:由于您在 each 中执行相同的操作if-statement,因此您可以在这些语句之前执行此操作。像这样:

total = (3 * kPad) + (3 * batGlove) + 45 + (3 * cricBall) + (5 * cricBat)
if psize == "s":
        total = total + tsmall
        print("The total cost of equipment is:", total)

再一次:对其他语句做同样的事情。

下面评论的解决方法:

#calculate base price
total = 3 * (kPad + batGlove + cricBall) + 45 + 5*cricBat
#Loop three times, ask for an input and add the price per input to total
count = 0;
while count < 3:
  #ask for input here
  #add size-based price to total (with the if-statements)
  count += 1
#exit loop and print the result

推荐阅读