Transportation, introducing a new variable?


In the Transportation problem we have to find the cost of renting a car per day. The argument is days. So instead of using days as the stand-in for cost we introduce what I assume is a variable; cost in the function.

Cost doesn’t have to be defined anywhere outside of the function for it to work in python? Is this typical in other languages?


Nope, you don’t need to create a cost variable anywhere outside of the function to use it inside the function. This isn’t specific to Python, most programming languages will let you create variables inside of functions which remain visible only to the code inside the function. This is called scope.

Let’s say you define the following function:

def raise_to(number, power):
  result = number ** power
  return result

In that code, we have defined a function raise_to which calculates the value of whatever you pass as number raised to a certain power. So raise_to(5,2) would return 25 (or 5 x 5).

The variable result only exists within that function, and isn’t available to use anywhere else in the larger body of code where that function appears.

Does that help?


Yes it does. Strange that it doesn’t even have to be defined as an argument. Then why define anything in the arguments?


You need to define the function as rental_car_cost(days) because the cost of renting the car depends on the number of days you have it for. Without the days argument, you can’t tell the function how many days of rental costs it needs to calculate.

We don’t need to have a cost argument in the function, because we’re never going to be telling the function what the cost should be - it’s the function’s job to work that out.


people often confuse the terms arguments and parameters, days is technically a parameter:

# function definition with parameter days
    print days

# function call with argument to satisfy parameter

the parameter doesn’t have to be defined anywhere, given its going to its value from the argument passed at function call(s), this allows us to pass different values at different times. Lets say the function calls represents different customers wanting to rent cars for different number of days.

This works fine, given functions only execute when called. So until the function is called, days is just a placeholder.


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