+ 2
print(range(x)) flaw
print(range(X)) Output : range(0,X) Why ?
6 odpowiedzi
+ 7
range(start, stop, step) creates a range object that goes from <start> to <stop-1> in steps of <step>. If you omit <start> and <stop>, Python assumes that <start> is 0 and <step> is 1. So range(5) is exactly the same as range(0, 5) or range(0, 5, 1). I don't see any flaw.
+ 2
You can fix it like this:
print(list(range(X)))
This will make a list out of it, so it won't just output the function
+ 2
Yes, I read it works this way but what's the flaw in that ? How it works behind the scenes ?
+ 2
It's because in python3 you have to make it a list
+ 2
It works using __iter__. I think range isn't a function, but a class.
Let try to create it.
class range:
def __init__(self, start, stop) :
self.start = start
self.stop = stop
self.actual = self.start - 1
def __iter__(self) :
return self
def __next__(self):
self.actual += 1
if self.actual < self.stop:
return self.actual
else:
raise StopIteration()
def __repr__(self):
return "range(0, X)"
+ 2
A good explanation is that range really doesn't create a list but it is a lazy promise to produce that values as and when required