Python – For Loops
I’m learning the basics of Python and these are my publically available notes for my reference. Hopefully they are useful for my readers as well.
The For loop in Python is used to iterate through different objects such as lists or dictionaries. The power of the For loop is that it can run as many times as needed and then stop without having to define the number of times it should run. It can also be used to run n number of times where we define n ourselves.
I’ll give some examples related to networking to make it more interesting. Let’s say that we want to create a lot of loopbacks so that we can advertise routes in BGP to play around with prefix-lists. We will create 10 loopbacks. This means that the For loop should run 10 times, we can use the range command for this. The iterator will start at 0 and have a stepping by 1 by default which means that our first loopback will be loopback0 and our first network will be 10.0.0.1/32.
for loopback in range(10): print "interface loopback{}".format(loopback) print "ip address 10.0.{}.1 255.255.255.255".format(loopback)