Let's say I have a function that accepts 3 optional arguments:
def function(arg1=0, arg2=0, arg3=0)
What is the cleanest way to handle conditionals within the function depending on which argument is passed?
Right now all I have is:
def function(arg1=0, arg2=0, arg3=0)
if arg1 !=0 and arg2 !=0 and arg3 != 0:
# do stuff with all three args
elif arg1 !=0 and arg2 != 0:
# do stuff with arg1 and arg2, etc...
To expand upon this, what if my function can take 5 arguments? Doing conditionals for all possible combinations seems like a drag. Can I not do something else to check which arguments have been passed to the function?
UPDATE: Based on some feedback I guess I'll just explain in real terms what I'm doing. I need to estimate someone's age based on when they graduated from school (high school, college, graduate program, etc). I may have multiple years to go on, and in fact I may have multiple years for each of high school, college, etc.
So, an example might be:
def approx_age(highSchool=0, college=0):
this_year = date.today().year
if (highSchool != 0) and (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 are only going to get more complicated from here...
arg != 0is equal toif argin most cases, actually.ifclause will be true if the 1stifclause is true. Do you want that?*argsand**kwargsare the way to go.