Tim
Tim

Reputation: 59

How to fix the function issue while allowing it to be dynamic?

Let's say i'm calling a function given the following arguments

Function(char1, char2, char3, char4, Number)

where the first 4 terms represent chars and the last is an int, i might add more chars so the function can't be static . The main function will start like

def Function(*args):
  table_line = ""
  for x in range(Number/2): 

but by giving the Function args it no longer knows that it should use the supplied argument number in that third line.

Upvotes: 1

Views: 63

Answers (2)

cs95
cs95

Reputation: 402563

If you're using python3.x (which you're now not, as you mentioned in the comments), you could unpack your args using * iterable unpacking, before using them:

def function(*args):
    *chars, number = args
    ...

It works like this:

In [8]: *a, b = (1, 2, 3, 4)

In [9]: a
Out[9]: [1, 2, 3]

In [10]: b
Out[10]: 4

Every element in args except the last is sent to chars, which now becomes a list. You may now use the number variable as a separate variable.

Upvotes: 1

Nils Werner
Nils Werner

Reputation: 36765

Pass number as the first argument:

def func(number, *char):
    ...

Upvotes: 2

Related Questions