Learn Python Relative to C++ : Part 2

Before going deep into python if you missed the basic in the first part of my blog you can read it over here.
So lets just get our self a bit more deep in beautiful world of python.

Branching Magic in Python :

As everything else Branching and looping has been made a lot easier in python. Branching in C and many other languages are achieved using If / If-else / else-If ladder / Switch case. Same goes with python. We can implement branching in python same way as this lets see an example :
C implementation :

if(a == b)
{
    printf("a and b are equal");
}
else
{
    printf("a and b are not equal");
}

Python implementation :

if a == b:
    print "a and b are equal"
else:
    print "a and b are not equal"

Just look at the colons at end of condition statement and else clause. Condition statements maybe written in parentheses or without that totally depends on user.(Python Is Freedom 😛 ). Just take care of the indentations as any code under that if must be written with same indentation (4 spaces to be exact). So only interesting thing here are the colons and Indentation.
After looking at it you must be thinking that so that makes it same as C++. But wait a minute lets see few tricks. Here let me introduce two good operators is and in. Python try to be as close to english like sentences as it can. Lets see this with an example :

a = 6
a = b
print "a is b : ",a is b
new_list = [1 , 4 , 6 , 10]
print "a in new list : ",a in new_list

Output :

a is b : True
a in new list : True

Look at two things here one is use of both the operators and second is how we used print statement here. In detail now with knowledge of is operator we can write above example as :
if a is b (than Do something…) instead of if a == b.
{Note : For more understanding and fundamental on is
is is identity testing, == is equality testing. what happens in your code would be emulated in the interpreter like this:

>>> a = ‘pub’
>>> b = ”.join([‘p’, ‘u’, ‘b’])
>>> a == b
True
>>> a is b
False
(here join is a method applied on a collection to join all of its elements with designated literal,that is ” means nothing here so it makes ‘pub’ with nothing in between list elements passed as method parameters.)
}
in is one of my favourite. Makes working with lists ,sets ,Dictionary ,tuples and even string a charm. It returns True / False so can be used in as a condition statement. But it is most widely used for checking if a dictionary key is available or not before calling its values :

>>>new_dict = {'harry':'potter' , 'albert':'einstein' , 'issac':'newton'}
>>>'harry' in new_dict.keys()
True
>>>'potter' in new_dict.keys()
False

Here keys() method of dictionary returns a list of all keys in that dictionary. Now it is good to be sure that dict has a harry before calling for its value and thats what we do here. Remember ‘potter’ is a value in dictionary not a key so for it we will get False. Use values() method for getting all the values of that dictionary.
Now as we have seen is and in we may as well look at not in python. This is same as negation in C++ which is achieved with ! for logical operations and ~ for bitwise operations. Here is python you can neatly write :
a is not b
which returns inverse result of a is b. or :
a not in new_list
which is inverse to a in new_list. Here you can see how much english like statements we are using.
We are forgetting one more thing and that is concatenation in print function using ‘,’. When you want to print value of a variable using print you don’t use quotes and can concatenate it with previous string using ‘,’ and may also use another string right after it also using ‘,’.
so : print ‘value ‘, a ,’is a’ will print “value 6 is a”.
Switch case and If else ladder are same as C++ in python just semantic difference.You can look at that on python docs.

Looping away with Python :

First lets look at the While loops in Python. Well they are almost same as C (ofc with the freedom we get with python included :P).Lets see syntax of while in python :

i = 0
while i < 10:
    print i
    i = i + 1

Nothing special above it simply shows python syntax to write a while loop.You can see that it is almost like its C version. Just don’t go with Do While in Python…

Now time to see some fantastic looping with python which is demonstrates by For loops.
We just saw how String , List , Tuple and Dictionary works in python. Using For loop we can iterate over each of the elements of this objects (yes every thing is an object in python).
Lets see this with an example for loop that loops over a list of items :

food_list = ['Burger','Hot Dog','Pizza','Pasta']
for food in food_list:
    print food

output:

Burger
Hot Dog
Pizza
Pasta

Here we can see the neat and great implementation with in operator. The for statement is nearly an English like statement. You would not even need a comment to tell you what that piece of code will do. That is the great thing about using python.
Most of the time this will be the most useful loop ,but only most of the time. For rest we need a loop that will just execute a certain amount of time while taking care of the looping index increment or decrement.In C we use it like follows :

for(int i = 0 ; i < index ; i++)
{
   //Do looping
}

In python we can do same using a function called range(). Let us look at it as it can be real useful for few integer tricks used in many programs.

