Why does range(start, end) not include end?

后端 未结 9 1323
夕颜
夕颜 2020-11-22 10:24
>>> range(1,11)

gives you

[1,2,3,4,5,6,7,8,9,10]

Why not 1-11?

Did they just decide to do it lik

9条回答
  •  不要未来只要你来
    2020-11-22 10:58

    Basically in python range(n) iterates n times, which is of exclusive nature that is why it does not give last value when it is being printed, we can create a function which gives inclusive value it means it will also print last value mentioned in range.

    def main():
        for i in inclusive_range(25):
            print(i, sep=" ")
    
    
    def inclusive_range(*args):
        numargs = len(args)
        if numargs == 0:
            raise TypeError("you need to write at least a value")
        elif numargs == 1:
            stop = args[0]
            start = 0
            step = 1
        elif numargs == 2:
            (start, stop) = args
            step = 1
        elif numargs == 3:
            (start, stop, step) = args
        else:
            raise TypeError("Inclusive range was expected at most 3 arguments,got {}".format(numargs))
        i = start
        while i <= stop:
            yield i
            i += step
    
    
    if __name__ == "__main__":
        main()
    

提交回复
热议问题