[Tutor] Function definition with default argument
Alan Gauld
alan.gauld at yahoo.co.uk
Sat Aug 22 15:17:54 EDT 2020
On 22/08/2020 17:51, Manprit Singh wrote:
> import pandas as pd
> ser = pd.Series(["M", "F", "M", "F", "F", "M"])
> function, and if i write a function and call it as given below ,
> passing the series as a default argument in the function :
>
> def offcnt(x=ser):
> return x.value_counts()
You almost certainly do not want to do that.
The reason is that the default argument is the value
of ser when you define the function. If you change ser
to something else and then call your function without
arguments it will still use the old value of ser.
Which I suspect is not what you would expect?
If it is what you want you should do it more explicitly:
def offcnt(x = = pd.Series(["M", "F", "M", "F", "F", "M"]))
...
> The second way of writing and calling a function to solve this problem is :
> Here i have passed the series as an actual parameter in the function call.
>
> def offcnt(x):
> return x.value_counts()
This is usually what you want. Then you can ass whatever
value ser has and get the answer you want. The point of
a default value is when you want the same value(not variable)
to be used as the argument.
Its often used where the value never changes or where the
function is normally called to habdle one specific set of
data (the set of primes say) but you want the ability to
change that when needed (to the fibonacci series say)
> My question is, what way of defining and calling functions should I
> prefer in this case, first one or second one ?
In most cases make the argument explicit if you expect it to change
regularly. Also as a generality don't make the default a variable
since it won't do what you 9or other users) might expect when you
change the variables value.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list