Home > Python, Routing > Learning Python: Week3 (Conditionals and For Loops) -Part 4

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

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 3

##################### EXERCISE ########################

IV. Create a script that checks the validity of an IP address.  The IP address should be supplied on the command line.
A. Check that the IP address contains 4 octets.
B. The first octet must be between 1 – 223.
C. The first octet cannot be 127.
D. The IP address cannot be in the 169.254.X.X address space.
E. The last three octets must range between 0 – 255.

For output, print the IP and whether it is valid or not.

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

 

In this exercise, user will enter IP address on the command line and will be checked for valid IP address depending over the conditions.

So let’s start with code to get the IP address on the command line from user using sys.argv.

As discussed in last exercise ,if the input is more than 2 argument, it will throw output as “Error Made”

import sys

if len(sys.argv) == 2:
 ip_addr = sys.argv.pop()
 print("The IP address is :",ip_addr)
else:
 print("Error Made")

If we run the above code , we will get the output as below

C:\Users\609807949\Documents\Personal\Python\kirk\week 3>py test1.py 10.10.10.1

The IP address is : 10.10.10.1

if more than 2 argument entered by user

C:\Users\609807949\Documents\Personal\Python\kirk\week 3>py test1.py 10.10.10.1
20.20.20.1
Error Made

So we have got the input as Ip address on the command line from user. Let’s split each octet of  ip address using split () method

ip_addr_new = ip_addr.split('.')

We have used the Nested If else loop to check all the below required conditions

A. Check that the IP address contains 4 octets.
B. The first octet must be between 1 – 223.
C. The first octet cannot be 127.
D. The IP address cannot be in the 169.254.X.X address space.
E. The last three octets must range between 0 – 255.

if (len(ip_addr_new)) == 4:
 if (int(ip_addr_new[0]) > 1 and int(ip_addr_new[0]) < 223 and int(ip_addr_new[0]) != 127):
 if (int(ip_addr_new[0]) != 169 and int(ip_addr_new[1]) != 254):
 if (int(ip_addr_new[1]) >0 and int(ip_addr_new[1])< 255 and int(ip_addr_new[2]) >0 and int(ip_addr_new[2]) < 255 and int(ip_addr_new[3]) >0 and int(ip_addr_new[3])< 255 ):
 print("Ip address is valid")
 else:
 print("Ip address is Invalid")
 else:
 print("Ip address is Invalid")
 else:
 print("Ip address is Invalid")
else:
 print("Ip address is Invalid")

 

Following   code Checks for condition A  that the IP address contains 4 octets.

if (len(ip_addr_new)) == 4:

 

Further belowcode Checks for condition B and C the first octet must be between 1 – 223 and first octet cannot be 127.

if (int(ip_addr_new[0]) > 1 and int(ip_addr_new[0]) < 223 and int(ip_addr_new[0]) != 127) :

Code to Check for condition D  that the IP address cannot be in the 169.254.X.X address space.
if(int(ip_addr_new[0]) != 169 and int(ip_addr_new[1]) != 254):

Now remains the last condition E that the last three octets must range between 0 – 255.

 if (int(ip_addr_new[1]) >0 and int(ip_addr_new[1])< 255 and int(ip_addr_new[2]) >0 and int(ip_addr_new[2]) < 255 and int(ip_addr_new[3]) >0 and int(ip_addr_new[3])< 255):

So we are done with all the required conditions, if any above mentioned condition fails , we should get output as “Error” otherwise output as “Valid IP”

Here is the Code from scratch for this exercise.

exercise3.PNG

Let’s check for each condition by providing valid and invalid input.

 

exercise3_out.PNG

Method 2 

The above code is not concise , lets have better code for same problem

Let’s start from scratch ,

import sys

if len(sys.argv) != 2:
 sys.exit("Usage: ./scriptarg2.py ")

ip_add = sys.argv.pop()

As discussed earlier, It will exit the script , if argument is not equal to 2 , further userlast input will be pop into ip_add

Lets define valid_ip as true , we will using for genuine ip address.

valid_ip =True

valid_ip =True

 

As user input is in decimal format , we need to split each octet

octets = ip_add.split('.')

Now lets check condition A  i.e length of octet should be 4.

if (len(octets)) != 4:
 sys.exit("The number of octet is invalid: ")

we will use for loop to get each octet and store them in different variable , also changing the type of each element into int as we will be performing checks on basis of integer

for i , octet in enumerate(octets):
 try:
 octets[i] = int(octet)
 except ValueError:
 sys.exit("\n\nInvalid IP address: {} \n".format(ip_add))

first_octet, second_octet, third_octet, fourth_octet = octets

Now task remains to check all the required conditions for input to be valid Ip address.

First checked the valid condition for first octet.

if first_octet &lt; 1:
 valid_ip = False
elif first_octet &gt; 223:
 valid_ip = False
elif first_octet == 127:
 valid_ip = False

 

Below code checks the condition that the IP address cannot be in the 169.254.X.X address space.

if first_octet == 169 and second_octet == 254:
 valid_ip = False

 

Now remains the last condition that the last three octets must range between 0 – 255.

for octet in (second_octet, third_octet, fourth_octet):
 if (octet &lt; 0) or (octet &gt; 255):
 valid_ip = False

Lets print whether the provided IP address is valid or not

if valid_ip:
 print ("\n\nThe IP address is valid:{}".format(ip_add))
else:
 sys.exit("\n\nInvalid IP address: {}".format(ip_add))

Overall Code

import sys

if len(sys.argv) != 2:
sys.exit("Usage: ./scriptarg2.py ")

ip_add = sys.argv.pop()

valid_ip =True


octets = ip_add.split('.')

if (len(octets)) != 4:
sys.exit("The number of octet is invalid: ")


for i , octet in enumerate(octets):
try:
octets[i] = int(octet)
except ValueError:
sys.exit("\n\nInvalid IP address: {} \n".format(ip_add))

first_octet, second_octet, third_octet, fourth_octet = octets

if first_octet < 1:
valid_ip = False
elif first_octet > 223:
valid_ip = False
elif first_octet == 127:
valid_ip = False

if first_octet == 169 and second_octet == 254:
valid_ip = False


for octet in (second_octet, third_octet, fourth_octet):
if (octet < 0) or (octet > 255):
valid_ip = False

if valid_ip:
print ("\n\nThe IP address is valid:{}".format(ip_add))
else:
sys.exit("\n\nInvalid IP address: {}".format(ip_add))

So done with this exercise , will be back with new post .

smiles 🙂

 

 

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: