the strange arguments of range

前端 未结 4 1284
情深已故
情深已故 2020-12-10 12:32

The range function in python3 takes three arguments. Two of them are optional. So the argument list looks like:

[start], stop, [step]

This means (correct me

4条回答
  •  攒了一身酷
    2020-12-10 13:07

    range() takes 1 positional argument and two optional arguments, and interprets these arguments differently depending on how many arguments you passed in.

    If only one argument was passed in, it is assumed to be the stop argument, otherwise that first argument is interpreted as the start instead.

    In reality, range(), coded in C, takes a variable number of arguments. You could emulate that like this:

    def foo(*params):
        if 3 < len(params) < 1:
            raise ValueError('foo takes 1 - 3 arguments')
        elif len(params) == 1
            b = params[0]
        elif:
            a, b = params[:2]
        c = params[2] if len(params) > 2 else 1
    

    but you could also just swap arguments:

    def range(start, stop=None, step=1):
        if stop is None:
            start, stop = 0, start
    

提交回复
热议问题