Control Structures

The "range" Function

range(start, end, step)

Returns an iterator from [start, end), and you can add a step number like:

range(0, 10, 2)

The current range index will add in steps of 2.

"else" in "for" Loops

An else statement after a for, is a block of code that will be executed after the loop ends.

for x in range(6):
    ...
else:
    print("For looop is finished")

Using "pass" Statement

Use pass to fill empty blocks like if, for, class or etc.

for x in range(6):
    pass

Iterator

Are objects which implements the iterator protocol:

  • __iter__()

  • __next__()

string, List, Tuple, Dictionary and Set are all iterable objects.

You can call iter() function on them and iterate them with next().

myIter = iter("banana")

# or

myIter = iter(someList)
...


next(myIter)
next(myIter)
next(myIter)
...

for loops automatically create iterators on objects and execute next() at each loop.

Creating iterators

You can create iterators by implementing the __iter__() and __next__() methods.

To avoid an iterator running forever, raise StopIteration.

class MyIterClass:
    def __iter__(self):
        self.a = 1
        return self

    def __next__(self):
        if self.a < 20:
            self.a += 1
            return self.a
        else:
            raise StopIteration

myIterClass = MyIterClass()

myIter = iter(myIterClass)
next(myIter)

# or

for x in myIterClass:
    ...

Last updated