0

I am trying to define a function in python in which the function has two possible sets of arguments.I am writing a code to determine an overall course grade and depending on if they change the standard course weights depends on how many arguments I want to send to the function that calculates the grade. If they do not change the standard weights I only want to pass two arguments(test scores and lab scores). If they change the weights I want to pass four arguments(test scores, lab scores, lab weight and test weight).Overall I am not sure how I would go about defining said function since the usual practice is simply putting all the arguments in the function to begin.

GradeWeight=raw_input('Enter C to change weights or D to use default weights.')
GradeWeight=GradeWeight.upper()
if GradeWeight=='D':
    grade_calculator(a=LabScores,b=TestScores)
elif GradeWeight=='C':
    LabWeight=float(input('What is the lab weight percentage?(without the %)'))
    TestWeight=float(input('What is the test weight percentage?(without the %)'))
    grade_calculator(a=LabScores,b=TestScores,c=LabWeight,d=TestWeight)
def grade_calculator():
Raviprakash
  • 2,410
  • 6
  • 34
  • 56

2 Answers2

2

It's possible:

def grade_calculator(**kwargs):
  if 'c'  in kwargs or 'd' in kwargs:
    #do your thing
  else:
    # do your other thing
Ereli
  • 965
  • 20
  • 34
0

I assume you are coming from a language that allows overloading, letting you do things like:

public int test(int one, int two)
public int test(int one, int two, int three)

Unfortunately, Python does not allow this. The easiest way would be the following.

def my_method(self, parameter_A, parameter_B=None):
   if isinstance(parameter_B, int):
     print parameter_A * parameter_B
   else:
     print parameter_A
     if parameter_B is not None:
       print parameter_B

Essentially, you are testing to see if the second parameter was given. If it was not given (or given as None, the Python equivalent of null), then it does not use this parameter. However, if it does, then the code evaluates it. Essentially, it's a game of if and else if statements.

You can read here some more about function overloading being missing in Python. It is a hassle, especially since it is something an OOP language should have, but its one of the few downsides to Python.

HunBurry
  • 113
  • 14