Def function and variables question


#1

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

vs

def rental_car_cost(days):
cost = days * 40

40%20PM|294x500


#2

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.


Aside

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))
25
>>> foo
<function foo at 0x02E05DB0>
>>> foo = foo(5)
>>> print (foo)
25
>>> foo
25
>>> 

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.


#3

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