[Tutor] Function definition with default argument

Manprit Singh manpritsinghece at gmail.com
Sat Aug 22 12:51:25 EDT 2020


Dear sir ,
Consider a pandas series as given below :

import pandas as pd
ser = pd.Series(["M", "F", "M", "F", "F", "M"])
upon printing the series we will get :

0    M
1    F
2    M
3    F
4    F
5    M
dtype: object

Now if i have to count number of "M' and 'F' in the series, using a
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()

g = offcnt()
print(g)

Which gives the right answer:

F    3
M    3
dtype: int64

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()

g = offcnt(ser)
print(g)

This also gives the right answer as written below:

F    3
M    3
dtype: int64

My question is, what way of defining and calling functions should I
prefer in this case, first one or second one ?

Need your guidance.

Regards

Manprit Singh


More information about the Tutor mailing list