Transportation - local variable referenced before assignment


def rental_car_cost(days):
if days >=7:
cost = days40 - 50
elif days >=3:
cost = days
40 - 20
return cost

Why does it throw an error that ‘local variable “cost” referenced before assignment’?


return cost

you are returning cost without assigning a value to it.

for example:
if you call the rental_car_cost(2) function with the argument then it’ll give the error as the compiler doesn’t know the value of cost.
you are returning the local variable cost without giving a value to it in the scope.


Aren’t we giving a value to Cost when we say cost = days*40 - 50?


yes,you are giving but i don’t see the line of code in your posted code.

also if you give the value to cost inside if or else statement then it’ll only assign the value to it when the condition will be True.

here is a simple example

def f():
  if n<5:
  return v
print f()

it’ll return the value of v.what if you change the value of n…

def f():
  if n<5:
  return v
print f()

you’ll get an error

Error: UnboundLocalError: local variable ‘v’ referenced before assignment

it skips the line(v=1) because the condition is not True.


Thank you! This helps!


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.