这是我到目前为止的代码:
def convertWeight():
(totalWeight * 0.45359237)
def getRate():
if totalWeight <= 2:
rate = totalWeight * 1.10
elif totalWeight > 2 and totalWeight <= 6:
rate = totalWeight * 2.20
elif totalWeight > 6 and totalWeight <= 10:
rate = totalWeight * 3.70
elif totalWeight > 10:
rate = totalWeight * 4.20
numBoxes = int(input('Please enter the number of boxes: '))
unit = input('Please enter the unit of measurement, Imperial or Metric (as I or M): ')
while unit != 'I' or 'M' or 'i' or 'm':
unit = input('Please enter the unit of measurement again, Imperial or Metric (as I or M): ')
while unit == 'I' or 'M' or 'i' or 'm':
for x in range(numBoxes):
weight = float(input('Please enter the weight of the boxes: '))
totalWeight = 0
totalWeight = totalWeight + weight
if unit == 'M':
totalWeight = convertWeight
else:
totalWeight = totalWeight
getRate(totalWeight)
transportCost = getRate * totalWeight
print('The number of boxes is {0}, the total weight is {1:.2f}, and the transport cost is {2:,}.' .format(numBoxes, totalWeight, transportCost))
如何首先循环单位输入,直到输入I,i,M或m,然后打破循环并继续? 另外,我如何计算运输成本,即从创建的函数中获取速率,然后按totalWeight计算它?
谢谢大家。
答案 0 :(得分:0)
这个程序有很多问题。首先,你的第二个while循环没有任何意义,导致额外的问题,因为现在你必须打破它。其次,您在for循环的每次迭代中重置totalweight
。第三,您试图致电convertWeight()
,而是将totalweight
设置为等于它。第四,你尝试调用getRate()
,但是因为你离开了()
你的程序会尝试将它作为一个变量而不是一个函数进行评估并抛出一个错误。第五,totalWeight
不在函数范围内,这意味着你必须将它作为参数传递。第六,检查正确输入的while循环不能按预期工作。它将评估是否unit != 'I'
然后它将评估'M'
是否为True
,它是什么。您的while循环将始终评估为True。第七,对于公制,您在循环的每次迭代中转换权重,然后在下一个循环中向其添加英制,然后再次转换它。这会给你错误的答案。将你的if语句移到for循环之外并删除else,因为它什么都不做。最后,convertWeight()
和getRate()
基本上什么都不做,因为你没有返回任何东西。你可以像这样解决它。
def convertWeight(totalWeight):
return (totalWeight * 0.45359237)
def getRate(totalWeight):
if totalWeight <= 2:
rate = totalWeight * 1.10
elif totalWeight > 2 and totalWeight <= 6:
rate = totalWeight * 2.20
elif totalWeight > 6 and totalWeight <= 10:
rate = totalWeight * 3.70
elif totalWeight > 10:
rate = totalWeight * 4.20
return rate
numBoxes = int(input('Please enter the number of boxes: '))
unit = input('Please enter the unit of measurement, Imperial or Metric (as I or M): ')
while unit not in ['I','M','i','m']:
unit = input('Please enter the unit of measurement again, Imperial or Metric (as I or M): ')
totalWeight = 0
for x in range(numBoxes):
totalWeight += float(input('Please enter the weight of the boxes: '))
if unit == 'M':
totalWeight = convertWeight(totalWeight)
transportCost = getRate(totalWeight) * totalWeight
print('The number of boxes is {0}, the total weight is {1:.2f}, and the transport cost is {2:,}.' .format(numBoxes, totalWeight, transportCost))