Reputation: 3
When would you know when to use arguments or local variables (by local variables I mean variables declared within the function like in example 2)? Sometimes people make local variables, sometimes they use arguments in a function. What is the difference?
def function(a, b):
return a+b
function(2,3)
And:
def function():
a = 2
b = 3
return a+b
This is a very simple example, but if the function were to be bigger, when would you use local variables instead of arguments? Please help.
Upvotes: 0
Views: 661
Reputation: 4991
To help answer this I would like to answer it with an example.
Functions can be thought of as repeatable instructions. So we can have a function called fixCar()
. This function is basically a set of instruction for our robot to fix cars. We would want to pass the car to the robot to fix, since we don't know what car the robot we will be fixing we should just pass in:
def fixCar(car):
This creates a requirement where we have to pass the car to the robot to fix, if we don't pass a car to the robot, how would the robot fix a car?
To fix the car, the robots needs to have basic tools, sure we can pass it the basic tools each time (def fixCar(car, tools)
), but if the set of basic tools are require to fix any car, it make sense to include the tools as a local variable where we don't need to specify them each time:
def fixCar(car):
tools = 'basic tools'
Now no matter what car we pass in, the robot has basic tools to work with. What happens if we want to give them special tools to work on special cars? Since it might be a special tool that the customer brings in (think tire locks on higher end cars), we will have to pass the set of special tools in through the argument to the robot:
def fixCar(car, specialTools):
tools = 'basic tools'
But if we were going to pass in some tools sometimes and not always, we can set a default to the argument. This makes specialTools
and optional argument
, meaning the program won't complain if we don't pass anything in, and will use the specialTools
if we pass something in:
def fixCar(carType, specialTools=None):
if specialTools:
print('I have special tools to work with')
else:
print('I didn't receive any special tools, but that's okie')
tools = 'basic tools'
In summary, local variables can be though of something the function requires so it can complete it's job. Arguments are to 'config' the function to run a certain way or is the 'unknown' factor that the function has to work with.
Upvotes: 1