I am a beginner in python programming and recently i came across functions,parameters,arguments and...
I have done a lot of research on Parameters and Arguments(Even checked the answers of similar past questions on StackOverflow)but i couldn't get their meanings.
Some say,parameters are variables which we give them to functions while we are defining them and arguments are values that are passed in function once we given them to the function in order to run the function.While some other say no,it's not like that.Parameters and Arguments are same and do the same task...
Can anyone tell me the meaning Parameters and Arguments in a clear way?
Are Parameters and Arguments considered variables?
For what kind of purpose do we use them?
Please don't explain too much complicated,i am a beginner.
Thank you so much.
Per the official documentation:
Parameters are defined by the names that appear in a function definition, whereas arguments are the values actually passed to a function when calling it. Parameters define what types of arguments a function can accept. For example, given the function definition:
def func(foo, bar=None, **kwargs):
pass
foo, bar and kwargs are parameters of func. However, when calling func, for example:
func(42, bar=314, extra=somevar)
the values 42, 314, and somevar are arguments.
The glossary defines them as:
Argument: A value passed to a function (or method) when calling the function.
Parameter: A named entity in a function (or method) definition that specifies an argument (or in some cases, arguments) that the function can accept.
Python doesn't really have "variables" like some other languages - it has "names" referring to "objects". See e.g. "Code like a Pythonista" and "Facts and myths about Python names and values".
Take it this way:
Parameter:
A parameter represents a value that the procedure expects you to pass when you call it. The procedure's declaration defines its parameters.
Argument:
An argument represents the value that you pass to a procedure parameter when you call the procedure. The calling code supplies the arguments when it calls the procedure.
Example:
int add (int value1, int value2) // Here value1 and value2 are PARAMETERS.
{
return value1+value2;
}
Now while calling the function
answer = add(2,3); // Here values 2 and 3 are ARGUMENTS.
Same goes with Python, while declaration, they are parameters, while calling they are arguments.
Some may differ with what i have written, but this is how it is actually known in programming world.
Related
Let's consider
foo(arg1=123, arg2=None) and foo(arg1=123).
Tell me please, if these two ways are equivalent ?
No, the two given function signatures (and hence functions) are not equivalent.
In foo(arg1=123, arg2=None), you have two arguments -- arg1 and arg2, which can be used inside the function as local names. Note that, assigning a value of None to some name does not make it anything special/different as far as the assignment statements are concerned. It is in fact a common way to give a placeholder value for a variable that is not mandatory or may be an empty mutable object.
On the other hand, foo(arg1=123) has only one argument arg1, which is available on the function's local scope for use.
Edit:
If you have a function defined as foo(arg1, arg2), both arguments are mandatory (positional) arguments.
So, foo(arg1=21) will throw a TypeError as you have not provided arg2. Whereas, foo(arg1=21, arg2=None) will work just fine as you have provided values for both the arguments.
Edit2:
If you have a function defined as foo(arg1=None, arg2=None) (or something similar i.e. with default values), both arguments are optional (keyword) arguments. In that case, both of the mentioned definitions would be the same.
This question already has answers here:
What's the difference between an argument and a parameter?
(38 answers)
Closed last month.
So I'm still pretty new to Python and I am still confused about using a parameter vs an argument. For example, how would I write a function that accepts a string as an argument?
Generally when people say parameter/argument they mean the same thing, but the main difference between them is that the parameter is what is declared in the function, while an argument is what is passed through when calling the function.
def add(a, b):
return a+b
add(5, 4)
Here, the parameters are a and b, and the arguments being passed through are 5 and 4.
Since Python is a dynamically typed language, we do not need to declare the types of the parameters when declaring a function (unlike in other languages such as C). Thus, we can not control what exact type is passed through as an argument to the function. For example, in the above function, we could do add("hello", "hi").
This is where functions such as isinstance() are helpful because they can determine the type of an object. For example, if you do isinstance("hello", int), it will return False since "hello" is a string.
See the FAQ:
What is the difference between arguments and parameters?
Parameters are defined by the names that appear in a function definition, whereas arguments are the values actually passed to a function when calling it. Parameters define what types of arguments a function can accept. For example, given the function definition:
def func(foo, bar=None, **kwargs):
pass
foo, bar and kwargs are parameters of func. However, when calling func, for example:
func(42, bar=314, extra=somevar)
the values 42, 314, and somevar are arguments.
See also:
language-agnostic What's the difference between an argument and a parameter?
This answer is my favourite.
For defining a function that accepts a string, see TerryA's answer. I just want to mention that you can add type hints to help people using your function to tell what types it accepts, as well as what type it returns.
def greeting(name: str) -> str:
return 'Hello ' + name
In Programming lingo, arguments refers to the data you are passing to the function that is being called whereas the parameter is the name of the data and we use the parameter inside the function to refer it and do things with it.
for example:
def functionname(something):
do some stuff with {something}
functionname(abc)
in this case,
abc --> argument
something --> parameter
A parameter is the placeholder; an argument is what holds the place.
Parameters are conceptual; arguments are actual.
Parameters are the function-call signatures defined at compile-time; Arguments are the values passed at run-time.
Mnemonic: "Pee" for Placeholder Parameters, "Aeigh" for Actual Arguments.
I have a function, and inside this function I should execute another function of 3 posibilities.
The simple way should be passing a parameter, doing a if-elif to exec function acording to that parameter, but I'd like to know it it's posible to pass the name of a funtion by params and use that, something like:
FunctionA(Param1, Param2, FunctionNameToUse)
....Code....
FunctionNameToUse(Value1, Value2)
....Code....
endFunctionA
Depending on how functionA is called, it will use one Function or another, I dont know if I explained well...
Thanks mates!
Functions themselves are first class objects in Python. So there's no need to pass the name: pass the actual function itself, then you can call it directly.
def func1(a, b):
pass
def func2(a, b):
pass
def functionA(val1, val2, func):
func(val1, val2)
# now call functionA passing in a function
functionA("foo", "bar", func1)
In python, functions are first-class values, which means they can be passed around as arguments, returned from functions, and so on.
So the approach you want to take should work (However you're not passing the name, you're passing the actual function).
Take a look at map and filter in the standard library, they do exactly this.
Yes, you can. As other have mentioned, functions are first-class objects, i.e. you can do everything you can think of to it (see What are "first class" objects? for more info).
So then, how does this really work when you pass in a function as parameter? If you have taken any ComSci class, you'd know that each process has a special area in memory allocated for its code; all of your functions are defined here. Whenever you call a function, the CPU would move the Program Counter (a special pointer that points to whatever code it is executing at the moment) to the beginning of that function's code, and go from there. Thus, after the function is loaded in memory, all that's needed to call it is its address. When you pass a function A's "name" as an argument to another function B in Python, what you are doing is really passing a reference (in C term, a pointer) that contains the address to the code that represents A in memory.
While I'm going through Python code and seeing functions called, I notice things like
functionCall(argument='something')
or
someclass.functionCall(argument='something')
I've played around with it and noticed you have to name that variable with the same name as the one in the scope of the function or class function itself. Is that just a convention (for useful naming) or is there more to it that I'm missing?
Those are just standard keyword arguments.
They are mainly useful when calling functions that usually assume default values, but the user is interested in passing a custom value without affecting the other defaults.
For example:
def foo(a='a', b='b', c='c'):
print a + b + c
Then:
>>> foo()
'abc'
>>> foo(c='x') # don't know or care about a and b's value
'abx'
This is called a keyword argument. Keyword arguments have a couple distinct advantages:
They can be specified in any order by the caller.
They have default values, which means the caller doesn't have to provide a value for each argument if the defaults are sensible.
They can make code more readable. For example, foo(width=100, height=200) is easier to understand than foo(100, 200). It is also easier to use, because you don't have to remember whether the function takes width,height or height,width.
It is good to have named arguments as arguments can be specified in any order by using named arguments.
Even required arguments (like object, which has no default value) can be named, and named arguments can appear in any order.
Also see This
Python's argument passing mechanisms are extremely flexible.
cons: too many arguments to a function. Solutions: split into multiple functions, pass some args together in a dictionary or object.
cons: bad variable names. Solution: give variables more descriptive names.
Or remember the correct order .. :)
class xyz:
def __init__ (self, a='1', b='2'):
print a,b
xyz(b=3,a=4)
xyz(a=5,b=6)
>>4 3
>>5 6
these are keyword parameters. They enable you to pass parameters in any order (useful for skipping optional parameters)
Please note though, calling functions that way comes with a little bit of overhead:
def test(a,b,c):
return a+b+c
def t1():
return test(1,2,3)
def t2():
return test(a=1, b=2, c=3)
timeit(t1)
0.23918700218200684
timeit(t2)
0.2716050148010254
I was wondering if the 'a=a', and 'b=b' can lead to problems/unexpected behaviour? code works fine in the example.
def add_func(a=2,b=3):
return a+b
a=4
b=5
answer = add_func(a=a, b=b)
Thanks
Not that I know of, although I'd love to be proved wrong.
The formal language reference defines the lexical structure of a function call. The important bit is that it defines a "keyword_item" as identifier "=" expression. Also, here's what it says about how the arguments to the call are interpreted:
If keyword arguments are present, they are first converted to
positional arguments, as follows. First, a list of unfilled slots is
created for the formal parameters. If there are N positional
arguments, they are placed in the first N slots. Next, for each
keyword argument, the identifier is used to determine the
corresponding slot (if the identifier is the same as the first formal
parameter name, the first slot is used, and so on). If the slot is
already filled, a TypeError exception is raised. Otherwise, the value
of the argument is placed in the slot, filling it (even if the
expression is None, it fills the slot). When all arguments have been
processed, the slots that are still unfilled are filled with the
corresponding default value from the function definition.
This lists a few possible scenarios.
In the simple case, like you mentioned, where there are two formal arguments (a and b), and if you specify the function call using keyword parameters like add_func(a=a, b=b), here's what happens:
Two slots are created to hold the parameters.
Since you didn't provide any positional arguments in the call (just keyword arguments), none of the slots are filled initially.
Each of your keyword arguments are analyzed individually, and the identifier of your argument (the "a" in the a= part) is compared with all of the formal parameters names of the function (the names that were given the parameters when the function was defined, in our case, a and b).
When a match occurs, the value of the keyword arguments (in this case, 4!) is used to fill the corresponding slot.
This repeats until all keyword arguments are analyzed. If all slots aren't filled, then Python tries to assign a default value to the remaining slots if one exists. If not, an error is raised.
So, Python treats the "identifier" in a keyword argument completely differently. This is only true for keyword arguments, though; obviously, if you tried something like add_func(b, a), even though your parameters themselves are called b and a, this would not be mapped to the formal parameters in the function; your parameters would be backwards. However, add_func(b=b, a=a) works fine; the positions don't matter as long as they are keyword arguments.
It depends on whether or not the global objects pointed to are mutable or immutable. immutable objects such as your integers are copies when modified, so it's safe. Mutable objects such as lists are modified in-place, and are NOT safe to use this way. Any change to them persists between calls and may (and probably will) cause unexpected behaviors.
This:
a=[]
def f(a=a):
pass
Is the same as:
def f(a=[]):
pass
Which is a known bad practice in Python programs.