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.

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

GCD and LCM in Python

GCD and LCM in Python

The logic to find the GCD and LCM is quite simple. First write a function to get GCD and then write function to get LCM of the number. GCD can get calculated by the logic to find reminder after dividing one number by another, next time dividing the divisor by reminder left out. Continue the process till divisor is greater then zero. Now to get LCM we need to apply logic to divide the multiplication of numbers by the GCD value of numbers. Like if a and b are two numbers then the LCM will (aXb)/gcd(a,b). Lets look into the program.

GCD and LCM calculation in Python.

Output will be like this –

Enter first number – 4
Enter second number – 12
GCD of 4 and 12 is = 4
LCM of 4 and 12 is = 12.0

Python Basic

Python Compound Data Types
(List, Tuple, Dictionary and String)

Python Compound data type are most powerful datatypes in compare to other languages. Python having four most important data types (List, Tuple, Dictionary and String). Lets start discussing it in brief.

List

List is the very first compound data type in python that can hold multiple values like array and indexed. Data will be enclose within square braces [] and separated by comma. The difference between normal array and list is- list can hold multiple value of multiple data type where as array can hold only same kind of data. For example –

lst = [4, ,6.7, ‘Hello”, ‘c’]

Here a list is declared with name lst and holding an integer, a float, a string and a single character.

Tuple

Tuple s another compound data type in python that can hold multiple values and indexed. Like array or list but the elements of tuple is immutable (can not changed). Data will be enclose within parenthesis () and separated by comma. For example –

tpl= (4, ,6.7, ‘Hello”, ‘c’)

Here a Tuple is declared with name tpl and holding an integer, a float, a string and a single character.

Dictionary

A dictionary is a collection or compound data type which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values.

dict = {'Name' :'Ramesh',
'age': 35,
'gender':'male',
'marks':98.5}

Here a Dictionary is declared with name dict and holding key value pair of name, age, gender and marks.

String

String literal are the datatype which is most common and most useful. You can store a String in double quotes or singe quotes. String is indexed data type and mutable in place.

strdq = "I am String literal" #String with double quotes
strsq = 'I am String literal'  #String with single quotes 
print(strdq)     #print string in python 
print(strsq)

Here a String is declared with strdq and strsq where strdq defined using double quotes and str sq defined using single quotes.