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

Blogger templates

Showing posts with label Python Programming. Show all posts
Showing posts with label Python Programming. Show all posts

Sunday, 16 August 2020

Difference between generator and function in python.

 Any python function that has ‘yield’ inside the function is a generator function. A normal function in python uses ‘return’ to return a value from the function.

There are three properties in generator function

  • Function uses ‘yield’ to return from function.
  • Function caller uses ‘next’ function to traverse the function.
  • And when end of the function is reached then “StopIteration” exception is called automatically by python.  

Following screenshot shows a generator function. In the following function there are two ‘yield’ to return two value from the function.

During function execution, whenever function encounters the YIELD, it returns the value and function goes to sleep with all context information.

The function wakes up when caller calls the function using ‘next’ function and the function starts execution till it encounters the next ‘yield’ and if no ‘yield’ is encountered and it reaches the end of the function and ‘StopIteration’ exception is raised by function.

In the following screenshot, i have called ‘next’ function two times and so first ‘10’ is returned and then ’20′ is returned.

As there are two yield in the function, the two ‘next’ command will work fine. The third call of ‘next’ function will raise ‘StopIteration’ exception as shown in the below screen shot.

Share:

Sunday, 9 August 2020

Which one is better- Python or C++ ?

 

Both python and C++ are good in their own fields. Python focuses on software quality and readability and simplicity of code. Compared to C/C++, python requires less code compared to C or C++. For example a “Hello World” program in C/C++ will require at least 5–6 lines of code but in case of python it will be just one line of code to write “Hello World” program.

Software quality is mandatory in python and it is not a option in python. Application development and software quality always goes hand-in-hand in python. But if you compare this with C or C++, application development is done first where developers focuses only on application development and later one more project is planned to focus on software quality.

Python is now very vast and it’s library is increasing day by day. One can develop many application for GUI, Gaming, data analysis, machine learning, deep learning, visualization and the list is continuously growing.

Only minus point of python is that it is slow and so it is not as efficient as compiled language like C,C++ or JAVA. But still there is workaround in python for this. Python has the ability to integrate with C API and that perfectly merges Python with C code. This means merging of easy coding in python and faster and efficient execution of C/C++. NumPy and Pandas libraries that are widely popular for data analysis are built on this framework that merges python and C API.

In summary, i would say we can’t directly compare C and Python because both are good in their own field. One should check the possibility to merge both language to get simple coding in python with faster execution of C/C++.

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

Blogs