Skip to content

Loops

The loop syntax

Create a file called loops.py:

touch loops.py

Show the syntax:

for LOOP_VARIABLE in LIST/DICTIONARY:
    code

Loop over a list

Create a simple list and show how to loop over a list:

routers = ['r1', 'r2', 'r3']

for router in routers:
    print(router)

Say that you can use item instead of router.

Execute the file:

python loops.py

Change the print statement:

routers = ['r1', 'r2', 'r3']

for router in routers:
    print('Hostname is {}'.format(router))

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:

python loops.py

Update the list

interfaces = ['Ethernet1/1', 'Vlan100', 'Loopback100', 'Management0']

Execute the file:

python loops.py

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:

facts = {'vendor': 'cisco', 'ip': '10.1.1.1', 'platform': 'nxos'}

Create a first loop:

for fact in facts:
    print(fact)

Execute the file:

python loops.py

Add the following loop:

for fact in facts:
    print(facts[fact])

Execute the file:

python loops.py

Add the following loop:

for value in facts.values():
    print(value)

Execute the file:

python loops.py

Add the following loop:

for key in facts:
    print(key, facts[key])

Execute the file:

python loops.py

Add the following loop:

for key, value in facts.items():
    print(key, value)

Execute the file:

python loops.py