Python hello world program video tutorial.

Video Tutorial on Python hello world program

Video Tutorial of Hello world program in Python

This is Video tutorial uploaded on youtube to understand how to write first python program. This also includes

  1. From where you can download Python setup
  2. How to install it
  3. How to open IDLE script
  4. How to write code in interactive mode of IDLE.

Hope you will like this video and will give your valuable suggestion on this video link.

Insertion Sort in Python

Insertion Sort in Python

Insertion sort is also one of the common sorting technique used. In this technique sorting place after each element encounter. Story of sorting is very simple. Very first node is ignored as it is known as sentinel node. Now from second element will be chosen for sorting. The insertion sort technique checks it position in 0 to n-1 element in the same list where n is the current position and insert the element. This works get repeated till the last element gets sorted. So you will observe that after every elements sorting the list get sorted till the element position. Here is the code and example of Insertion sort.

lst = [15, 6, 13, 22, 3, 52, 2]
print("original list is - ", lst)
for i in range(1, len(lst)):
    key = lst[i]
    j = i - 1
    while j >= 0 and key < lst[j] :
        lst[j + 1] = lst[j]
        j = j - 1        
    else :
        lst[j + 1] = key
    print("List after {0} pass - ".format(i),lst)
print('Now sorted list is - ', lst)

Now we will see the output of the code –

original list is – [15, 6, 13, 22, 3, 52, 2]
List after 1 pass – [6, 15, 13, 22, 3, 52, 2]
List after 2 pass – [6, 13, 15, 22, 3, 52, 2]
List after 3 pass – [6, 13, 15, 22, 3, 52, 2]
List after 4 pass – [3, 6, 13, 15, 22, 52, 2]
List after 5 pass – [3, 6, 13, 15, 22, 52, 2]
List after 6 pass – [2, 3, 6, 13, 15, 22, 52]
Now sorted list is – [2, 3, 6, 13, 15, 22, 52]

Thank you. If you have any query you can ask and post comments to me. I will try to reply.

BUBBLE SORT IN PYTHON

Bubble Sort in Python

Bubble sort is one of the import sorting technique which is implemented in many languages. Here we can implement Bubble Sort technique in Python as well. For this we need an array (Same Data element) which is nothing but a List in Python. The technique is to sort the adjacent element in order (ascending or descending). It you will do so, the largest element in the array will get sorted in every pass. So after every pass one largest element will get sorted in ascending order if sorting is done in ascending order. Here is the sample code for bubble sort and its output after every pass.

'''
Created on Jan 10, 2020<br>
Bubble sort implemented in Python in ascending<br>
order using List.<br>
@author: admin@pythonport.com<br>
'''
lst = [56, 778, 87, 55, 11, 33, 97]
print('Original list is - ', lst)
n = len(lst)
for i in range(n):
     for j in range(0, n - i - 1):
         if lst[j] > lst[j + 1] :
             lst[j], lst[j + 1] = lst[j + 1], lst[j]    
     print('Sorted list after {0} - {1}'.format(i+1,lst))
 print('Sorted list is - ', lst)

Output of above code will look like –

Original list is – [56, 778, 87, 55, 11, 33, 97]
Sorted list after 1 – [56, 87, 55, 11, 33, 97, 778]
Sorted list after 2 – [56, 55, 11, 33, 87, 97, 778]
Sorted list after 3 – [55, 11, 33, 56, 87, 97, 778]
Sorted list after 4 – [11, 33, 55, 56, 87, 97, 778]
Sorted list after 5 – [11, 33, 55, 56, 87, 97, 778]
Sorted list after 6 – [11, 33, 55, 56, 87, 97, 778]
Sorted list after 7 – [11, 33, 55, 56, 87, 97, 778]
Sorted list is – [11, 33, 55, 56, 87, 97, 778]

Thank you . Please post comment you have any query based on Bubble sorting.

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