Lab 14 - Getting Started with Conditionals¶
This lab walks you through an introduction of using conditionals allowing you to add more intelligence and business logic into your code.
Task 1 - Introduction to the IF Statement¶
We've already reviewed boolean expressions, so you already know how to build if statements.
Examples:
Perform the same boolean check:
Step 1-1¶
Each of the expressions can easily be used in an if statement. Start a new Python interactive interpreter in a terminal session.
Try the following examples that map what was done previously:
>>> hostname = "nxos-spine1"
>>>
>>> if hostname == "nxos-spine1":
... print("The hostname is correct.")
...
The hostname is correct.
>>>
Notice how the only changes were adding the if statement, the trailing : colon, and then the code to execute if the expression is true.
Note: Mind the indentation! Each line that "belongs" to the
ifblock should be indented to the right using 4 spaces. This is where a code editor usually helps you, but on the command line of the Python interpreter you have to take special care yourself when typing.
Step 1-2¶
Another example, testing membership of a list of results that might come from gathering data about your network devices.
>>> platforms = ['nexus', 'catalyst', 'asa', 'csr', 'aci']
>>>
>>> if 'catalyst' in platforms:
... print("Catalyst has been found in the network.")
...
Catalyst has been found in the network.
>>>
Step 1-3¶
Create a variable called supported_platforms and assign it the value of ['nexus', 'catalyst'].
Determine which of the platforms are supported platforms using a combination of conditional logic and a for loop.
>>> supported_platforms = ['nexus', 'catalyst']
>>>
>>> for platform in platforms:
... if platform in supported_platforms:
... print("Platform {} -- SUPPORTED".format(platform))
...
...
Platform nexus -- SUPPORTED
Platform catalyst -- SUPPORTED
>>>
Note: Mind the indentation, part two! This time you have an
ifblock nested within aforblock. For each level of indentation, you have to add 4 spaces.
Step 1-4¶
Add an else statement to the previous example printing an equivalent statement so we can see even the invalid platforms.
>>> for platform in platforms:
... if platform in supported_platforms:
... print("Platform {} -- SUPPORTED".format(platform))
... else:
... print("Platform {} -- NOT SUPPORTED".format(platform))
...
Platform nexus -- SUPPORTED
Platform catalyst -- SUPPORTED
Platform asa -- NOT SUPPORTED
Platform csr -- NOT SUPPORTED
Platform aci -- NOT SUPPORTED
>>>
Step 1-5¶
Create the following list of dictionaries:
Pretty print it to make sure you understand its data type.
Step 1-6¶
Print ONLY the VLAN name for VLAN 20. Assume there are 100s of VLANs in this list and you don't know the VLANs index value.
>>> for item in vlans:
... if item['id'] == 20:
... print("VLAN NAME: {}".format(item['name']))
...
VLAN NAME: app
>>>
Step 1-7¶
Generate and print all required Cisco IOS commands to configure the list of desired VLANs:
>>> for item in vlans:
... vlan_id = item['id']
... name = item['name']
... print("vlan {}".format(vlan_id))
... print(" name {}".format(name))
...
vlan 10
name web
vlan 20
name app
vlan 30
name db
>>>
Step 1-8¶
Remove the VLAN name for VLAN 20.
Step 1-9¶
Repeat Step 6.
Does it work?
Step 1-10¶
When you use the [] notation it assumes the key is going to be there and if it's not (like for VLAN 20), a KeyError is raised.
However, we did cover in the booleans section AND the dictionary section a method we can use to overcome this.
ALWAYS, if a dictionary key may not exist, do NOT use the notation like dict['key']. Instead, you should use dict.get('key')
Once you extract a value using get, you can perform a conditional check on it to see if it has a value assigned. For reference scroll up and look at the examples before Step 1.
>>> for item in vlans:
... vlan_id = item['id']
... name = item.get('name')
... print("vlan {}".format(vlan_id))
... if name:
... print(" name {}".format(name))
...
vlan 10
name web
vlan 20
vlan 30
name db
>>>
See what happened here? Since get returns None if the key doesn't exist, it's easy to use in an if statement to see if a value was in fact returned.
Step 1-11¶
Create the variable called devices as such:
>>> devices = [{'platform': 'nexus', 'hostname': 'nycr01'}, {'platform': 'catalyst', 'hostname': 'nycsw02'}, {'platform': 'mx', 'hostname': 'nycr03'}, {'platform': 'srx', 'hostname': 'nycfw01'}, {'platform': 'asa', 'hostname': 'nycfw02'}]
>>>
Pretty print to better see the full object, but it's a list of dictionaries. Each dictionary has two key-value pairs, e.g. a platform key and a hostname key.
>>> print(json.dumps(devices, indent=4))
[
{
"platform": "nexus",
"hostname": "nycr01"
},
{
"platform": "catalyst",
"hostname": "nycsw02"
},
{
"platform": "mx",
"hostname": "nycr03"
},
{
"platform": "srx",
"hostname": "nycfw01"
},
{
"platform": "asa",
"hostname": "nycfw02"
}
]
Step 1-12¶
Loop through devices and print the vendor of each device. Make sure the code also prints out "Unknown Vendor" if it is an unknown vendor - for this example, treat the ASA as "unknown".
Make sure to use the elif statement in this example.
>>> for item in devices:
... platform = item.get('platform')
... if platform == "nexus":
... print("Vendor is Cisco")
... elif platform == "catalyst":
... print("Vendor is Cisco")
... elif platform == "aci":
... print("Vendor is Cisco")
... elif platform == "srx" or platform == "mx":
... print("Vendor is Juniper")
... else:
... print("Unknown Vendor")
...
Vendor is Cisco
Vendor is Cisco
Vendor is Juniper
Vendor is Juniper
Unknown Vendor
>>>
There are a few ways to handle this and we're showing two in this example. You can check each platform separately as shown with Cisco or check them on the same line as shown with Juniper using an or statement.
Step 1-13¶
There is another way too if we pre-build a known platform list per vendor.
>>> cisco_platforms = ['catalyst', 'nexus', 'aci']
>>> juniper_platforms = ['mx', 'srx']
>>>
>>> for item in devices:
... platform = item.get('platform')
... if platform in cisco_platforms:
... print("Vendor is Cisco")
... elif platform in juniper_platforms:
... print("Vendor is Juniper")
... else:
... print("Unknown Vendor")
...
Vendor is Cisco
Vendor is Cisco
Vendor is Juniper
Vendor is Juniper
Unknown Vendor
>>>
Conclusion¶
Conditionals and loops are very powerful programming language constructs that help you add branching and repeatable logic to your code.
While it is a bit cumbersome to write such code on the Python interpreter directly (due mostly to indentation requirements), it serves as a great learning tool before moving to what's more typically done: placing code within files (with the help of a code editor) and executing those.