Archive

Posts Tagged ‘split()’

Learning Python: Week3 (Conditionals and For Loops) -Part 2

14 May 2017 Leave a 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 Week 3 (Conditionals and For Loops) .This post will focus on exercise 1

######################## EXERCISE 1 #######################

I. Create an IP address converter (dotted decimal to binary).  This will be similar to what we did in class2 except:

    A. Make the IP address a command-line argument instead of prompting the user for it.
        ./binary_converter.py 10.88.17.23

    B. Simplify the script logic by using the flow-control statements that we learned in this class.

    C. Zero-pad the digits such that the binary output is always 8-binary digits long.  Strip off the leading ‘0b’ characters.  For example,

        OLD:     0b1010
        NEW:    00001010

    D. Print to standard output using a dotted binary format.  For example,

        IP address          Binary
      10.88.17.23          00001010.01011000.00010001.00010111

    Note, you might need to use a ‘while’ loop and a ‘break’ statement for part C.

        while True:
            …
            break       # on some condition (exit the while loop)

    Python will execute this loop again and again until the ‘break’ is encountered. 

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

 

Most of the part of this exercise is repeated one from last exercise done in week 2.

Lets take step by step , first we need a command line argument instead of prompting from the user, this can be done be sys,argv (discussed in last post )

 

scriptarg1

 

Here we are getting input from command line, restricted input not more than 2 argument.if we tried to give more than 2 argument from command line, it will through a error.

Output:

scriptarg1_out

Now we need to split the entered IP address using split method and then convert into binary. Its same as we did in week 2 exercise.

raw_input=ip_addr.split('.')

 

Above code will split the ip address into element of list separated by ‘.’ .

We will also define a list which we will be using afterward to store the ip octet converted into binary.

ip_add_new =[]

 

We will use the for loop to go through each octet of Ip address and convert into binary

for i, element in enumerate(raw_input):
 octet = (bin(int(raw_input[i])))

we will get the output as below

0b11000000
0b10101000
0b1010
0b1

Its the Binary conversion of each octet of ip address. So we are done with part a and b of exercise .Now we need to zero-pad the digits such the binary output is always 8-binary digits  longs i.e strip off the leading ‘ob’ characters from above output.

Lets first remove the ‘ob’ from each binary converted octet ,this can be easily done by string slicing.

octet_new = octet[2:]

 

octet_new will have now have binary representation of ip octet without first two character of string i.e ‘ob’ that are at index 0 and index 1.

In short , now octet_new will have following values

 0 octet   11000000 
 1 octet   10101000 
 2 octet   1010 
 3 octet   1 

so ‘ob’ is removed from each octet’s binary output.

Now we have the make each octet with zero-pad such that binary output is eight digit.

so for that we run while loop , it checks for the length of octet and gets output as if condition fails (len(octet_new) >=8:).

if condition true , it will run the while loop adding the ‘o’ to the octet binary till length of binary output becomes 8.I also need to append the element into the list which i have defined earlier i.e ip_add_new =[] with each iteration.

 

 

for i, element in enumerate(raw_input):
octet = (bin(int(raw_input[i])))
print(octet)
octet_new = octet[2:]
print(octet_new)
while True:
if len(octet_new) >=8:
break
octet_new = '0'+ octet_new
print(octet_new)
ip_add_new.append(octet_new)

 

so only  thing to focus is to join all four octet of binary representation using ‘.’

that can be easily done using  ‘.’.join method

ip = '.'.join(ip_add_new)

Now print the output using format method

 

print("\n")
print("{:20}{:20}".format("IP address","Binary"))
print("{:20}{:20}".format(ip_addr,ip))

Here is the Code from scratch for this exercise.

exercise1.png

OUTPUT:

exercise1_out

So here we are done with the Exercise 1 , will be back with exercise 2.

Smiles 🙂

     

 

 

Advertisements

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: , , , , , ,
%d bloggers like this: