Loops¶
The loop syntax¶
Create a file called loops.py:
Show the syntax:
Loop over a list¶
Create a simple list and show how to loop over a list:
Say that you can use
iteminstead ofrouter.
Execute the file:
Change the print statement:
Remove everything and add another example:
interfaces = ['Ethernet1/1', 'Vlan100', 'Loopback100']
for interface in interfaces:
if interface.lower().startswith('et'):
iftype = 'ethernet'
elif interface.lower().startswith('vl'):
iftype = 'vlan'
elif interface.lower().startswith('lo'):
iftype = 'loopback'
elif interface.lower().startswith('po'):
iftype = 'portchannel'
else:
iftype = 'unknown'
print(interface, iftype)
Execute the file:
Update the list
Execute the file:
Loop over a dictionary¶
Comment code:
# interfaces = ['Ethernet1/1', 'Vlan100', 'Loopback100', 'Management0']
#
# for interface in interfaces:
# if interface.lower().startswith('et'):
# iftype = 'ethernet'
# elif interface.lower().startswith('vl'):
# iftype = 'vlan'
# elif interface.lower().startswith('lo'):
# iftype = 'loopback'
# elif interface.lower().startswith('po'):
# iftype = 'portchannel'
# else:
# iftype = 'unknown'
#
# print(interface, iftype)
Add a dictionary:
Create a first loop:
Execute the file:
Add the following loop:
Execute the file:
Add the following loop:
Execute the file:
Add the following loop:
Execute the file:
Add the following loop:
Execute the file: