Python Conditionals
Conditionals
With Python conditionals statements, different computations or actions are taken depending on whether booleans constraints are true or false. The format can be summarised into the following:
if expression (true)
Statement
else (if false)
Statement
As usual, let’s look at some examples to clarify the use of conditionals in Python.
I start by creating a dictionary holding a set of routers names, and corresponding S/W as values:
The task is to have a condition, which states that if the router name I input is in this dictionary, then I print statement 1, else I print statement 2.
#create dictionary
devices = {"R1":"ios", "R2":"xr", "R3":"nx-os"}
#call for manual input
node = input()
if node in devices:
print (f"I can configure {devices[node]}")
else:
print('I dont know much about these devices')
When I run this script, I will be expected to input a value. Based on my input a statement will be printed.
In 1st instance, I will input a node name from within my dictionary, for example R2. The output, will then be the value associated with the key “R2” in this print:
“I can configure xr”
In 2nd run, I will input R6 or anything else. Since this key does not exist in my dictionary, then the if statement is not met, or is “false”. In this case, the output will be:
“I dont know much about these devices”
Loops
Loops are used to iterate over a sequence, it could be a list or a dictionary, then an action is taken.
Let’s follow up on the above example. Using the dictionary already created, we want to print all keys (not values).
devices = {"R1":"ios", "R2":"xr", "R3":"nx-os"}
#go through devices and print the keys
for items in devices:
print (items)
#output:
R1
R2
R3
And if we want to print the value only, the method remains the same:
devices = {"R1":"ios", "R2":"xr", "R3":"nx-os"}
for key,value in devices.items():
print (value)
#Output
ios
xr
nx-os
Python crash course video
To learn more about Python for Engineers, watch this 1hr crash course video.
This course covers foundation topics: