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

Tuesday, July 21, 2015

Object Oriented Programming with Python

Object oriented programming is the way of looking at things in hand as object. Think Object as a real life thing with certain properties and attributes. Suppose we have a list of student,we think about students -they have a name, age, class,grade etc. as their properties or attributes and some method like finding average number, finding next grade etc. So, we generalize the concept of student as class Student and every individual student is the object of that class. Lets see the python programming examples  -

class Student:
        def __init__(self,name,age):
                self.name=name
                self.age=age
                self.grades=list()
        def __str__(self):
                return "Name :%s"%(self.name)+" "+"Age:%2d"%self.age
        def set_grades(self,grade):
                self.grades.append(grade)
        def avg_grades(self):
                return float(sum(self.grades))/len(self.grades)

Look at the example above, we have defined a class Student in the first statement. Notice the colon and indentation. Like other object oriented programming language we need to or rather we should  initialize classes with their attributes. The class Student has two attributes which need to be passed when we want to create an instance of the class. So, to create an Student object we need to write like below -

a=Student("Jhon",23)

This will create a Student object with name "Jhon" and age as 23. Next we have __str__() method, which is nothing but a show value kind of method. Write str(a) to understand what it is.
Now, we have not supplied the grades any value in the initialization phase of the class. To add grades to the Student we have created we have to write -

a.set_grades(89)

a.set_grades(78)
a.set_grades(99)
a.set_grades(79)
a.set_grades(76)

The next method avg_grades() will simply sums all the grades , then take  average and returns it.
To run it, you should write something like -
a.avg_grades()

Now look at the example below - 

class Grad_Student(Student):
        def __init__(self,name,age,university):
                Student.__init__(self,name,age)
                self.university=university
        def __str__(self):
                return "Name :%s"%(self.name)+" "+"Age:%2d"%self.age+"  "\
                       +"University:%s"%self.university

       
The class above inherited from the Student class i.e. it can access to all the methods defined in the Student class. Look at the initialization process, the __init__method here takes three argument with one extra argument 'university' and then it calls the __init__ of Student class which initialized the name and age attributes of the class and the other attribute university is initialized here.

 We can use the set_grades() and avg_grades() of the Student class from the Grad_Student class.


Also look at the __str__() here. This  is the example of polymorphism. The method described here overwites the method in Student class. So when run str(a) it will run the method here. 



Please visit my website http://pythonbeginner.in for further studies and learn python effortlessly.

Saturday, July 4, 2015

Python loops and conditionals

Like many other programming language Python also has loop controlling and conditional operators, they are not renamed to something else. We can iterate through any list or anything which are close relative list.
For loop for tuple or list:
Suppose we have a list a=[1,3,5,7,6], we want to iterate through the list and do some operation, we can do it by -
for i in a:
   i=i+1
   print i

The above snippet will iterate through the list and add one to each element, then print it. See the use of for loop in the program. The temporary variable i  iterate through the list a. So we don't have to know the number of element  in the list. We can use the same method for tuple. Or not? See it yourself as the tuples are not modifiable.
The same can be done in while loop.
i=0
While i<len(a):
   print i
   i=i +1

for and while loop works in a same way, i.e. iterate through a range or until some conditions are met. while loop is particularly useful when you need to write an infinite loop. Just write -
 while 1:
     print "looping continuously"
you can also write while True, too. Python has a boolean True and False keyword, so True is a viable option.

See the video for a better understanding.

The other important thing in python is conditional operator. if-elif-else can be used to see if certain condition or met and execute some statement if the condition is true.
It works like this  - 
if somecondition==true:
   execute something
elif seeothercondition==true:
   execute other statement
else :
   do this statement
You can see here how if else works in python.Let's see it by an example -

    value=raw_input("Enter a value") #To have user input through console
    value=int(value) #converting the value to an integer
    if value<5:
       print "You entered less than five"
    elif value>=5 and  value<10:
       print "You enter between 5 to 10"
    else:
       print "You entered beyond 10"

     

In the program we are checking the value of variable value and executing print statement. see the use of <,>,and,= statement in the program. The raw_input is used for prompt user to enter a value.You can use while 1: to loop forever through the program.



Tuesday, June 30, 2015

Python tuple

Tuple in Python is more or less like list but with one very important difference i.e tuple is not modifiable or editable. That means once declared  you can't change the value of a tuple.
To declare a tuple just like
>> a=() or
>>a=tuple()
The above two will create an empty tuple.
You can write like below to create a tuple with value.
>>a=(2,1,35,3,7,3)
>>a
(2,1,35,3,7,3)
The insert, remove, push, pop these commands will not work in tuple as worked in a list.
We can count the number of occurrence of an element by count method
>>a.count(3)
2
Also we can find the first occurrence of any element by index method.
>>a.index(3)
3
We will discuss more about tuple when we will use it in  real program.


Feautured Post

Python Trivia Post: enumerate()

Python has a very useful inbuilt function, which is called enumerate(). This is needed whenever you need the numbering of a certain element...