python - 如何添加具有多个变量的多个 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)
解决方案
你已经有了一个好的开始。我宁愿不提供任何代码,因为您可以通过自己的帮助来了解更多信息。但是,如果您真的无法弄清楚,我可以稍后添加它。
首先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
推荐阅读
- android - 在 Android 中使用 Hilt 后无法创建视图模型实例
- arrays - Laravel collect($array)->sortBy($value)->values() 显示在屏幕上
- python - 数据框中的向量化字符串搜索
- r - 改进 R 中的现有循环和延迟
- java - 用坐标、长度、宽度和角度计算矩形的中心
- python - 如何将 arg 从命令传递到子命令 Discord py
- c# - 将文件上传到 Blob 存储错误 get_NetworkTimeout 没有实现
- typoscript - Typo3:语言没有 isoCodeA2
- pyparsing - 将文本“DA23.3445 DC15.445”解析为 [“DA”、“23.3445”、“DC”、“15.445”]
- python - matplotlib 中未定义 ax