the strange arguments of range

百般思念 提交于 2019-11-28 11:02:49

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

range does not take keyword arguments:

range(start=0,stop=10)
TypeError: range() takes no keyword arguments

it takes 1, 2 or 3 positional arguments, they are evaluated according to their number:

range(stop)              # 1 argument
range(start, stop)       # 2 arguments
range(start, stop, step) # 3 arguments

i.e. it is not possible to create a range with defined stop and step and default start.

def foo(first, second=None, third=1):
     if second is None:
         start, stop, step = 0, first, 1
     else:
         start, stop, step = first, second, third
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!