@Rupertus

Как понять ошибку в коде Python (local variable 'cost' referenced before assignment)?

Здравствуйте! Я новичок в программировании, прохожу курс на Codecademy, написал простенькую программу по заданию, при значениях weight до 10 она нормально работает, ставлю выше, выдает ошибку, никак не могу понять, в чем она заключается. Помогите, пожалуйста. Благодарен за помощь!

def ground_shipping(weight):
  if weight <= 2.00:
    cost = 20.00 + 1.50 * weight
  elif weight > 2.00 and weight <= 6.00:
    cost = 20.00 + 3.00 * weight
  elif weight > 6.00 and weight <= 10.00:
    cost = 20.00 + 4.00 * weight
  else:
    сost = 20.00 + 4.75 * weight
  return cost

pgs_cost = 125.00

def drone_shipping(weight):
  if weight <= 2:
    cost = 4.50 * weight
  elif weight > 2 and weight <= 6:
    cost = 9.00 * weight
  elif weight > 6 and weight <= 10:
    cost = 12.00 * weight
  else:
    cost = 14.25 * weight
  return cost

def cheapest_shipping(weight):
  if ground_shipping(weight) < drone_shipping(weight) and ground_shipping(weight) < pgs_cost:
    return "You should ship using ground shipping. It will cost $" + str(ground_shipping(weight))
  
  elif drone_shipping(weight) < ground_shipping(weight) and drone_shipping(weight) < pgs_cost:
    return "You should ship using drone shipping. It will cost $" + str(drone_shipping(weight))
  
  else:
    return "You should using premium ground shipping. It will cost $125.00"

print(cheapest_shipping(5))
print(cheapest_shipping(10))
print(cheapest_shipping(41.5))

Результат:
You should ship using ground shipping. It will cost $35.0
You should ship using ground shipping. It will cost $60.0
Traceback (most recent call last):
  File "script.py", line 37, in <module>
    print(cheapest_shipping(41.5))
  File "script.py", line 26, in cheapest_shipping
    if ground_shipping(weight) < drone_shipping(weight) and ground_shipping(weight) < pgs_cost:
  File "script.py", line 10, in ground_shipping
    return cost
UnboundLocalError: local variable 'cost' referenced before assignment
  • Вопрос задан
  • 28991 просмотр
Решения вопроса 2
sergey-gornostaev
@sergey-gornostaev Куратор тега Python
Седой и строгий
Понять так, что к переменной обращение происходит раньше, чем её присваивание. То, что столь простая ошибка ставит вас в тупик - является прекрасным показателем того, на сколько курс Codecademy хуже учебника.
Ответ написан
Mi11er
@Mi11er
A human...
Кстати, ошибка смешная =)
В целом у вас все ок.
Но сама ошибка, говорит о том, что переменная еще не определна, значит косяк в условии else

Нооо... И там вроде все ок, кроме одного, что в функции ground_shipping , в условии else возвращается не cost =)))
а сost =)
Чувствуете разницу ?)
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы