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.

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

Saving Python object to File (serialization)

Saving Python object to File (Serialization)

Serialization and de-serialization is the process to store python object structure into file and viceversa. All because of using pickle module this process is known as pickling (serialization) and un-pickling(de-serialization). Pickling can get achieved by dump() method and un-pickling can be achieved by load() method of pickle module. But using this module in your program first you need to import pickle in your file. Here is the example of pickling(serialization).

Dump Student Object to file

This code will create a class called Student and at line no 29 Object of Student is created stu1. After that data is being loaded using readMarks() method at line no 31. One data is loaded, created file object f1 of ‘student.log’ file at line no 34. Later on used pickle.dump() method to dump the data into file and at last closed() the file object.

Python with Mysql

Connect Python with MySql

Python is having very good support to connect any database. The most popular database used is mysql. Here is the example to connect Python mysql.

  1. You need to download mysql-connector from https://pypi.org from your command prompt.
  2. In command prompt type command pip install mysql-connector and wait till the package is getting install. After completion of installation you will get message “Successfully installed mysql-connector-2.1.6
  3. If pip is not working in command prompt then you need to set the path of python script and python installation folder into environment variable of your computer.
  4. Open idle prompt and check the import of mysql-connector by using import statement (import mysql.connector as mycon)
  5. If you are not getting any exception from Python Interpreter then your system is ready with mysql-connector to connect Python with mysql.

This is how you can download the connector from pip and test it. Now the next step to test the connection of python with mysql. Here is the program to test and get data from mysql in python console.

Program to test Python connection with MySql Database

Output of above program will be

(1, ‘Akash’, ‘teacher’, 1, Decimal(‘20000’), Decimal(‘1200’), 1)
(2, ‘Suraj’, ‘teacher’, 2, Decimal(‘23000’), Decimal(‘1300’), 2)
(3, ‘Aman’, ‘prof’, 3, Decimal(‘30000’), Decimal(‘2000’), 4)
(4, ‘Rakesh’, ‘businesman’, 4, Decimal(‘40000’), Decimal(‘3000’), 3)

Customizing to the output as your requirement – You can customize the output as per your requirement. Here I have iterated the output in two loops. First loop is to get row from cursor and second loop is to get individual elements from the row. So variable a will have row data and variable b will have every element of the row. Lets look into the for loop.

Data iteration from the cursor object.

Output of above program will be

1 Akash teacher 1 20000 1200 1
2 Suraj teacher 2 23000 1300 2
3 Aman prof 3 30000 2000 4