Learning Python: Week2 (Printing, Numbers, and Lists) -Part 5

5 May 2017 1 comment

As discussed in post  ( https://crazyrouters.wordpress.com/2017/02/25/learning-python-kirk-byers-python-course/  ) , i will be sharing the my learning on weekly basis as course continues. This will not only motivate me but also help others who are in phase of learning python 3.

This post will focus on Exercise 4.

################# Exercise 4 #############

IV. You have the following string from “show version” on a Cisco router

cisco_ios = “Cisco IOS Software, C880 Software (C880DATA-UNIVERSALK9-M), Version 15.0(1)M4, RELEASE SOFTWARE (fc1)”

Note, the string is a single line; there is no newline in the string.

How would you process this string to retrieve only the IOS version:

   ios_version = “15.0(1)M4”

Try to make it generic (i.e. assume that the IOS version can change).

You can assume that the commas divide this string into four sections and that the string will always have ‘Cisco IOS Software’, ‘Version’, and ‘RELEASE SOFTWARE’ in it.

############## END ##########################

 

These will be easy to get it done, if gone through last three exercise of week 2. We have given a string named cisco_ios . we need to go through the string and retreive  the IOS Version.

cisco_ios = “Cisco IOS Software, C880 Software (C880DATA-UNIVERSALK9-M), Version 15.0(1)M4, RELEASE SOFTWARE (fc1)”

As we can see there are four parts of string seperated by  ‘ , ‘ , so lets use the our evergreen classic best method to separate the strings  in 4 elements of list by using  the split method.

ios_ver1

So now we are having list out with 4 elements, we have to focus on element 2 only of list out .

ios_ver2

Here we can see 2 elements separated by space , we target is second element which is literally ios_version.

ios_ver3

So we have got the required result. Lets have a code altogether to get the required result

CODE:

ios_ver_code

OUTPUT:

ios_ver_code_out

So, here we are done with exercise of week 2. Hope its was cool !!!!

smiles 🙂

 

 

 

 

Advertisements
Categories: NOTES, Python, Routing Tags: , , ,

Learning Python: Week2 (Printing, Numbers, and Lists) -Part 4

As discussed in last post  ( https://crazyrouters.wordpress.com/2017/02/25/learning-python-kirk-byers-python-course/  ) , i will be sharing the my learning on weekly basis as course continues. This will not only motivate me but also help others who are in phase of learning python 3.

This post will focus on Exercise 3

########### EXERCISE 3  #########

III. You have the following four lines from ‘show ip bgp’:

entry1 = “*  1.0.192.0/18   157.130.10.233     0 701 38040 9737 i”
entry2 = “*  1.1.1.0/24       157.130.10.233     0 701 1299 15169 i”
entry3 = “*  1.1.42.0/24     157.130.10.233     0 701 9505 17408 2.1465 i”
entry4 = “*  1.0.192.0/19   157.130.10.233     0 701 6762 6762 6762 6762 38040 9737 i”

Note, in each case the AS_PATH starts with ‘701’.

Using split() and a list slice, how could you process each of these such that–for each entry, you return an ip_prefix and the AS_PATH (the ip_prefix should be a string; the AS_PATH should be a list):

Your output should look like this:

ip_prefix             as_path                                           
1.0.192.0/18       [‘701’, ‘38040’, ‘9737’]                          
1.1.1.0/24           [‘701’, ‘1299’, ‘15169’]                          
1.1.42.0/24         [‘701’, ‘9505’, ‘17408’, ‘2.1465’]                
1.0.192.0/19       [‘701’, ‘6762’, ‘6762’, ‘6762’, ‘6762’, ‘38040’, ‘9737’]

Ideally, your logic should be the same for each entry (I say this because once I teach you for loops, then I want to be able to process all of these in one four loop).

If you can’t figure this out using a list slice, you could also solve this using pop().

############### END ################

 

Lets begin to code the requirement using pop and slice and then move to solve the exercise using for loop.

Here is the input provided , we have to get the IP prefix part and as_path extracted from each entry.

entry1 = “*  1.0.192.0/18   157.130.10.233     0 701 38040 9737 i”
entry2 = “*  1.1.1.0/24       157.130.10.233     0 701 1299 15169 i”
entry3 = “*  1.1.42.0/24     157.130.10.233     0 701 9505 17408 2.1465 i”
entry4 = “*  1.0.192.0/19   157.130.10.233     0 701 6762 6762 6762 6762 38040 9737 i”

Lets consider each entry one by one, if we are able to crack the logic for one entry ,it will be valid for all other entry .

First need to split entry1  into elements of a new  list ent1  using split method .

aspath1

Next task is to split the list into new list out1  having the same elements as ent1 excepts the first  element i.e ‘*’ and last element ‘i’.

We can do the same by using the pop method but i have used the split method to get new list out1 having the all elements except first one and last one .

aspath2

next requirement is to print the ip prefix i.e first element of list out1 and As-path which starts with element value’701′

aspath3

So we have got both ip prefix and as_path as output for entry1. so we can go ahead the same for each entry and get the required output.

Here is final code for reference

CODE:

as_path_code1.PNG

 

As you note in above code that i have changed the list into string (str(out1[3:]) for each entry  while printing the output.As we try to pass only the list , it will throw error as below ,so need to change type from list to string.

TypeError: unsupported format string passed to list.__format__

aspath4

OUTPUT:

as_path_code1_ou

So we have got the final output as required .

Lets optimise and get the same code using the for loop.

first taken each entry as element of  list named as  output.

as_for1

Now i will run the for loop for each element of output and perform the same operation on each element of list output as below:

opearation for each iteration of element of list output: 

1) Split each element of list output  into a new list out  using split method .

2)Further Split the list into new list out1  having the same elements as out excepts ‘*’and ‘i’.

3) Print the first element of list out1 as ip_prefix and slice of list out1 starting from value’701′ as as_path .

Here is the code using for loop for reference.

CODE:

as_path_for_code

OUTPUT:

as_path_for_code_out

So we are done with this exercise , using for loop and without for loop.

I will be back with last exercise of week 2 .

Smiles 🙂

 

 

 

 

Categories: NOTES, Python, Routing Tags: , , ,

Learning Python: Week2 (Printing, Numbers, and Lists) -Part 3

As discussed in last post,  ( https://crazyrouters.wordpress.com/2017/02/25/learning-python-kirk-byers-python-course/  ) , i will be sharing the my learning on weekly basis as course continues. This will not only motivate me but also help others who are in phase of learning python 3.

Here we are going to discuss the Exercise 2 . Here is the Exercise 2 instruction

 

>>>>>>>>>>>>EXERCISE 2     >>>>>>>>>>>>>>

II. Create an IP address converter (dotted decimal to binary):

    A. Prompt a user for an IP address in dotted decimal format.

    B. Convert this IP address to binary and display the binary result on the screen (a binary string for each octet).

    Example output:
    first_octet    second_octet     third_octet    fourth_octet
    0b1010        0b1011000        0b1010         0b10011

>>>>>>>>>>>>>>>>>>>>END >>>>>>>>>>>>>>>>>>>>>>>

 

Its would be simple to do if gone through Exercise 1 . Instruction is to get ip address as input from user and need to convert the IP address to binary and print on screen as required.

I have already discussed in last post ,how to convert element of list into binary , just to summarise ,

Lets understand the same by the help of an example ,let consider user enter ip address as 10.10.10.0 which is stored in list as element as octet by help of split method

bin

if we check the type of each element of list ,its string ,so we cannot use the bin and hex function on string as it  works only on integers , if tried to work bin function on string, the following error will be observed:

> TypeError: ‘str’ object cannot be interpreted as an integer

bin2

So we need to change the string into integer while using the bin or hex function on element of the list.

>>>bin(int(a[0]))

bin3

Its same content from last post , lets move to exercise .

raw_input =input(“Enter the IP address “).split(‘.’)

Code will get the  input from user in form of ip address where each octet is separated by ‘.’ , so we have used split(‘.’) method to split each octet as element of list raw_input.

Next instruction is to convert IP address into binary .We have to work one by one each octet  and it should be noted that the type of  element of list is string so we need first convert  type to integer  and then  execute bin function of each octet.

first_octet = bin(int(raw_input[0]))
second_octet = bin(int(raw_input[1]))
third_octet = bin(int(raw_input[2]))
fourth_octet = bin(int(raw_input[3]))

So we have converted each octet of ip address  into binary , lets print it as required in instructions:

print

So we are done with the exercise , find the whole code below for reference.

CODE :

script2

OUTPUT:

scrip2_out

I tried to acheive the exercise result  with the help of for loop , i was able to get the required result but able to print on screen row wise instead of column wise ,working to work upon the same and will come with the updated code, time being find the same exercise code where output is printed in row wise

CODE : 

script21

OUTPUT:

script21out

 

So we are done with Exercise 2 , I will come back soon with Exercise 3 .

 

Smiles 🙂

 

Categories: Routing

Learning Python: Week2 (Printing, Numbers, and Lists) -Part 2

2 May 2017 2 comments

As discussed in last post  ( https://crazyrouters.wordpress.com/2017/02/25/learning-python-kirk-byers-python-course/  ) , i will be sharing the my learning on weekly basis as course continues. This will not only motivate me but also help others who are in phase of learning python 3.

Now its time to go for the exercise , already shared the notes related to week 2 in last post (https://crazyrouters.wordpress.com/2017/04/30/learning-python-week2-printing-numbers-and-lists-part-1/) , surly it will help to understand exercise and solve it.Lets begin with first exercise :

>>>> EXERCISE 1 >>>>>>

I. Create a script that does the following
A. Prompts the user to input an IP network.

        Notes:
        1. For simplicity the network is always assumed to be a /24 network

        2. The network can be entered in using one of the following three formats 10.88.17.0, 10.88.17., or 10.88.17

    B. Regardless of which of the three formats is used, store this IP network as a list in the following format [’10’, ’88’, ’17’, ‘0’] i.e. a list with four octets (all strings), the last octet is always zero (a string).

        Hint: There is a way you can accomplish this using a list slice.

        Hint2: If you can’t solve this question with a list slice, then try using the below if statement (note, we haven’t discussed if/else conditionals yet; we will talk about them in the next class).

>>>> CODE <<<<

if len(octets) == 3:
    octets.append(‘0’)
elif len(octets) == 4:
    octets[3] = ‘0’

>>>>>>>>>>>>>>

C. Print the IP network out to the screen.
D. Print a table that looks like the following (columns 20 characters in width):

      NETWORK_NUMBER   FIRST_OCTET_BINARY      FIRST_OCTET_HEX
      88.19.107.0                    0b1011000                            0x58

>>>>>>>>>>>>>>>>END >>>>>>>>>>>>>>>>>>>>

Solution :

First step is to get the input from the user , that can  be done by using input

raw_input =input(“Enter the IP address “).split(‘.’)

we are taking the dynamic input i.e IP address  from user and storing the each octet in form in list by using the split method . split(‘.’)  method used to split the Ip address into octet.

Next instruction is that user may enter ip address in   following three formats 10.88.17.0, 10.88.17., or 10.88.17 ,regardless of which of the three formats is used, store this IP network as a list in the following format [’10’, ’88’, ’17’, ‘0’]

If user enter only 3 octets of ip address, we will add the fourth octet by using append(‘0’) method else if all four octets are entered, we will changed the third_octet value to ‘0 ‘ .

if len(raw_input) == 3:
     raw_input.append(‘0’)
elif len(raw_input) == 4:
     raw_input[3]=’0′

Next instruction is to convert first octets of Ip address into binary and hexadecimal.There is built in function to convert the decimal  into binary or hexadecimal ,but works only on integer values  not on strings.

Lets understand the same by the help of an example ,let consider user enter ip address as 10.10.10.0 which is stored in list as element as octet by help of split method

bin

if we check the type of each element of list ,its string ,so we cannot use the bin and hex function on string as it  works only on integers , if tried to work bin function on string, the following error will be observed:

> TypeError: ‘str’ object cannot be interpreted as an integer

bin2

So we need to change the string into integer while using the bin or hex function on element of the list.

>>>bin(int(a[0]))

bin3

So same method  will be used in our program to convert each first octet of ip address into bin and hex.

binn = bin(int(raw_input[0]))
hexx = hex(int(raw_input[0]))

Next instruction is used to print the output on screen as  below format

NETWORK_NUMBER   FIRST_OCTET_BINARY      FIRST_OCTET_HEX
 88.19.107.0                       0b1011000                            0x58

We will be using join method to join each element of list to get the output in form of X.X.X.X..We have joined the each element of list raw_input by using join method.

net_num = ‘.’.join(raw_input)

So we have got the Network number, binary and hexa , now need to print as mentioned in instruction. We  will format method the print the required output.

print(“{:20}{:20{:20}”.format(“NETWORK_NUMBER”,”FIRST_OCTET_BINARY”,”FIRST OCTET_HEX”))
print(“{:20}{:20}{:20}”.format(net_num,binn,hexx))  

 

So we have done now :).Here is final code for reference :

CODE:

script1

OUTPUT:

script1_output

 

Smiles 🙂

 

 

 

Categories: NOTES, Python, Routing Tags: , , , , , ,

Learning Python: Week2 (Printing, Numbers, and Lists) -Part 1

30 Apr 2017 1 comment

As discussed in last post,  ( https://crazyrouters.wordpress.com/2017/02/25/learning-python-kirk-byers-python-course/  ) , i will be sharing the my learning on weekly basis as course continues. This will not only motivate me but also help others who are in phase of learning python 3.

Kirk discussed about the printing ,raw_input,numbers,List and Tuple . Few of my friends asks to include  summery in form of notes about whatever  learned from course ,then further proceed with exercise.

So i will be sharing the  very short notes before  proceeding with the exercise

 

NOTES:

 

Kirk talks about the format syntax to print and method to get the input from the user.

 

Format method used to print

 

format

We can also provide the input in any sequence and call it accordingly in print statement as in example below:

format1

{1}  – calls input provided as sequence 1 i.e “ Dubes”

{0} – -calls input provided as sequence 0  i.e “30”

{3} – -calls input provided as sequence 2 i.e “Delhi”

 

Input method to get the dynamic Input from the user

Script:

format3

Output:

format3_output

 

Numbers :

Already discussed about the string method split in week 1 ,we can convert each octet of IP address into binary and hexadecimal as below

number

As above, we are converting integer 172 into binary ,not string ‘172’ ,as ip_add is list having values stored as string , so we need to convert the same into integer to make binary and hex function to work upon them.

>> bin(int (ip_add.split(‘ . ‘)[0]))

so we have changed string type into integer.Below snapshot show example to covert ip_add octet into binary and hex.

number1

 

List :

If we want to remove the list element , we can go ahead with the help of pop ,remove and del.

POP: Removes the list element based on index, it reflect the pop value in output.

Remove: Removes the list element based on value not index.

Del :Deletes the list elemet based on index

pop

Note : ****List is mutable means that list value can be changed. If a and b is pointed to same list , if a element is change in b , there will be change in element b as a and b  both points to same memory.

Let’s have a example for the same.

list

So how to go for scenario , where we need to change the element of list a , but not element b ?

We can use slice method to fulfil the above requirement.

 

slice.png

 

So, i am finished with the Notes .Next post i.e Part 2 will  have the exercise related to whatever we have covered in Notes.

 

 

 

 

 

 

 

 

 

 

 

 

Categories: NOTES, Python Tags: , ,

Learning Python: Week1 (Preliminaries and Strings)

15 Apr 2017 Leave a comment

 

As discussed in last post  ( https://crazyrouters.wordpress.com/2017/02/25/learning-python-kirk-byers-python-course/  ) , i will be sharing the my learning on weekly basis as course continues. This will not only motivate me but also help others who are in phase of learning python 3.

Kirk discussed about the string methods in first week ,where he also put some exercise for us to work upon.The exercise seems to be simple for python experts ,but its  good learning exercise for the beginners who are in process of learning Python.

This post will focus only on the python exercise  for week 1.

Exercise:

1 ) Need a python script where user echo an input as IPv4 address and our task is to split into its octets.

 

Code

1c

Output

1o

 

We have used the system specific function  defined to get the user input and print the output. Sys.stdin is used for all interactive input by user whereas sys.stdout is used for the output of the same.

Here we are using echo to send the data to sys.stdin .We have entered input as  “Hello ! How are You” .Which gets print out the text on screen.

We can also used the fileinput.input() function to read the file or interactive input by user, same shown in below code.

We have to modify the code so that user enter the Ipv4 address and get the Ip address to be split into octets

 

Code

2c

Output

2o

 

We have used string method line.split() to split the ip address into octets. But here comes the new problem ,we don’t want newline character ‘\n’ in output. We need to get rid of the same.

 

Code

3c

As in above mentioned code ,I tried to used string method string.rstrip(‘\n’) on the output list ,but it gave error ‘list object has no attribute ‘rstrip’

That means list does not support rstrip().

So it makes us to think further other method to get rid of newline character ‘\n’. There are two ways to achieve the required result.

 

Code-way1

4c

Output

4o

Above code has used  the rstrip() method on the specific  element of the list  rather than whole list

 

Code-way2

5c

Output

5o

 

We have modified the code as shown above  , we are working first to get rid of the newline character by using the rstrip() method on the initial  string input by user and then going for the strip of the ip address into different octets resulting output as a list . It Seems more straight forward 🙂

 

Exercise 2

 

  1. Use the split method to divide the following IPv6 address into groups of 4 hex digits (i.e. split on the “:”) FE80:0000:0000:0000:0101:A3EF:EE1E:1719 and use join method to reunite your split IPv6 address back to its original value.

 

Its bit simple , if you gone through last exercise . It is a easy part just need to use the split() and join() method to do the needful.

 

Code:

6c

Output :

6o

 

 

 

Learning Python -Kirk Byers Python Course

25 Feb 2017 10 comments

Learning is process and there is no end to it. I came across Kirk Byers  python series and subscribed to the same .

The next Learning Python course starts on April 13th. I should receive the first class on that day. Reviews for this course is positive .Hopefully i will be able to follow the course as schedule and would share my learning as the course  proceeds.

About Kirk Byers :

He is  CCIE (emeritus) in routing and switching and have extensive Python experience. Since 2014, he has  been teaching Python and Ansible to network engineers. he also writes the Netmiko Python library and contributed the IOS driver to NAPALM.

 

Categories: Python
%d bloggers like this: