Join my course at Udemy (Python Programming Bible-From beginner to advanced )

Blogger templates

Monday, 25 May 2020

Iteration



Python provides various ways to iterate over sequences and perform repetition tasks. for and while loop provides the way to iterate, range, zip, enumerate and map are specialized function to loop through sequences. 

In the similar line, iterator provides simpler way to loop through sequences and it provides faster alternative as it runs at C language speed.

What is iteration object ?

A object is a iteration object if it has following two functionality :
- Object with __next__ method to advance to next result.
- Object that raises ‘StopIteration’  exception at the end of the series.

In python, a file object is an iteration object by default. Following examples show how file object can be used as iterator to browse the file.

File object as iterator object.

In the following example we can see that file object (f) is a iterator object and hence True is returned. 

f= open("HelloPython.py")
iter(f) is f
True

As explained above, if file object is a iterator object then
- We should be able to use f.__next__ to traverse through the file.
- And when end of file is reached then "StopIteration" exception should be raised.

Following example shows the implementation of __next__ function of file as a iterator object. Note that "HelloPython.py" has three line and we can traverse the file line by line using __next__ function of iterator.

f = open("HelloPython.py")
print(f.__next__())
print(f.__next__())
print(f.__next__())
Hello Python-1
Hello Python-2
Hello Python-3

As HelloPython.py  file has just three lines, the next call of f.__next__() should raise "StopIteration" exception.

print(f.__next__())

 StopIteration                             Traceback (most recent call last)
<ipython-input-29-db2988a815ca> in <module>()
    ---> 12 print(f.__next__())
StopIteration:


Using next(f) instead of __next__() 

Python provides next function that internally calls __next__() function. This way we can use neater function to loop through the file. 

f = open("HelloPython.py")
print(next(f))
print(next(f))
print(next(f))

Hello Python-1
Hello Python-2
Hello Python-3


Iteration of file object with for Loop

Above example shows the traversal of file object is not a neater way as  calling next() or __next__  function every time is cumbersome. As shown the example below, for loop provides easier way where calling __next__() function and checking for StopIteration function is automatically checked. 

for line in open("HelloPython.py"):
    print(line)
Hello Python-1
Hello Python-2
Hello Python-3

List and Dictionary as iterator

By default list and dictionary are not a iterator object but it is possible to change the them to a iterable object using the iter function as shown below.

Following code shows how to change the list object to an iterator and then use that in for and while  to loop through the sequence object.

##List Iterator – with while loop
L=[1,2,3,4]
I=iter(L) ## change the list to iterator
while True:
    try:
        nextElem = next(I)
    except StopIteration:
        break;
    print (nextElem)
1
2
3
4

##List iterator -- Using FOR Loop
L=[1,2,3,4]
for x in L:  ##changes to iterator and traverses list element
    print(x)
1
2
3
4


In the similar way it is possible to change dictionary to iterator object and then traverse the dictionary object. Following example shows the use of dictionary iterator with for and while loop.

D = {"first":1, "second":2, "third":3}
I=iter(D)
while True:
    try:
        nextElem = next(I)
    except StopIteration:
        break;
    print (nextElem, end=",")
first, second, third,


##Dictionary Iterator
D = {"first":1, "second":2, "third":3}
for x in D:
    print (x, end=",")
first, second, third,
The above example shows how to convert list and dictionary to an iterator using iter  function This function can be used to change other python datatype to a iterator and then use the iterator to traverse the object.

Conclusion

In the post we have gone through iterator that can be used as an alternative to have a neater and faster way to traverse through the python object. In the next post we will go through comprehension that is another way to traverse through python object.
Share:

Saturday, 23 May 2020

range, zip and enumerate



The traditional looping technique of python is For and While loop but Python also provides more specialized looping techniques in the form of built-in function. Note that the specialized functionality can also be achieved using For and While loop but the built-in function in cleaner and neater way.

  • Range - creates sequence of numbers that can be used with any another python statement.
  • Zip - Zip function combines multiple object element by element and returns the combined or zipped version of new object in the tuple format.
  • Enumerate - It generates both values and indexes of the item and returns both of them in a tuple format.
  • map  - map allows to apply a function to each element of the container sequence object and the result can be collected as the return value of the function.

In this post we will go through range, zip and enumerate built in function. We will study map object in the later post.

range 

range built-in function allows to generate numbers based on start, end and skip values provided.

list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list(range(2,10))
[2, 3, 4, 5, 6, 7, 8, 9]
list(range(2,10,2))
[2, 4, 6, 8]

range built-in function works with for loop to iterate through sequence containers based on the numbers created via range function that can be used as index to the sequence containers. Following example shows multiple ways to traverse string.

##Print String
S="HelloPython"
for i in range(0, len(S)):
    print(S[i], end=",")
H,e,l,l,o,P,y,t,h,o,n,
##Skip Print String
S="HelloPython"
for i in range(0, len(S),2):
    print(S[i], end=",")
H,l,o,y,h,n,

zip

zip allows to use multiple sequence in parallel and it returns the combined or zipped version of element in the tuple format.

##Zipping two list.
L1 = [1,2,3,4,5,6,7]
L2 = [8,9,10,11,12,13,14]
ZipList = zip(L1,L2)
print(list(ZipList))
[(1, 8), (2, 9), (3, 10), (4, 11), (5, 12), (6, 13), (7, 14)]


zip can be also be used in conjunction with for loop to loop through combined version of sequence object element by element.

##Zipping two list with FOR loop.
L1 = [1,2,3,4,5,6,7]
L2 = [8,9,10,11,12,13,14]
ZipList = zip(L1,L2)
for (x,y) in ZipList:
    print(x,y,sep=",", end="\n")
1,8
2,9
3,10
4,11
5,12
6,13
7,14

if there is size mismatch then zip takes the sequence element with lowest size and then combines the element and skips the elements that can't be combined.


##Zip with more than two lists.
L1 = [1,2,3,4,5,6,7]
L2 = [8,9,10,11,12,13,14]
L3=[15,16,17,18,19,20,21]
L4=[22,23,24,25,26,27,28]
ZipList = zip(L1,L2,L3,L4)
for (x,y,z,k) in ZipList:
    print(x,y,z,k,sep=",", end="\n")
1,8,15,22
2,9,16,23
3,10,17,24
4,11,18,25
5,12,19,26
6,13,20,27
7,14,21,28


zip can also be used to create a dictionary by passing keys and values in separate list.

##Joining two strings  with Mismatch in length
S1="abcde"
S2="fghijkl"
zipS = zip(S1,S2)
for (x,y) in zipS:
    print (x,y,sep=",", end="\n")
a,f
b,g
c,h
d,i
e,j

enumerate

 It returns offset and indexes of the sequence objects. enumerate creates a generator object so that it can be used in conjunction for loop. 

S = "Hello"
for (index, item) in enumerate(S):
    print(index, item, sep = ",", end ="\n")
0,H
1,e
2,l
3,l
4,o 

It can also be used to traverse a file line by line using manual loop with next function or in a automatic loop with For. This is possible because enumerate returns generator object that provides automatic way to traverse sequence object item by item.

S="HelloPython"
x=enumerate(S)
print(x)
print(next(x))
print(next(x))
<enumerate object at 0x0000023CA27D0C18>
(0, 'H')
(1, 'e')

Conclusion

In this post we have seen range, zip and enumerate to traverse through python container objects and performed specified operation. In the next post we will go through iteration and comprehension that provides another approach to traverse a python container objects.
Share:

Wednesday, 20 May 2020

Python FOR statement





Python For loop is similar to While loop and it loops through the items in ordered sequence. There is optional Else  statement with For loop that executes after the For statement block is executed. Following is the syntax for the Python For Loop.

For Loop Syntax

Rules

Following are the rules for For Loop statement:
  • At every iteration one item from sourceObject is assigned to targetObjectItem variable.
  • After assigning to targetObjectItem, block of code inside For loop is executed.
  • else  statement is optional in For Loop.
  • If else statement is defined, then it will be executed after For loop unless the control has come out of the for block with break statement.
  • Control comes out of For loop when all items from sourceObject is assigned to targetObjectItem.
Note: else statement in While and For loop should not be confused with the working with If/else block in Python where else  is only executed when If  is not executed. For While and For loop else code block is always executed unless the break statement is executed in For block.

Examples with List, Tuples and String

The below code shows the example of For loop with list, string and tuple. All three are sequence data types and  at every iteration For loop takes element one by one from left to right from the sequence container and print the element. Note that syntax for all three are similar and there is no change in because of different sequence objects.


##Printing items in list
for x in ["first", "second", "third"]:
print (x)

first second third

##Separate character from string
str = 'HelloPython'
for x in str:
print (x, end=" ")

H e l l o P y t h o n

##With Tuple
T = [(10,20), (30,40), (50,60)]
for (x,y) in T:

10 20
30 40
50 60



Examples with Dictionary

For loop integrates well with dictionary as well with similar syntax as that for list and tuple.  Following code prints the key  and keys and values from dictionary.

##Print Key value from dictionary.
##printing ‘key’ from dictionary
D = {"first":1, "second":2, "third":3}
for key in D:
    print(key, end = " ")

first second third 

##printing (key,value) from dictionary
D = {"first":1, "second":2, "third":3}
for (key,value) in D.items():
    print(key,value, sep=",", end = "\n")

first,1
second,2
third,3

Examples with Extended Assignment

For loops integrates well with extended assignment as well. For details on extended assignment please check my post at Python Assignment.

##With extended assignment
S = [(1,2,3,4,5), (6,7,8,9,10)]
for (a, *b, c) in S:
    print(a,b,c, sep=",", end="\n")

1,[2, 3, 4],5
6,[7, 8, 9],10



Conclusion

We have seen how For loop works and how easily it integrates with any container object with almost similar syntax of target and source objects. For loop may not be the faster option in Python and that's why Python provides functionality like List Comprehension, map, filter, reduce etc  that can imitate   the functionality of For loop with faster execution. We will discuss all alternatives of for loop  in later posts.
.

Share:

Monday, 18 May 2020

Python While Statement


Python While loop is a compound statement that allows block of statement inside the WHILE block. Block of statement inside While statement runs until the While condition is True. The control comes out of while loop when condition is False.

Following is the syntax for While Statement:

While Statement

Syntax

Following are the set of rules for writing While statement
  • When test1 condition is True  then statement1 and statement2 will be executed.
  • When test1 condition is False then statement1 and statement2 will not be executed.
  • Else statement with While loop is optional.
  • If Else statement is defined with While loop then then it will be always be executed except for one scenario. 
  • If the control comes out of While loop because of break inside While loop then Else statement will not be executed.

Example1 : While + Else statement

a=0; b=5
while a < b:
    print ("A, B ",a,b)
    a = a+1
else:
    print ('Out of while LOOP’)



A, B  0 5
A, B  1 5
A, B  2 5
A, B  3 5
A, B  4 5
Out of while LOOP

In the above code, while statement will return TRUE as long as the value of a is less than b.  Note that the  value is incremented inside the loop for every iteration.  When the value of a is greater then  then the control comes out of while loop. After the control comes out of while loop then else block code is executed and "Out of while LOOP" is printed.

Example2 : While + Break + Else statement

a=0; b=5
while True:
    print ("A, B ",a,b)
    a = a + 1
    if a > 4:
        break;
else:
    print ('Out of while LOOP’)


A, B  0 5
A, B  1 5
A, B  2 5
A, B  3 5
A, B  4 5 

Above code is similar to Example1 with slight change in while loop by adding break statement. The only difference between Example1 and Example2 is that in Example2, control comes out of while loop because because of break statement. And because of this Else statement will not be executed and that's why "Out of while LOOP"  will not be printed in this case.

Summary

While statement is comparatively easier loop in Python and it's functionality is similar to any other programming language like C, C++ and JAVA. Similar to While, python provides For loop that we will cover in our next blog post.
Share:

Friday, 15 May 2020

Python IF statement




Python  IF statement is compound statement that allows it to embed multiple statements  inside the IF block. The statement that can be included inside IF statement can be any Python statement like IF, WHILE, FOR or any other python statement.

Syntax

Python Syntax for IF statement is as below :

IF Statement
Above figure shows the basic syntax of Python IF statement. 

Following are set of rules for writing IF statement :

  • If 'test1' condition return 'True' then code block inside If statement ('Statement1' and 'Statement2') will be executed.
  • 'elif' code block is optional.
  • 'elif' must be following by a condition. In the above syntax, 'test2' defines the condition for 'elif' and if 'test2' returns True then Statement3 and Statement4 will be executed.
  • else  block is option.
  • No condition is required in else  statement.
  • If the test conditions for If  and elif returns false then only Statement5  and Statement6 will be executed.
  • There can be only one If  and else block in the statement.
  • There can be multiple 'elif' block in the statement.

IF-ELIF code basic examples

Following code shows the basic example of IF statement.

num = 50
if (num < 70)
   print ("Needs improvement")
elif (num > 70):
   print ("Congratulation !! You got distinction ")

Needs improvement

In the above IF block, based on the 'num' value control will either go to If  or elif  code. Since num=50,  so test statement of If  loop will be True and output will be printed as "Needs Improvement"

num = 80 
if (num < 70): 
   print ("Needs improvement")
elif (num > 70):
   print ("Congratulation !! You got distinction ")

Congratulation  !! You got distinction 


In the above IF block, based on the 'num' value control will either go to If  or elif  code. Since num=80,  so test statement of If  loop will be False. Then the test statement of elif block will be evaluated. In this case it will retirn True and so print statement of elif will be executed.

Incorrect logic to be taken care in IF-ELIF 

num = 30 
if (num < 70): 
   print ("Needs improvement") 
elif (num < 30): ##Dead code. 
   print ("Congratulation !! You got distinction ")

Needs Improvement

One should take care that the test condition for If and elif are mutually exclusive. In the above block elif code is dead code as whenever test condition for elif is True then test condition for If block will also be True and hence control will also go to If block and never to elif block.


IF-ELIF-Else block

x = "low" 
if x == "low": 
   print ( "Average marks is 30") 
elif x == "below average": 
   print ("Average marks is 70") 
elif x == "Average": 
   print ("Average marks is 90") 
else: 
   print ("Grading is not proper") 

Average marks in 30

The  above code shows the If clock with If, elif and else block. Based on the value of x, control will go to If block. Please note that if one write such code they need to make sure that condition in If and elif code are mutually exclusive othere there will be chance of introduction of redundant code.

Shortcut IF statement

num = 50 
if (num < 70): 
    print ("Needs improvement") 
else : 
    print ("Congratulation !! You got distinction ")

The above 4 lines of code of If-else can be written in one line as per following syntax.

num = 50 
print ("Needs improvement") if (num < 70) else print ("Congratulation !! You got distinction ")


As evident from the above code, If  block statement is written before If  and else  and corresponding print statement is written in the same order as the code above. In terms of functionality, both code are same but it terms of readability, second code block is better.


IF statement alternative

Python also provide dictionary based syntax as an alternative of If  statement.

x = "Distinction" 
y = {"Distinction" : 90, "No distinction" : 50}[x] 

90

The above statement returns the value by passing the dictionary key as an argument to dictionary in square bracket.


Conclusion 

IF statement is one of powerful python statement that is used in almost all python application to take decisions. This is simple statement to understand and  write the code. 

Share:

Thursday, 14 May 2020

Python Assignment Statement

Any variable that assigns a literals to a python variable is called assignment statement. 
Following  are some example of assignment statement in python.

               a=10

Above .statement does the following :
- Creates a python variable 'a'
- Assigns a integer object with value = 10
- Make variable 'a' point to the integer object with value = 10.

a=10

Properties

Python assignment has following properties :
1) Assignment creates references
2) Variables are created when it is first assigned. Unlike C,C++ and JAVA, dynamic typing allows python  not to declare the data type when variables are created.

Scenarios where implicit assignment is done are as follows :
     - Module imports
     - Function arguments
     - Class definition

Various types of assignment in Python 

Basic Assignment

Variable assignment deals with basic variable assignment as follows :

               a=10   ## Pointing to integer
               a="hello Python"  ##Pointing to string
               a=10.2   ## Pointing to float.

In python, variable and python object as two distinct entities, variable are just a way to keep track of the corresponding object. Because of this it is possible for a variable to just change references to point to  objects with different datatype. In the above example variable 'a' is first pointing to integer 10, then  to a string "hello Python" and then to a float number 10.2.

Tuple, List and Sequence assignment 

Tuple, List and String assignment take the advantage of positional value of elements in tuple, list and string.
               a, b = 10, 20  ##Tuple assignment
               c,d = [10,20]  ##List assignment
               e,f,g,h,i = "Hello"  ##String assignment

The above assignment syntax assigns the value based on the positional order. For tuple and list assignment, the first value(=10) in list/tuple will go to variable 'a' and second value(=20) of the tuple/list will go to variable 'b'. In the similar way 'e','f','g','h','i' will be assigned the corresponding character from "Hello" string based on position.

Extended Sequence Assignment

In the above tuple, list and string assignment, it is mandatory to match the no of elements on the left side and the right side. If there is mismatch then there will be a error.

                    a,b = "Hello"  ##String assignment ERROR

So the above assignment statement will be error as left side there are just two variables and right side there are 5 characters in the string.

To take care of these error python has provided extended sequence assignment. It allows to use '*' before the variable to assign more than one element (character in case of string) to a variable. We can correct the above example as below :

                    a,*b = "Hello"  ##String assignment ERROR

                    Output
                    >>> a
                    'H'
                    >>> b
                    ['e', 'l', 'l', 'o’]

'a' will be assigned "H" and variable 'b' will be assigned a list of remaining characters.

Multiple Target Assignment

It allows multiple variable to be assigned to a value in one line. Please note that following statement will be assigned to same integer object will value equal to 10.

                    a = b = c = 10  ##Multiple target assignment

Representation of the statement is as shown below. All three variable 'a','b' and 'c' is pointing to same python integer object with value =10. 


a=b=c=10

Augment Assignment

Augment assignment makes the developer life easy by enabling him/her to shorten the statement of addition, subtraction etc. In short a=a+10 can be replaced with augment assignment as below:


                              a += 10

The same functionality is present for other expressions as  -, /, //, %, ** etc. Augment assignment has two advantages over normal assignment :
- Lesser to type
- Augment assignment runs faster than normal assignment.

Augment assignment is faster because it does the 'in-place' changes. Following are the two ways to add new element in list :
                                              L = L + [100, 101] ##Creates new list
                          L += [100,101]  ##Does in place change in existing list.

In the above addition the augment assignment update the new list in the existing list while basic addition creates a new list and appends the list. So one need to be careful when using augment assignment because of in-place changes in augment assignment.

Conclusion 

In this article we have seen python assignment statement and four different types of assignment statement.  One needs to be careful about assignment as many times it may create references.





Share:

Feature Top (Full Width)

Pageviews

Search This Blog