Python: Conditionals for optional function arguments -
let's have function accepts 3 optional arguments:
def function(arg1=0, arg2=0, arg3=0)
what cleanest way handle conditionals within function depending on argument passed?
right have is:
def function(arg1=0, arg2=0, arg3=0) if arg1 !=0 , arg2 !=0 , arg3 != 0: # stuff 3 args elif arg1 !=0 , arg2 != 0: # stuff arg1 , arg2, etc...
to expand upon this, if function can take 5 arguments? doing conditionals possible combinations seems drag. can not else check arguments have been passed function?
update: based on feedback guess i'll explain in real terms i'm doing. need estimate someone's age based on when graduated school (high school, college, graduate program, etc). may have multiple years go on, , in fact may have multiple years each of high school, college, etc.
so, example might be:
def approx_age(highschool=0, college=0): this_year = date.today().year if (highschool != 0) , (college != 0): hs_age = (this_year - highschool) + 18 college_age = (this_year - college) + 21 age_diff = abs(hs_age - college_age) if age_diff == 0: return hs_age elif return (hs_age + college_age)/2 elif highschool != 0: hs_age = (this_year - highschool) + 18 return hs_age elif college != 0: college_age = (this_year - college) + 21 return college_age
things going more complicated here...
why check argumnet value 0
, use of elif
pythonic. conditional statement check statement truth value
if true condition proceed else switch next condition.
and
in [112]: bool(0) out[112]: false in [113]: bool(none) out[113]: false
so if argument value 0
don't need match 0
python selfly illustrate it.
def function(arg1=0, arg2=0, arg3=0) if arg1 , arg2 , arg3: # stuff 3 args elif arg1 , arg2: # stuff arg1 , arg2, etc... .. .. else: #do
or none
too:
def function(arg1=none, arg2=none, arg3=none) if arg1 , arg2 , arg3: # stuff 3 args
Comments
Post a Comment