Fibonacci Series using recursion.

Fibonacci Series using recursion

In Python the Fibonacci numbers, commonly denoted Fn form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. Here is the example of Fibonacii Series using Recursion in Python.

Fibonacii using Recursion in Python

Thank you, your comments are appreciated.

Object Oriented Code in Python

Object Oriented Code in Python

This is time to go through the code to demonstrate the concept of OOP in Python. This is well known fact that OOP can not be done without Class and Object. So here is the example of Class and Object in Python.

Code of OOP in Python

Output of above code is –

Output of two Students Object

Now lets start understanding the code line by line. First line to Fourth line nothing but class level comment. Make it as clear and understandable as you can. Line no 8 is the beaning of class structure [class student(object): ]. It says that we are going start a class named Student and (object) is saying that this is new style of writing class and at last : is for starting the block statement. This is similar to { } sign in Java or C++

Next is [def __init__(self, name, marks):]. Here init is a function to initialise the object of class. If you are adding it well and good, if you left it don’t worry Python will insert it with default argument self on behalf of you. But here I used two extra parameters (name and marks), that means when ever user will try to create the object of Student class he/she have to pass these two parameters. After that self.name and self.marks are two instance variables which are getting initialised by parameters of init method. Remember the style of writing init method, it starts with two underscore sing and ends with the same two underscore sign.

Now you can write N numbers of methods a per your business requirement. Remember that if the function takes self as parameter are instance method and will get called by the object directly. [def getStudent(self):] this is the only function we are heving right now.

Lastly we need to create object and call method associated with that. [s1 = student(‘Robin’, 98)] will create one object s1 of student class. As my init method takes two parameters except self. So need to pass. and lastly call getStudent() on s1. You will get output as above. I created two Objects, you can create as much as you want.

That’s it. You are done with basic example of Class and Object in Python. Comments and feedback are always welcome. Bye bye…

Basic Object Oriented Concept in Python

Object Oriented Concept in Python

Object oriented programming in Python is easy most then other OOP languages. Object oriented programming concept relates the programming to real world entities. You can reuse your code by creating multiple instance. Here import thing is to understand the concept of class and object.

Concept of Class and Object

Class – Classes are blueprint of real world situation, if you want to represent students details in terms of programming then you create a class named Student and add attributes to it as per your requirement like sname, fname, class, rollno, contactno, addr etc or any information that you want to get from Student.

Object – Objects are real instance of class created earlier (Student). You can create as much as object as per your requirement. Each object will have its own attribute associated and if you call the object you will able to get all the attributes detail associated with that object. Suppose rahul is the object of Student then rahul will carry all other infomations [sname-paul, fname-john, classs-9, addr- xyz colony]. Lets understand with code using Python in next post.

Exception Handling in Python

Exception Handling in Python

Exception handling is one of the important task which is covered in every language in many ways. Python also supports exception handling in their own way. Python exception handling is similar to Java exception handling. Like Java try – catch block python also having similar try – except block.

Any code that you that you think is going to throw exception must be written inside the try block. If exception occurs then the control will automatically transfer to except block and the code written in the except block will get executed. There are some predefined or built-in exception classes in python whose super class is Exception. The exception classes are –

  • FileNotFoundError
  • PermissionError
  • InterruptedError
  • NameError
  • OverflowError
  • RuntimeError

And many more similar exception classes are there for specify the error or exception in python. You can refer to Python Doc
https://docs.python.org/3/library/exceptions.html for more details of exception. But don’t worry you no need to worry about keep remembering the names of above exception classes. What you can do is to use Exception class which is super of all other exception class.

Next part of exception is throwing the exception as and when you want your code to through it. So for doing that if your remember Java we are having throw statement. In python we are having raise statement to throw specific exception from try block which will get cached by except block. Here is the example to demonstrate simple use of try-except block and exception handling in Python.

Code to demonstrate the use of Exception Handling

Output of the above programs are as follows –

Happy Scenario of code where no Exception

Exception Handling Scenario

The second output is from except block. If you want to contribute feel free to comment and give output.

Writing data to file in Python

Writing data to file in Python

Writing data to the file is another important topic need to be discussed for Data file handling in Python. We can write data to file by using write() or writelines() function. write() function takes string as argument where writelines() takes list of lines as argument. But before all these thing we need to open the file object by using open() function with w or a as file mode. For example –

fout = open(‘address.txt’, ‘w’) here file mode used is w in place of that we can use a as file mode. The difference between w and a is when you will open a file with write mode it will create a new file called address.txt or else if file exist will delete all existing data from the file and start writing from the first line. Where as when you open a file using append mode will create a new file if not exist else will start writing to the file at the last position in a file. Now lets see the example of writing data into file –

Code to write date to file

The output of the program will look like this –

The first output section is taking input from user till your says n. And next output is displaying all the content appended at the list of the file.

If want to discuss something, feel free to comment. Thank you.

File Handling – Reading data from text file

Reading data from text file

Python supports file handling and allow to read and write data from file . Python supports two kind of files 1. text file 2. binary file. Text file is used to read and write data into file where data will store in human readable format and binary file will store the data in binary format which is readable using program only.

Now without wasting our time lets jump into example. So here is the example –

Code to read text file using read()

In this example we opened addr.txt file in read mode. The default mode is read mode only so you can write open(‘addr.txt’) is also valid. Now once the connection is established between file and file object you can call read() function on the file object. Next step is to print. Last but very important work is to close the connection using close() function. Here is the output-

Output of read from file

That’s it. In next chapter we will discuss about reading data using readline() and readlines().

Bar Chart in Python

Bar Chart in Python

Bar chart implementation is also very interesting using Matplotlib. In last post we discussed about Line Chart implementation in Python using Matplotlib. So for installation of Matplotlib and to start using it, you can refer Line Chart in Python page.

Now lets focus on Bar Chart Implementation. To generate bar chart using matplotlib you need to call pyplot.bar() function and need to pass minimum x and y co-ordinates values in terms of list. Lets see the example code first.

Bar Chart using Matplotlib

Apart from the basic parameter which is x and y co-ordinates value you can pass the width value, I used 0.5 to keep distance between bar charts. Next parameter we can pass is COLOR. Color can be single value like ‘red’, in this case all the bars color will be of Red color. If you want to appear your bars to be multicolor then you can pass list of colors to color parameter of bar() function. Here four color has been used, so first four will be as is and fifth onward color will get repeated. Lets see the output of above bar chart code.

Multicolor Bar Chart using Matplotlib

That’s it, you can try your own to get this beautiful bar chart using above code.

Line chart in Python

Line chart in Python

Drawing chart in other languages are one of the difficult task and need to do lots of exercise to plot a simple chart. But here in case of Python, plotting a chart is only 2 or 3 lines of job. So lets start to learning line cart plotting in Python.

For doing that you need to install third party library Matplotlip (https://matplotlib.org/ ). You can install matplotlib using pip command in the command prompt. Steps to import and use Matplotlip –

  1. You need to open command prompt and type below command on command line if pip package is already installed in your machine and path of python home directory is already set in your system.
  2. type pip install matplotlib on the command prompt
  3. It will start downloading matplotlib from internet and will take few minutes to get it install.
  4. If you are getting success message on command prompt then you are done with installing.

Next step is to import matplotlib. In your program you need to write import matplotlib.pyplot as pyplot in very first line of your program to use pyplot facilities in your program. Here is the sample code to create line chart.

Code to plot Line Chart

If you will see this code, First line is importing matplotlib.pyplot after that second line is plotting linechart using two data, one is using days name on x-axis of chart and second is average temperatures on y-axis. Last line is displaying the chart which is plotted in second line. Now the output of this code will look like –

Output of Line Chart

Check Right Angle Triangle using sides.

As you aware that this is very common question asked in exams in school. Basic logic to get this is to check if any of the sides square value is equal to the addition value of squares of other two side. For example if a, b, c are three sides then if a**2 = b**2+c**2 then this triangle will be the right angle triangle. This logic is valid for any of the side from a, b, c. Lets have a look into the program.

Program to Check Right Angle Triangle

Output –

First Side – 6
Second Side – 5
Third Side – 4
NOT A RIGHT ANGLE TRIANGLE

First Side – 3
Second Side – 4
Third Side – 5
Given data is making a RIGHT ANGLE TRIANGLE

Dictionary and Json in Python

Dictionary and Json in Python

Dictionary is one of the important feature of Python of key : value pair. Dictionary is mutable datatype of python. Python dictionary is similar to Json data which is used widely now a days.

Python comes with pre-loaded feature of JSon in-coding and de-coding. To use python json in-coding you need to import json in your file. Here is the example-

Dictionary and Json in Python

Once you run this program the output will look like this –

output – Dictionary and Json