>>>>range(5)       #Format : range(stop_index)
[0,1,2,3,4]
>>>>range(1,5)     #Format : range(start_index , stop_index)
[2,3,4]
>>>>range(1,10,2)  #Format : range(start_index , stop_index , increment_by)
[1, 3, 5, 7, 9]

Code above is nearly self explanatory. So this range function generates a list of integers on which our for loop can iterate now :

sum = 0
for num in range(5):
    sum = sum + num
print sum

So using this much basic it is really easy to go on and make many simple to moderately complex python programs. Next step comes to introduce functions in python and than go forward with class and more object oriented approach towards making a code that can be called a dynamic approach and easy to debug and maintain on long run. Lets give a brief look at functions in python.

How Does Functions Do Their Function in Python :

Any program may have one or more functions as its building block (if not classes). In C to build a function we gotta tell computer :
1> what that function will return
2> what is it called (The Name to call that function)
3> what parameters it will take and of course as it is C we gotta tell what type of that parameters that will be.
So it is something like below:

unsigned integer long_name(int param1 , int param2 , char so_on)
{
    //Fuction block
    return ans;
}

Hmmm that’s ok how does python do it? Well , of course it does it in a great way… lets look at the python way :

def great_name(param1 , param2 , so_on):
    #Function block
    return ans

Wahh, so many good thing just happened there. First of all no function return type !!! You know what that means?? It means FREEDOM!!! 😛 . It means function may return any type or kind of object you desire you will not have to change return type if your function generates something else. Lets see one case. Your function does some computation in it and it returns an answer depending on the parameters passed to it. Now this answer maybe an Integer or a float number and dramatically some time it may find no answer and Still we can still use this same function that will return Integer or a float or even a None (Which is also an object that represents Nothing!!) without any change in function code.
Next interesting thing is that even parameters don’t have any type associated with them. So you may pass any type of parameter to that function of yours. In C this is called function overloading and for each overloaded type you have to create new function returning new type. Anyone having tried function overloading in C will see the reduced effort programmer will put to write same code in python..
{ Note: With Great Powers Comes Greater responsibility…
It is great to use the type freedom provided by python but if that kind of power is miss used by a novice programmer he may end up having too many type casting errors. So When using functions that may return more than one type in python be sure that the code area that receives its result will be ready for that and will not generate an exception. You may not refrain from using return type check with type() function of python and process result accordingly.}
Some times it is great to have default values of parameters passed in the function:

def myFunction( param1 , param2 = 10)
    print param1
    print param2
#in calling program
>>>>myFunction(5 , 6)
5
6
>>>>myFunction(5)
5
10

Here you can see that we set the default value of param2 as 10. So if no argument for param2 is passed than 10 will be taken as its argument. Also remember that using function like:
def myFunction( param1 = 10 , param2):
will give an error : “SyntaxError: non-default argument follows default argument”
All the default arguments may be only used at end of all the non-default arguments (and it is easy to understand why so….if you can use your head that is :P).
Another way to call a function is as follows:
>>>>myFunction( param2 = 5 , param1 = 4 )
This will change the order of passing arguments but the result will be same as:
>>>>myFunction( 4 , 5 )
This kind of call is particularly useful when a function have too many arguments and many of them have default values. So in calling function user will just pass few arguments to the parameters that he needs to override leaving rest as it is and without bothering about the order of parameters…(So cool!!)

Let us end our preliminary discussion on python over here. Python is not so good just because its cool implementation and user friendliness. It also have great libraries written by many people contributing to open source. All their hard work is available free and easily to any user who will need it. There are few fantastic libraries like Matplotlib , scipy , pylab , numpy for plotting and calculation works, Tkinter , wxpython , pygames for developing easy Gui applications , there are libraries to integrate matlab code with python , jython for java , and Cpython for C integration , pyserial and pyusb are great libraries for hobbyist who want there micro controllers to communicate with there PC. You may like to know about raspberry pie which is a little computer like arm development board that can be programmed using python. Want to develop a complex website with descent web back end? use Django-python. Django helps you make a functional website with admin interface up and running in just few minutes and with nearly insignificant amount of code written. And the best thing is that like java your python application or script will work for any platform may it be windows , Linux or mac OS X.
In addition to that if you find your self stuck at any unsolvable bug or issue python has a great community which will be more than willing to help solve your bug(most of the time your solution is one google search away).

I will be going on and introducing new libraries of python now on ( As i myself keep learning them one by one ). Hope it will be useful for you and you all loved reading and learning the basics till now.

Happy Codding !!!

Advertisements

One thought on “Learn Python Relative to C++ : Part 2

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