pythonfunctionparametersdefault-parameters

Sets the default value of a parameter based on the value of another parameter


So I want to create a function that generates consecutive numbers from 'start' to 'end' as many as 'size'. For the iteration, it will be calculated inside the function. But I have problem to set default value of parameter 'end'. Before I explain further, here's the code:

# Look at this -------------------------------
#                                           ||
#                                           \/
def consecutive_generator(size=20, start=0, end=(size+start)):
    i = start
    iteration = (end-start)/size

    arr = []
    temp_size = 0

    while temp_size < size:
        arr.append(i)

        i += iteration
        temp_size += 1

    return arr

# with default end, so the 'end' parameter will be 11
c1= consecutive_generator(10, start=1)
print(c1)

# with end set
c2= consecutive_generator(10, end=20)
print(c2)


As can be seen above (on the default value of the 'end' parameter), what I want to achieve is the 'end' parameter whose default value is 'start' + 'size' parameters (then the iteration will be 1)

The output will definitely be an error. So how can i do this? (this is my first time asking on stackoverflow sorry if i made a mistake)

(Closed)


Solution

  • This is a pretty standard pattern:

    def consecutive_generator(size=20, start=0, end=None):
       if end is None:
           end = size + start