0

I am trying to make my function be able to accept as many inputs or as little inputs as needed.

Currently I have 3 inputs that are hard coded (loc1, loc2, loc3). Is there a way to keep the inputs variable so if I just had 1 input, or if I have 5 inputs, my function can be flexible?

def np_array(loc1, loc2, loc3):
    loc_a = np.array(loc1)
    loc_b = np.array(loc2)
    loc_c = np.array(loc3)

    pressure_vector1 = np.subtract(loc_a, loc_c)
    pressure_vector2 = np.subtract(loc_a, loc_b)

    movement_vector = np.add(pressure_vector1, pressure_vector2)

    return movement_vector
Ralf
  • 16,086
  • 4
  • 44
  • 68
Evan Kim
  • 769
  • 2
  • 8
  • 26

2 Answers2

2

You can use *args or **kwargs for this.

In Python, the single-asterisk form of *args can be used as a parameter to send a non-keyworded variable-length argument list to functions. It is worth noting that the asterisk (*) is the important element here, as the word args is the established conventional idiom, though it is not enforced by the language.

The double asterisk form of **kwargs is used to pass a keyworded, variable-length argument dictionary to a function. Again, the two asterisks (**) are the important element here, as the word kwargs is conventionally used, though not enforced by the language.

Like *args, **kwargs can take however many arguments you would like to supply to it. However, **kwargs differs from *args in that you will need to assign keywords.

To learn more about this I recommend this awesome post

Sreeram TP
  • 11,346
  • 7
  • 54
  • 108
0

You could use default arguments to make the function more flexible like:

def np_array(loc1=None, loc2=None, loc3=None):
    # ensure you don't use None type variables
    if loc1 is None:
        loc1 = 'sensibleDefaultValueGoesHere'
    # repeat as often as needed before you proceed with the

    # actual calculation ...
meissner_
  • 556
  • 6
  • 10