Transportation - local variable referenced before assignment


#1

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’?


#2

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.


#3

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


#4

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

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

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

n=6
def f():
  if n<5:
    v=1
  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.


#6

Thank you! This helps!


#7

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