Medical Insurance Project - name error

So frustrated today. Can someone please explain how I have NOT DEFINED insurance_cost outside of the function after I have returned it?

#here’s my code
def calculate_insurance_cost(age = 28,sex = 0,bmi = 26.2,num_of_children = 3,smoker = 0):

insurance_cost = 250age - 128sex + 370bmi + 425num_of_children + 24000*smoker - 12500

return insurance_cost

print(“The estimated insurance cost for Maria is " + str(insurance_cost) + " dollars.”)

and it returns:

Traceback (most recent call last):
File “”, line 5, in
print(“The estimated insurance cost for Maria is " + str(insurance_cost) + " dollars.”)
NameError: name ‘insurance_cost’ is not defined

Thanks for the help!

Welcome to the forums!

You’ve defined insurance_cost as a variable inside the calculate_insurance_cost() function. This means that it is only accessible inside of that function. Remember that a variable is only accessible within its scope (which could be within a function, globally, etc.) and cannot be accessed outside of its scope.

Yes, you return insurance_cost, but this does not make it accessible outside of the function. This simply returns the value stored in insurance_cost to the function call. It seems that you need to review return statements and functions in general; I recommend you go back to those lessons to gain a better understanding of these concepts. This is another resource (you should still be reviewing the lessons on functions even after reading this) that explains return.

When you return insurance_cost, you are passing its value back to the call to the function.

def foo():
  return "bar"

foo() # this is a function call
print(foo()) # calls foo() and prints "bar", the value returned from it

With this new understanding of functions and return statements, how could you print out insurance_cost outside of the calculate_insurance_cost() function?

Note: please format your code using the </> button to preserve indentation in future posts.


Thanks, I properly understand the use of return and had no problem finishing the project after that :slight_smile:

1 Like