我想添加一个接受权重和输出成本的def函数,但我不知道如何使用if elif循环
weight = float(input("Enter package weight: ")) #package weight
cost_ground_premium = 125.00 #flat charge for premium
if weight <= 2: #package weighs 2 lb or less
  cost_ground = weight * 1.50 + 20 # $1.50/lb, flat charge of $20
elif weight <= 6: #over 2lb but less/equal to 6lb
  cost_ground = weight * 3.00 + 20 # $3/lb + flat charge
elif weight <= 10: #over 6lb but less/equal to 10lb
  cost_ground = weight * 4.00 + 20 # $4/lb + flat charge
else: #over 10lb
  cost_ground = weight * 4.75 + 20 # $4.75/lb + flat charge
print("Ground Shipping $", round(cost_ground, 2))
print("Ground Shipping Premium $", round(cost_ground_premium, 2))
drone_weight = float(input("Enter package weight if using Drone Shipping: "))
if drone_weight <= 2: # $4.50/lb. No flat charge
  cost_drone = drone_weight * 4.50 #no flat charge
elif drone_weight <= 6: # $9/lb 
  cost_drone = drone_weight * 9.00
elif drone_weight <= 10: # $12/lb
  cost_drone = drone_weight * 12.00
else: # $14.25/lb
  cost_drone = drone_weight * 14.25
print("Drone Shipping $", round(cost_drone, 2))发布于 2021-11-18 19:18:58
您需要将cost_ground和cost_drone从if和elif块中删除。下面我将为你的代码编写函数和循环。
def func(weight, drone_weight):
    cost_ground = None
    cost_drone = None
    cost_ground_premium = 125.00 #flat charge for premium
    if weight <= 2: #package weighs 2 lb or less
        cost_ground = weight * 1.50 + 20 # $1.50/lb, flat charge of $20
    elif weight <= 6: #over 2lb but less/equal to 6lb
        cost_ground = weight * 3.00 + 20 # $3/lb + flat charge
    elif weight <= 10: #over 6lb but less/equal to 10lb
        cost_ground = weight * 4.00 + 20 # $4/lb + flat charge
    else: #over 10lb
        cost_ground = weight * 4.75 + 20 # $4.75/lb + flat charge
    if drone_weight <= 2: # $4.50/lb. No flat charge
        cost_drone = drone_weight * 4.50 #no flat charge
    elif drone_weight <= 6: # $9/lb 
        cost_drone = drone_weight * 9.00
    elif drone_weight <= 10: # $12/lb
        cost_drone = drone_weight * 12.00
    else: # $14.25/lb
        cost_drone = drone_weight * 14.25
    return (round(cost_ground, 2), round(cost_drone, 2), cost_ground_premium)
while 1:
    weight = float(input("Enter package weight: ")) #package weight
    if weight == 0:
        break
    
    drone_weight = float(input("Enter package weight if using Drone Shipping: "))
    cost_ground, cost_drone, cost_ground_premium = func(weight, drone_weight)
    print("Ground Shipping $", cost_ground)
    print("Ground Shipping Premium $", cost_ground_premium)
    print("Drone Shipping $", cost_drone)https://stackoverflow.com/questions/70025346
复制相似问题