Combination for and if#
Consider example of combining for
and if
.
Generate_access_port_config.py file:
1 access_template = ['switchport mode access',
2 'switchport access vlan',
3 'spanning-tree portfast',
4 'spanning-tree bpduguard enable']
5
6 access = {'0/12': 10, '0/14': 11, '0/16': 17, '0/17': 150}
7
8 for intf, vlan in fast_int['access'].items():
9 print('interface FastEthernet' + intf)
10 for command in access_template:
11 if command.endswith('access vlan'):
12 print(' {} {}'.format(command, vlan))
13 else:
14 print(' {}'.format(command))
Comments to the code:
The first
for
loop iterates keys and values in nested fast_int[‘access’] dictionaryAt this moment of loop the current key is stored in intf variable
At this moment of loop the current value is stored in vlan variable
String “interface Fastethernet” is displayed with interface number added
The second loop
for
iterates commands from access_template listSince switchport access to vlan command requires a VLAN number:
within second loop
for
commands are checkedif command ends with “access vlan”
command is displayed and VLAN number is added to it
in all other cases, command is simply displayed
Result of script execution:
$ python generate_access_port_config.py
interface FastEthernet0/12
switchport mode access
switchport access vlan 10
spanning-tree portfast
spanning-tree bpduguard enable
interface FastEthernet0/14
switchport mode access
switchport access vlan 11
spanning-tree portfast
spanning-tree bpduguard enable
interface FastEthernet0/16
switchport mode access
switchport access vlan 17
spanning-tree portfast
spanning-tree bpduguard enable
interface FastEthernet0/17
switchport mode access
switchport access vlan 150
spanning-tree portfast
spanning-tree bpduguard enable