Python Functions
Functions
Functions are block of code, mostly used for repetitive tasks. The process is to define to function, set the arguments, the take action or execute the code.
This will be best explained by looking at examples.
Say for example we want to generate a config to support OSPF routing, and this template will change often, depending on OSPF process ID, OSPF area and network.
See example below, and pay attention to the comments (marked with #).
#define funcion and arguments
def ospf_process (process_id, network, mask, area):
#action to be taken by my function
print(f" router ospf {process_id} \n network {network} {mask} area {area}")
#supply arguments to my function
ospf_process ("20", "20.1.1.0", "255.255.255.240" , "30")
#Output:
router ospf 20
network 20.1.1.0 255.255.255.240 area 30
Using this function, we have just created a config template ready to paste to a Cisco router. Now let’s say we would like the code to generate the config based on arguments we are inputting, instead of having them listed (as we did in the previous example).
Here, we shall make use of the “input” Syntax, which will be expecting arguments to be typed by the operator. Once all arguments are key in, the function executes and generates the config. See below example.
#define funcion and arguments
def ospf_process (process_id, network, mask, area):
#action to be taken by my function
print(f" router ospf {process_id} \n network {network} {mask} area {area}")
#supply arguments to my function
process_id = input('process_id')
network = input('network')
mask = input('mask')
area = input('area')
#Execute the function
ospf_process (process_id, network, mask , area)
#Passing arguments:
process_id10
network172.16.1.1
mask255.255.255.255
area50
#Output:
router ospf 10
network 172.16.1.1 255.255.255.255 area 50
Python crash course video
To learn more about Python for Engineers, watch this 1hr crash course video.
This course covers foundation topics: