Def function and variables question


I do not quite understand the difference between the two codes I have attached. specifically the difference between
def rental_car_cost(days):
rental_car_cost = days * 40


def rental_car_cost(days):
cost = days * 40



The second is the more appropriate diction for this exercise. assuming the block is indented.

The first example creates confusion for the reader by using the name of the function as the variable name. Simple variable names that carry meaning are favorable.

Bottom line, though, as long as it works the subjective differences can be ignored.


Be careful how you name variables in global (or same) scope. While we can use a variable name the same as that of the function within the scope of the function, we cannot do so in the same scope as the function. Eg.

>>> def foo(bar):
	foo = bar * 5
	return foo

>>> print (foo(5))
>>> foo
<function foo at 0x02E05DB0>
>>> foo = foo(5)
>>> print (foo)
>>> foo

Notice that global variable replaced the function object with a numeric. The function no longer exists. Something to always keep in mind. For safety, treat function names as reserved words. The same could be said for data structures that may be needed at a future time. Keep them safe, too.


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