Archive

Posts Tagged ‘lists’

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

28 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 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

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: , ,

Python Basics – Part 2 cont…

30 Nov 2016 Leave a comment

4.Tuples

A tuple is similar to a list. The difference between the two is that we cannot change the elements of a tuple once it is assigned whereas in a list, elements can be changed. A tuple is created by placing all the items (elements) inside a parentheses ()

  • We generally use tuple for different datatypes and list for homogeneous similar datatypes.
  • Since tuple are immutable, means value can not be changed.
  • Tuples that contain immutable elements can be used as key for a dictionary. With list, this is not possible.
  • If you have data that doesn’t change, implementing it as tuple will guarantee that it remains write-protected.

Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses)

CODE:

tuple1

OUTPUT:

tuple1out

 

 

5 .Dictionary

Python dictionary is an unordered set of key:value pairs , with the requirement that the keys are unique (within one dictionary). A pair of braces creates an empty dictionary: {}.Dictionary have no concept of order among elements.

Keys are unique within a dictionary while values may not be.The values of dictionary can be any type ,but the keys must be of an immutable such as strings,numbers or tuples.

CODE:

dict.PNG

 

OUTPUT:

dictout

%d bloggers like this: