Friday, 9 August 2024

Python - Multithreading

 ----------------------------------------------

Python Multithreading

----------------------------------------------

Multitasking:

---------------

-computer execute more than one program or task simultaneously or concurrently.


Types of Multitasking:

--------------------------

1. Process based Multitasking

2. Thread based Multitasking


1. Process based Multitasking:

-------------------------------------- 

-Each task is a separate independent process

Example for OS Level:

--------------------------

a) Typing a Python Program in the editor

b) Listening audio songs from the same system

c) Downloading new songs from the internet


2. Thread based Multitasking:

-------------------------------------- 

-Each task is an independent part of the same program

Ex:

 a) car games

 b) Access Internet

 c) User work with word(Typing,check grammar and print)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

thread  :

-------- 

-A thread is a sequence of such instructions within a program that can be

 executed independently of other code.

-A thread is simply a subset of a process


Multithreading

------------------

-Multithreading is defined as the ability of a processor to execute 

  multiple threads concurrently.

-Multithreading is the ability of a program or an operating system process

 to manage its use by more than one user at a time and to even manage 

 multiple requests by the same user without having to have 

 multiple copies of the programming running in the computer.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Thread Methods:

--------------------

1. start():start the thread activity

2. run()  :thread activity

3. join() :wait until the thread terminates

4. getName() : get thread Name

5. setName() : set thread Name

6. isAlive() : checks whether a thread is still executing

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

# creating thread in 3 ways

1) Creating a Thread without using any class

2) Creating a Thread by extending Thread class

3) Creating a Thread without extending Thread class

   ----------------------------------------------------

1) Creating a Thread without using any class

  -----------------------------------------------------

 #Program 1: Creating a Thread without using any class

 #Method 1

from threading import *

def display():

    for i in range(1,5):

        print(i," Thread")

#creation of thread object to execute display

t1=Thread(target=display)

t1.start()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 2: Creating a Thread without using any class

 #Method 2

import threading

def display():

    for i in range(1,5):

        print(i," Thread")

#creation of thread object to execute display

t1=threading.Thread(target=display)

t1.start()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

     ------------------------------------------------------

2) Creating a Thread by extending Thread class

   -------------------------------------------------------

#Program 1 : Creating a Thread by extending Thread class

 #Method 1

from threading import *

class MyThread(Thread):

    def run(self):

        for i in range(1,5):

            print(i," Thread")

#creation of thread object to execute display

t1=MyThread()

t1.start()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 2 : Creating a Thread by extending Thread class

 #Method 2

import threading

class MyThread(threading.Thread):

    def run(self):

        for i in range(1,5):

            print(i," Thread")

#creation of thread object to execute display

t1=MyThread()

t1.start()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

     -----------------------------------------------------------

3) Creating a Thread without extending Thread class

   -------------------------------------------------------------

#Program 1 : Creating a Thread without extending Thread class

#Method 1:

from threading import *

class one:

    def display(self):

        for i in range(1,5):

            print(i," Thread")

#creation of class object

obj=one()

t1=Thread(target=obj.display)

t1.start()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 2 : Creating a Thread without extending Thread class

#Method 2:

import threading

class one:

    def display(self):

        for i in range(1,5):

            print(i," Thread")

#creation of class object

obj=one()

t1=threading.Thread(target=obj.display)

t1.start()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

------------------------------

Using Thread Methods

-----------------------------

#Program 1: using Thread Methods

from threading import *

def display():

    print("welcome")

#creation of thread object to execute display

t1=Thread(target=display)

t1.start()

print("Current Thread :",current_thread())

print("Current Thread Name:",current_thread().name)

print("Thread Name :",t1.getName())

t1.setName("jahab")

print("Thread Name ",t1.getName())

print("Identification No :",t1.ident)

print("Alive or Not :",t1.isAlive())

print("Count :",active_count())

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 2: Example Program for Multithreading(single thread)

#Method 1:

from threading import *

import time

def msg1():

    time.sleep(0.5)

    print("Welcome")

    print("Current Thread ",current_thread().getName())

try:

    t1 = Thread(target=msg1)

# starting thread 1 

    t1.start() 

except:

   print ("Error: unable to start thread") 

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 3: Example Program for Multithreading(single thread)

#Method 2:

import threading

import time

def msg1(tname,delay):

    time.sleep(delay)

    print("Welcome to ",tname)

try:

    t1 = threading.Thread(target=msg1, args=("Thread-1",5)) 

 # starting thread 1 

    t1.start() 

except:

   print ("Error: unable to start thread") 

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 4: Example Program for Multithreading

import threading

import time

def msg1(tname,delay):

    time.sleep(delay)

    print("Welcome to ",tname)

def msg2(tname,delay):

    time.sleep(delay)

    print("Welcome to ",tname)

try:

    t1 = threading.Thread(target=msg1, args=("Thread-1",5))

    t2 = threading.Thread(target=msg2, args=("Thread-2",3)) 

 # starting thread 1 

    t1.start()

    print(threading.current_thread())

    print(t1.getName())

    t1.setName("jahab")

    print(t1.isAlive())

 # starting thread 2

    t2.start()

except:

   print ("Error: unable to start thread")

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 5: Example Program for Multithreading

import threading

import time

def msg1(tname,delay):

    for i in range(1,6):

        time.sleep(delay)

        print("Welcome to ",tname)

def msg2(tname,delay):

    for i in range(1,6):

        time.sleep(delay)

        print("Welcome to ",tname)

try:

    t1 = threading.Thread(target=msg1, args=("Thread-1",5))

    t2 = threading.Thread(target=msg2, args=("Thread-2",3)) 

 # starting thread 1 

    t1.start()

 # starting thread 2

    t2.start()     

except:

   print ("Error: unable to start thread") 

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 6: Example Program for Multithreading using join method

import threading

import time

def msg1(tname,delay):

    for i in range(1,5):

        time.sleep(delay)

        print("Welcome to ",tname)

def msg2(tname,delay):

    for i in range(1,5):

        time.sleep(delay)

        print("Welcome to ",tname)

try:

    t1 = threading.Thread(target=msg1, args=("Thread-1",5))

    t2 = threading.Thread(target=msg2, args=("Thread-2",3)) 

 # starting thread 1 

    t1.start()

 # wait until thread 1 is completely executed 

    t1.join()   

 # starting thread 2

    t2.start()     

 # wait until thread 2 is completely executed 

    t2.join() 


 # both threads completely executed 

    print("Done!") 

except:

   print ("Error: unable to start thread") 

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

------------------------------------

Daemon Thread

-------------------------------------

-The Main purpose is to provide support for non-daemon threads(main thread)

Ex: Garbage Collector

Note:

------

  -Once thread started we cannot change its Daemon nature

  -Default thread Nature : Non-Daemon

  -Whenever last Non-Daemon thread terminates automatically all Daemon threads will be 

   terminated, we are not required to terminate explicitly

  -supporting jobs can be implemented by Daemon threads

  -Main Jobs can be implemented by Non Daemon threads

  -The entire Python program exits when only daemon threads are left.

Ex:

1)car game

   cars--->Non Daemon

   background Sceneries--->Daemon 

2) Cinema Shooting

    Hero,Heroines--->Non-Daemon

    Maku up -->Daemon


Methods:

---------

1) isDaemon()

2) setDaemon(True)

3) setDaemon(False)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 1 : Example for Daemon Thread

from threading import *

import time

def job1():

    for i in range(10):

        print("Job1")

        time.sleep(2)


t1=Thread(target=job1)

print(t1.isDaemon())

t1.setDaemon(True)

print(t1.isDaemon())

t1.start()

time.sleep(10)

print("End of Main Thread")

------------------------------------------------

#Program 2 : Example for Daemon Thread

import threading

import time

def print_work_a():

    print('Starting of thread :', threading.currentThread().name)

    #time.sleep(2)

    print('Finishing of thread :', threading.currentThread().name)



def print_work_b():

    print('Starting of thread :', threading.currentThread().name)

    print('Finishing of thread :', threading.currentThread().name)


a = threading.Thread(target=print_work_a, name='Thread-a', daemon=True)

#a = threading.Thread(target=print_work_a, name='Thread-a')

b = threading.Thread(target=print_work_b, name='Thread-b')


a.start()

b.start()

Python - JSON

 ------------------------------------------------------------------

Python JSON(JavaScript Object Notation Serializer)

----------------------------------------------------------------

Purpose: 

----------

-Encode Python objects as JSON strings, and decode JSON strings into Python objects.

-JSON is a syntax for storing and exchanging data.

-JSON is text, written with JavaScript object notation.

Uses:

------

-JSON (JavaScript Object Notation) is a lightweight data-interchange format

-The JSON format is often used for serializing and transmitting structured data over a network connection.

-It is used primarily to transmit data between a server and web application(client), serving as an alternative to XML.

-It is easy for humans to read and write. 

-It is easy for machines to parse and generate. 

-It is based on a subset of the JavaScript Programming Language, Standard ECMA

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

You can convert Python objects of the following types, into JSON strings:

dict, list, tuple, string, int, float, True, False, None

Difference between XML and JSON:

--------------------------------------------

-Both JSON and XML can be used to receive data from a web server.

-JSON is a Data Oriented , XML is a Document Oriented

-JSON Support arrays, XML Not support array

-JSON less secured, XML more Secured


JSON Example:

------------------

{"employees":[

    { "firstName":"Jahab", "lastName":"Deen" },

    { "firstName":"Anna", "lastName":"Smith" },

    { "firstName":"Peter", "lastName":"Jones" }

]}

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

XML Example:

------------------

<employees>

    <employee>

        <firstName>Jahab</firstName> <lastName>Deen</lastName>

    </employee>

    <employee>

        <firstName>Anna</firstName> <lastName>Smith</lastName>

    </employee>

    <employee>

        <firstName>Peter</firstName> <lastName>Jones</lastName>

    </employee>

</employees>   

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 1: Convert from JSON to Python

import json

# some JSON:

x =  '{ "name":"Jahab", "age":30, "city":"Trichy"}'

# parse x:

y = json.loads(x)

# the result is a Python dictionary:

print(y["name"])

print(y["age"])

print(y["city"])

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 2: Convert from Python to JSON

import json

# a Python object (dict):

x = {

  "name": "Jahab",

  "age": 30,

  "city": "Trichy"

}

# convert into JSON:

y = json.dumps(x)

# the result is a JSON string:

print(y)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Note:

------

1) json.dumps(x, indent=4)   - Format the result

2) json.dumps(x, indent=4, separators=(". ", " = ")) - Separators

3) json.dumps(x, indent=4, sort_keys=True)   - Order the result

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 3: Convert from Python to JSON

import json

print(json.dumps({"name": "Jahab", "age": 30}))

print(json.dumps(["apple", "bananas"]))

print(json.dumps(("apple", "bananas")))

print(json.dumps("hello"))

print(json.dumps(42))

print(json.dumps(31.76))

print(json.dumps(True))

print(json.dumps(False))

print(json.dumps(None))

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Python - Iterator

Python Iterator

---------------------

An iterator is an object that contains a countable number of values.

An iterator is an object that can be iterated upon, meaning that you can traverse through all the values.

Iterator Methods:

---------------------

1. iter()  - used to get an iterator

2. next()- next() function to manually iterate through all the items of an iterator

~~~~~~~~~~~~~~~~~~~~~~~~

#Program 1 : Example program for iterator

a=[10,20,5,7,90]

i=iter(a)

print(next(i))

print(next(i))

print(i.__next__())

print(i.__next__())

print(i.__next__())

print(next(i))

~~~~~~~~~~~~~~~~~~~~~~~~

#Program 2 : Example program for iterator

mytuple = ("apple", "banana", "cherry")

myit = iter(mytuple)

print(next(myit))

print(next(myit))

print(next(myit))

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 3 : Example program for iterator

mystr = "jahab"

myit = iter(mystr)

print(next(myit))

print(next(myit))

print(next(myit))

print(next(myit))

print(next(myit))

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Python - Events

 Python events:

-----------------

 -The program enters mainloop()  which wait for events (user actions).

 -We define the button which has a callback to the function callback().

 -master is the root window, the window where your button will appear in.

- Events can be key presses or mouse operations by the user.

Note:

----------------------

I) Mouse Events:

   ----------------------

A). Button Events:

      ------------------

1) <Button-1> = left mouse button

2) <Button-2> = middle button

3) <Button-3> = The rightmost mouse button

4) <Button-4> = defines the scroll up event on mice with wheel support

5) <Button-5>  = the scroll down. 

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

B). Motion Events:

      ------------------

1) <B1-Motion> = Left

2) <B2-Motion> = Middle

3) <B3-Motion> = Right

~~~~~~~~~~~~~~~~~~~~~~~~~~~

C). ButtonRelease Events:

      --------------------------

1) <ButtonRelease-1> = Left Button is released

2) <ButtonRelease-2> = Middle Button is released

3) <ButtonRelease-3> = Right Button is released

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

D). DoubleButton Events:

      --------------------------

1) <Double-Button-1> = Left

2) <Double-Button-2> = Middle

3) <Double-Button-3>  = Right

~~~~~~~~~~~~~~~~~~~~~~~~~~~~

E). Mouse Entered & Leave Events:

     ----------------------------

1) <Enter> = Mouse Enter to widgets

2) <Leave> = Mouse Leave from widgets

-----------------------------------------------------------------------------

II) Keyboard Events:

   ----------------------

1) <FocusIn> - Focus to widget 

2) <FocusOut> - Focus from widget

3) <Return> - User Press Enter Key

4) <Key> - User Pressed any Key

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 1 : tkbutton with onclick event

from tkinter import *

master = Tk()

 

def msg():

    print ("click!")

b = Button(master, text="OK", command=msg)

b.pack()

mainloop()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 2 : tkbutton with bind method

from tkinter import *

master = Tk()

 

def msg(event):

    print ("click!")


b = Button(master, text="OK")

master.bind('<Button-1>',msg)

b.pack()

mainloop()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 3 : tkbutton with onclick event

from tkinter import *

master = Tk()

master.minsize(300,100)

master.geometry("320x100")

 

def callback():

    print ("click!")


photo=PhotoImage(file="1.gif")

b = Button(master,image=photo, command=callback, height=50, width=150)

b.pack()

mainloop()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 4 : tkbutton with onclick event

from tkinter import *

master=Tk()

master.minsize(300,120)

master.geometry("320x120")


def add():

    a=int(a1.get())

    b=int(a2.get())

    c=a+b

    a3.set(c)#print c

def sub():

    a=int(a1.get())

    b=int(a2.get())

    c=a-b

    a3.set(c)#print c

    

def clear():

    a1.set("")

    a2.set("")

    a3.set("")

    

a1=StringVar()   #a1=IntVar()

a2=StringVar()   #a2=IntVar()

a3=StringVar()   #a3=IntVar()


t1=Entry(master,textvariable=a1)

t1.focus_set()

t1.pack()

t2=Entry(master,textvariable=a2)

t2.pack()

b1=Button(master,text="Add",command=add,width=20)

b1.pack()

b2=Button(master,text="Sub",command=sub,width=20)

b2.pack()

b3=Button(master,text="Clear",command=clear,width=20)

b3.pack()


t3=Entry(master,textvariable=a3)

t3.pack()

master.mainloop()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 5 : tkbutton with bind method

from tkinter import *

master=Tk()

master.minsize(300,120)

master.geometry("320x220")


def add(event):

    a=int(a1.get())

    b=int(a2.get())

    c=a+b

    a3.set(c)#print c

def sub(event):

    a=int(a1.get())

    b=int(a2.get())

    c=a-b

    a3.set(c)#print c

    

def clear(event):

    a1.set("")

    a2.set("")

    a3.set("")

    

a1=StringVar()   #a1=IntVar()

a2=StringVar()   #a2=IntVar()

a3=StringVar()   #a3=IntVar()


t1=Entry(master,textvariable=a1)

t1.focus_set()

t1.pack()

t2=Entry(master,textvariable=a2)

t2.pack()

b1=Button(master,text="Add",width=20)

b1.bind('<Button-1>',add)

b1.pack()


b2=Button(master,text="Sub",width=20)

b2.bind('<Button-1>',sub)

b2.pack()


b3=Button(master,text="Clear",width=20)

b3.bind('<Button-1>',clear)

b3.pack()



t3=Entry(master,textvariable=a3)

t3.pack()

master.mainloop()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 6: Button single click & double click

from tkinter import *

import sys


master=Tk()

def hello(event):

    print("Single Click, Button-l") 

def quit(event):                           

    print("Double Click, so let's stop")

    sys.exit()

    master.withdraw()


widget = Button(master, text='Mouse Clicks')

widget.pack()

widget.bind('<Button-1>', hello)

widget.bind('<Double-1>', quit) 

master.mainloop()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 7:  Mouse events

from tkinter import *


class MouseLocation( Frame ):

   def __init__( self ):

      Frame.__init__( self )

      self.pack( expand = YES, fill = BOTH )

      self.master.title( "Demonstrating Mouse Events" )

      self.master.geometry(  "275x100" )

      

      self.mousePosition = StringVar() # displays mouse position

      self.mousePosition.set( "Mouse outside window" )

      self.positionLabel = Label( self,textvariable = self.mousePosition )

      self.positionLabel.pack( side = BOTTOM )


      self.bind( "<Button-1>", self.buttonPressed )

      self.bind( "<ButtonRelease-1>", self.buttonReleased )   

      self.bind( "<Enter>", self.enteredWindow )

      self.bind( "<Leave>", self.exitedWindow )

      self.bind( "<B1-Motion>", self.mouseDragged )


   def buttonPressed( self, event ):

      self.mousePosition.set( "Pressed at [ " + str( event.x ) + ", " + str( event.y ) + " ]" )


   def buttonReleased( self, event ):

      self.mousePosition.set( "Released at [ " + str( event.x ) + ", " + str( event.y ) + " ]" )


   def enteredWindow( self, event ):

      self.mousePosition.set( "Mouse in window" )


   def exitedWindow( self, event ):

      self.mousePosition.set( "Mouse outside window" )


   def mouseDragged( self, event ):

      self.mousePosition.set( "Dragged at [ " + str( event.x ) + ", " + str( event.y ) + " ]" )


MouseLocation().mainloop()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Python - Networking

 ---------------------------

Python Networking:

---------------------------

-Sharing data between a Connected network(Wired/Wireless)


Python Network Services:

---------------------------------

There are two levels of network service access in Python. These are:

1. Low-Level Access(connect same system(client and server) via socket)

2. High-Level Access(Application level network protocols(HTTP, FTP.,,)


Socket:

--------

-A socket is the end-point in a flow of communication between two programs or communication channels operating over a network. 

Syntax:

--------

      g = socket.socket (socket_family, type_of_socket, protocol=value)


Some of the important server socket methods are:

------------------------------------------------------------

1) listen(): is used to establish and start TCP listener.

2) bind(): is used to bind address (host-name, port number) to the socket.

3) accept(): is used to TCP client connection until the connection arrives.

4) connect(): is used to initiate TCP server connection.

5) send(): is used to send TCP messages.

6) recv(): is used to receive TCP messages.

7) sendto(): is used to send UDP messages

8) close(): is used to close a socket.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Step by step Socket programming

---------------------------------------

Step1 : importing the socket library

        Ex:

            import socket

Step 2 : making a simple socket(Socket creation)

        Ex: 

            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        Here,

          1) AF_INET - address family ipv4(internet protocol version 4)

          2) SOCK_STREAM - Connection oriented TCP Protocol

Step 3: Connecting to a server (find the ip of the server)

        Ex:

             import socket 

             ip = socket.gethostbyname('www.google.com')

             print(ip)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 1: find the ip of the server using Python

import socket

try:

    ip1 = socket.gethostbyname('www.google.com')

    ip2 = socket.gethostbyname('www.gmail.com')

    ip3 = socket.gethostbyname('www.facebook.com')

    print(ip1)

    print(ip2)

    print(ip3)

except Exception as e1:

    print(e1)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 2: find the Machine host name using Python

import socket

try:

    ip1 = socket.gethostbyname(socket.gethostname())

    print(ip1)

except Exception as e1:

    print(e1)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 3 : An example script to connect to Google using socket programming in Python 

import socket # for socket 

import sys  

try: 

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 

    print ("Socket successfully created")

except Exception as err: 

    print ("socket creation failed with error : ",err) 


# default port for socket 

port = 80

try: 

    host_ip = socket.gethostbyname('www.google.com') 

except Exception as err1: 

    print ("there was an error resolving the host",err1)

    sys.exit() 

# connecting to the server 

s.connect((host_ip, port)) 

print ("the socket has successfully connected to google on port =",host_ip) 

Output:

---------

Socket successfully created

the socket has successfully connected to google on port == 216.58.200.132

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 4 : Client and server Program

Step1: (save client1.py)

-----

# Import socket module 

import socket                

  

# Create a socket object 

s = socket.socket()          

  

# Define the port on which you want to connect 

port = 12345                

  

# connect to the server on local computer

ip1 = socket.gethostbyname(socket.gethostname())

s.connect((ip1, port)) 

  

# receive data from the server 

print(s.recv(1024)) 

# close the connection 

s.close()        

----------------------------

Step2: (server1.py)

# first of all import the socket library 

import socket                

  

# next create a socket object 

s = socket.socket()          

print ("Socket successfully created")

  

# reserve a port on your computer in our 

# case it is 12345 but it can be anything 

port = 12345                

  

# Next bind to the port 

# we have not typed any ip in the ip field 

# instead we have inputted an empty string 

# this makes the server listen to requests  

# coming from other computers on the network 

s.bind(('', port))         

print ("socket binded to %s" %(port)) 

  

# put the socket into listening mode 

s.listen(5)      

print ("socket is listening")

  

# a forever loop until we interrupt it or  

# an error occurs 

while True: 

  

   # Establish connection with client. 

   c, addr = s.accept()      

   print ('Got connection from', addr) 

  

   # send a thank you message to the client.  

   c.send('Thank you for connecting') 

  

   # Close the connection with the client 

   c.close() 

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Python - Database Connectivity

 Database:

--------

- The database is a collection of organized information that can easily be used,

   managed, update, and they are classified according to their organizational approach.

- Database is also called as Backend Tool(Store and  maintenance the data)

- Database is a collection of tables(Relation)

Note:

-----

-Table  : Collection of rows and columns

-Rows  : Record or tuples

-Column : Field or Attributes


Example for Database:

--------------------------

1. MySQL

2. SQLite

3. MS SQL

4. PostgreSQL

5. Informix

5. Sybase

6. Inter-base

7. Oracle etc..


Note:   The DB-API is the standard for Pythons database interface(ODBC Support).

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Python Database Connectivity:

---------------------------------------------

-Python can be used in database applications.

-One of the most popular database is MySQL.


Steps are include in Python+MySQL :

---------------------------------

1) Install MySQL Driver :Python needs a MySQL driver to access the MySQL database.

   C:\Users\ISS\AppData\Local\Programs\Python\Python37-32\Scripts\pip install mysql-connector

Via DOS Prompt

-------------

  Step1 : (Windows+R)Run->cmd

  Step2 : cd\

  Step3 : c:\>cd Users\\ISS\\AppData\\Local\\Programs\\Python\\Python37-32\\Scripts>pip install mysql-connector

  

2) import python database interface

----------------------------------

ex:

   import mysql.connector

  

3) Create connection

  --------------------

ex:

   conn = mysql.connector.connect(user='root',password='',host='localhost',database='sample')

  

4) Define a Cursor object

-------------------------

ex:

   cursor = conn.cursor()

   

5) Create a SQL Query

---------------------

ex:

   sql=""

   

6) Execute SQL Query

--------------------

ex:

   cursor.execute(sql)


7) Close Connection

--------------------

ex:

   cursor.close()

   conn.close()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Programs:

-----------

1) Create Database

2) Create Table

3) Insert Records

4) View All Records

5) View Specific Record

6) Delete Records

7) Update Records

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 1 : Create a Database

import mysql.connector

try:

# opening a database connection

    conn = mysql.connector.connect(user='root',password='',host='localhost')    

# define a cursor object

    cursor = conn.cursor()

    sql = "create database sample1"

# execute query

    cursor.execute(sql)

# close object

    cursor.close()

# close connection

    conn.close()

    print("Successfully Created...")

except Exception as e1:

    print (e1)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 2 : Create a table

import mysql.connector

try:

# opening a database connection

    conn = mysql.connector.connect(user='root',password='',host='localhost',database='sample')    

# define a cursor object

    cursor = conn.cursor()

    sql = "create table register(roll int, name1 varchar(15),city varchar(10))"

# execute query

    cursor.execute(sql)

# close object

    cursor.close()

# close connection

    conn.close()

    print("Successfully Created...")

except Exception as e1:

    print (e1)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 3 : Insert Records

import mysql.connector

try:

    a=int(input("Enter Your Roll :"))

    b=input("Enter Your Name :")

    c=input("Enter Your City :")

    conn = mysql.connector.connect(user='root',password='',host='localhost',database='sample')    

    cursor = conn.cursor()

    sql1 = ("insert into register(roll,name1,city) values(%s,%s,%s)")

    Values=[a,b,c]

    cursor.execute(sql1,Values)

    cursor.close()

    conn.close()

    print("Successfully Inserted...")

except Exception as e1:

    print (e1)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 4 : View Records

import mysql.connector

try:

    conn = mysql.connector.connect(user='root',password='',host='localhost',database='sample')    

    cursor = conn.cursor()

    sql1 = ("select *from register")

    cursor.execute(sql1)

# fetch all of the rows from the query

    data=cursor.fetchall()

    print("roll\tName\tCity")

    print("----------------")

          

# print the rows

    for row in data :

        print (row[0], row[1], row[2])

    cursor.close()

    conn.close()

except Exception as e1:

    print (e1)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 5 : View Particular Records

import mysql.connector

try:

    roll=int(input("Enter the roll :"))

    conn = mysql.connector.connect(user='root',password='',host='localhost',database='sample')    

    cursor = conn.cursor()

    sql1 = ("select *from register where roll=%s")

    values=[roll]

    cursor.execute(sql1,values)

# fetch all of the rows from the query

    data=cursor.fetchall()

    print("roll\tName\tCity")

    print("----------------")

          

# print the rows

    for row in data :

        print (row[0], row[1], row[2])

    cursor.close()

    conn.close()

except Exception as e1:

    print (e1)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 6 : Delete Particular Records

import mysql.connector

try:

    roll=int(input("Enter the roll :"))

    conn = mysql.connector.connect(user='root',password='',host='localhost',database='sample')    

    cursor = conn.cursor()

    sql1 = ("delete from register where roll=%s")

    values=[roll]

    cursor.execute(sql1,values)

    print("Successfully Deleted...")

    cursor.close()

    conn.close()

except Exception as e1:

    print (e1)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 7 : Update Records

import mysql.connector

try:

    roll=int(input("Enter the roll :"))

    name=input("Enter username : ")

    city=input("Enter City : ")

    

    conn = mysql.connector.connect(user='root',password='',host='localhost',database='sample')    

    cursor = conn.cursor()

    sql1 = ("update register set name1=%s,city=%s where roll=%s")

    values=[name,city,roll]

    cursor.execute(sql1,values)

    print("Successfully Updated...")

    cursor.close()

    conn.close()

except Exception as e1:

    print (e1)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

-----------------------------------------------

GUI Registration Form

-----------------------------------------------

#Program 1: Create a Registration Form

from tkinter import *

import mysql.connector

import tkinter

from tkinter import messagebox


window=Tk()

window.minsize(300,200)

window.geometry("320x200")


def register():

    try:

        a=int(a1.get())

        b=a2.get()

        c=a3.get()

        conn = mysql.connector.connect(user='root',password='',host='localhost',database='sample')    

        cursor = conn.cursor()

        sql1 = ("insert into register(roll,name1,city) values(%s,%s,%s)")

        Values=[a,b,c]

        cursor.execute(sql1,Values)

        cursor.close()

        conn.close()

        messagebox.showinfo("Information","Success")

    except Exception as e1:

        print (e1)

def clear():

    a1.set("")

    a2.set("")

    a3.set("")

    

a1=StringVar()   #a1=IntVar()

a2=StringVar()   #a2=IntVar()

a3=StringVar()   #a3=IntVar()


l1=Label(window, text='Roll')

l1.pack()

t1=Entry(window,textvariable=a1)

t1.focus_set()

t1.pack()


l2=Label(window, text='Name')

l2.pack()

t2=Entry(window,textvariable=a2)

t2.pack()


l3=Label(window, text='City')

l3.pack()

t3=Entry(window,textvariable=a3)

t3.pack()


b1=Button(window,text="Register",command=register,width=20)

b1.pack(pady=10)

b2=Button(window,text="Clear",command=clear,width=20)

b2.pack()

window.mainloop()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

-----------------------------------------------

GUI Login Form

-----------------------------------------------

#Program 1 : Design Login Form

from tkinter import *

import mysql.connector

import tkinter

from tkinter import messagebox

import os

window=Tk()

window.minsize(300,200)

window.geometry("320x200")


def login():

    try:

        a=a1.get()

        b=a2.get()

        conn = mysql.connector.connect(user='root',password='',host='localhost',database='sample')    

        cursor = conn.cursor()

        sql1 = ("select *from register1 where username=%s and password=%s")

        Values=[a,b]

        cursor.execute(sql1,Values)

        # fetch all of the rows from the query

        data=cursor.fetchall()

#print the rows

        for row in data :

            messagebox.showinfo("Information","Login Success")

            os.system(“python user.py”)

            break

        else:

            messagebox.showerror("Error", "Invalid Login")

        cursor.close()

        conn.close()

    except Exception as e1:

        print (e1)

def clear():

    a1.set("")

    a2.set("")

       

a1=StringVar()   #a1=IntVar()

a2=StringVar()   #a2=IntVar()


l1=Label(window, text='username')

l1.pack()

t1=Entry(window,textvariable=a1)

t1.focus_set()

t1.pack()


l2=Label(window, text='password')

l2.pack()

t2=Entry(window,textvariable=a2,show='*')

t2.pack()


b1=Button(window,text="Login",command=login,width=20)

b1.pack(pady=10)

b2=Button(window,text="Clear",command=clear,width=20)

b2.pack()

window.mainloop()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 2 : Design Login Form using Grid

from tkinter import *

import mysql.connector

import tkinter

from tkinter import messagebox

import os

window=Tk()

window.minsize(300,200)

window.geometry("320x200")


def login():

    try:

        a=a1.get()

        b=a2.get()

        conn = mysql.connector.connect(user='root',password='',host='localhost',database='sample')    

        cursor = conn.cursor()

        sql1 = ("select *from register1 where username=%s and password=%s")

        Values=[a,b]

        cursor.execute(sql1,Values)

        # fetch all of the rows from the query

        data=cursor.fetchall()

#print the rows

        for row in data :

            messagebox.showinfo("Information","Login Success")

            os.system(“python user.py”)

            break

        else:

            messagebox.showerror("Error", "Invalid Login")

        cursor.close()

        conn.close()

    except Exception as e1:

        print (e1)

def clear():

    a1.set("")

    a2.set("")

       

a1=StringVar()   #a1=IntVar()

a2=StringVar()   #a2=IntVar()


l1=Label(window, text='username').grid(row=0,column = 0)

t1=Entry(window,textvariable=a1).grid(row=0,column = 1)


l2=Label(window, text='password').grid(row=1,column = 0)

t2=Entry(window,textvariable=a2,show='*').grid(row=1,column = 1)


b1=Button(window,text="Login",command=login,width=20).grid(row=2,column = 0)

b2=Button(window,text="Clear",command=clear,width=20).grid(row=2,column = 1)

window.mainloop()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

-----------------------------------------------

GUI View,Update & Delete Form

-----------------------------------------------

#Program 1 : Design a View,Update & Delete Form

from tkinter import *

import mysql.connector

import tkinter

from tkinter import messagebox


window=Tk()

window.minsize(300,200)

window.geometry("320x200")


#View Data

def view():

    try:

        a=int(a1.get())

        conn = mysql.connector.connect(user='root',password='',host='localhost',database='sample')    

        cursor = conn.cursor()

        sql1 = ("select *from register where roll=%s")

        Values=[a]

        cursor.execute(sql1,Values)

        # fetch all of the rows from the query

        data=cursor.fetchall()

#print the rows

        for row in data :

            a2.set(row[1])

            a3.set(row[2])

            break

        else:

            messagebox.showerror("Error", "Invalid Roll Number..")

        cursor.close()

        conn.close()

    except Exception as e1:

        print (e1)

#Clear

def clear():

    a1.set("")

    a2.set("")

    a3.set("")


#Update Data

def update():

    try:

        a=int(a1.get())

        b=a2.get()

        c=a3.get()

        conn = mysql.connector.connect(user='root',password='',host='localhost',database='sample')    

        cursor = conn.cursor()

        sql1 = ("update register set name1=%s,city=%s where roll=%s")

        Values=[b,c,a]

        cursor.execute(sql1,Values)

        cursor.close()

        conn.close()

        messagebox.showinfo("Information","Successfully Updated...!")

    except Exception as e1:

        print (e1)

        

#Delete Data

def delete():

    try:

        a=int(a1.get())

        conn = mysql.connector.connect(user='root',password='',host='localhost',database='sample')    

        cursor = conn.cursor()

        sql1 = ("delete from register where roll=%s")

        Values=[a]

        cursor.execute(sql1,Values)

        cursor.close()

        conn.close()

        messagebox.showinfo("Information","Successfully Deleted...!")

    except Exception as e1:

        print (e1)

        

a1=StringVar()   #a1=IntVar()

a2=StringVar()   #a2=IntVar()

a3=StringVar()   #a3=IntVar()


l1=Label(window, text='Roll')

l1.pack()

t1=Entry(window,textvariable=a1)

t1.focus_set()

t1.pack()


b1=Button(window,text="View",command=view,width=20)

b1.pack(pady=10)


l2=Label(window, text='Name')

l2.pack()

t2=Entry(window,textvariable=a2)

t2.pack()


l3=Label(window, text='City')

l3.pack()

t3=Entry(window,textvariable=a3)

t3.pack()


b2=Button(window,text="Update",command=update,width=20)

b2.pack()

b2.pack(pady=10)


b3=Button(window,text="Delete",command=delete,width=20)

b3.pack()

b3.pack(pady=10)


b4=Button(window,text="Clear",command=clear,width=20)

b4.pack()


window.mainloop()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


Python turtle

 -----------------------------------

Python Turtle:

----------------------------------

-Turtle graphics is a popular way for introducing programming to kids.

-The "turtle" is an imaginary pen that is given drawing commands, such as go forward and turn right. On screen, the turtle is shaped like a triangle


Turtle Methods:

-------------------

Method     Description

----------        ----------------

1) Turtle     - Creates and returns a new turtle object

2) forward     - Moves the turtle forward

3) backward  -Moves the turle backward

4) right     -Turns the turtle clockwise

5) left    -Turns the turtle counter clockwise

6) up    -Picks up the turtles tail

7) down    -Puts down the turtles tail

8) color    -Changes the color of the turtle’s tail

9) fillcolor    -Changes the color of the turtle will use to fill a polygon

10) heading  -Returns the current heading

11) position  -Returns the current position

12) goto     -Move the turtle to position x,y

13) begin_fill-Remember the starting point for a filled polygon

14) end_fill   -Close the polygon and fill with the current fill color

15) dot     -Leave a dot at the current position

16) stamp     -Leaves an impression of a turtle shape at the current location

17) shape     -Should be ‘arrow’, ‘classic’, ‘turtle’, ‘circle’ or ‘square’

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Mouse Events:

----------------

1) onclick()

2) ondrag()

3) onrelease()


Keyboard Events:

---------------------

1) onkey()

2) listen()

~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 1:  draw a arrow (Method - I)

import turtle

turtle.forward(50)

turtle.backward(50)

~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 2:  draw a arrow (Another Method - II)

import turtle

t1=turtle.Turtle()

t1.forward(50)

t1.backward(50)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 3:  draw a arrow (Another Method - III)

from turtle import Turtle

t1=Turtle()

t1.setheading(270)  #setheading(angle)

t1.forward(50)

t1.backward(150)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 4:  set turtle color

import turtle

t=turtle.Turtle()

t.screen.bgcolor("black")

t.screen.title("turtle Color")

t.color("blue")

~~~~~~~~~~~~~~~~~~~~~~~

#Program 5:  set background image

import turtle

t=turtle.Turtle()

t.hideturtle()

t.screen.bgpic("one.gif")

~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 6:  Change shape size

import turtle

turtle.shape("turtle")

turtle.shapesize(30)

~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 7:  Write text to screen

import turtle

turtle.hideturtle()

turtle.write("Cool Python Codes",move=True,align="center",font=("Freestyle Script",50,"normal"))

~~~~~~~~~~~~~~~~~~~~~

#Program 8:  drawing a circle using onclick method(Mouse)

from turtle import Turtle

t=Turtle()

t.screen.bgcolor("black")

t.color("orange")


def circle(x,y):

    t.circle(60)

 

t.onclick(circle)

~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 9:  drawing a any shape using ondrag method(Mouse)

from turtle import Turtle

t=Turtle()

t.screen.bgcolor("black")

t.color("blue")

 

def goto(x,y):

    t.goto(x,y)

 

t.ondrag(goto)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 10:  drawing a square

import turtle

turtle.forward(50)

turtle.left(90)

turtle.forward(50)

turtle.left(90)

turtle.forward(50)

turtle.left(90)

turtle.forward(50)

turtle.left(90)

~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 11:  drawing a square using loop

import turtle

for i in range(4): 

    turtle.forward(50) 

    turtle.right(90)

turtle.done()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 12:  drawing a rectangle

import turtle

turtle.forward(100)

turtle.left(90)

turtle.forward(50)

turtle.left(90)

turtle.forward(100)

turtle.left(90)

turtle.forward(50)

turtle.left(90)

~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 13:  drawing a star

import turtle

for i in range(10): 

    turtle.forward(50) 

    turtle.right(144) 

turtle.done() 

~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 14:  drawing a spiral square

import turtle   #Outside_In 

wn = turtle.Screen() 

wn.bgcolor("light green") 

wn.title("Turtle") 

skk = turtle.Turtle() 

skk.color("blue") 

  

def sqrfunc(size): 

    for i in range(4): 

        skk.fd(size) 

        skk.left(90) 

        size = size-5

  

sqrfunc(146) 

sqrfunc(126) 

sqrfunc(106) 

sqrfunc(86) 

sqrfunc(66) 

sqrfunc(46) 

sqrfunc(26) 

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 15:  drawing a spiral square

import turtle  #Inside_Out 

wn = turtle.Screen() 

wn.bgcolor("light green") 

skk = turtle.Turtle() 

skk.color("blue") 

  

def sqrfunc(size): 

    for i in range(4): 

        skk.fd(size) 

        skk.left(90) 

        size = size + 5

  

sqrfunc(6) 

sqrfunc(26) 

sqrfunc(46) 

sqrfunc(66) 

sqrfunc(86) 

sqrfunc(106) 

sqrfunc(126) 

sqrfunc(146) 

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 16:  drawing a rainbow color

import turtle 

colors = ['red', 'purple', 'blue', 'green', 'orange', 'yellow'] 

t = turtle.Pen() 

turtle.bgcolor('black') 

for x in range(50): 

    t.pencolor(colors[x%6]) 

    t.width(x/100 + 1) 

    t.forward(x) 

    t.left(59) 

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 17:  Keyboard Events(move left, right, up and down)

from turtle import Turtle

t=Turtle()

def up():

    if not(t.heading() == 90):

        t.setheading(90)

        t.fd(50)

    else:

        t.fd(50)

    

def down():

    if not(t.heading() == 270):

        t.setheading(270)

        t.fd(50)

    else:

        t.fd(50)

    

def right():

    if not (t.heading() == 0):

        t.setheading(0)

        t.fd(50)

    else:

        t.fd(50)

    

def left():

    if not (t.heading() ==180):

        t.setheading(180)

        t.fd(50)

    else:

        t.fd(50)

 

def undo_button():

    t.undo()

        

def keyboard_commands():

    t.screen.onkey(up,"Up")

    t.screen.onkey(down,"Down")

    t.screen.onkey(right,"Right")

    t.screen.onkey(left,"Left")

    t.screen.onkey(undo_button,"End")

    t.screen.listen()

 

keyboard_commands()

t.screen.mainloop()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Python - Tkinter (GUI)

 Tkinter:  (Toolkit Interface)

--------

    -Tkinter is Python’s standard GUI (Graphical User Interface) package. 

    -Tkinter Toolkit used to create GUI Applications(Desktop Applications)


Tkinter Types

----------------

1. Tk Dialogs(Messagebox dialogs,question dialogs, File dialogs)

2. Tk widgets(widgets like labels, textbox,buttons, frames, menus etc. to the window)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

1. Tkinder Dialogs

  ----------------

  - The messagebox module is used to display the message boxes in the python applications.


  A. messagebox dialogs

     ------------------

    1). showinfo()

    2). showwarning()

    3). showerror()


      Declaration In Python:

      ----------------------  

        import tkinter

        from tkinter import messagebox


  B. Question dialogs

      --------------

    1). askokcancel()

    2). askyesno()

    3). askretrycancel()

      

      Declaration In Python:

      ----------------------  

import tkinter

        from tkinter import messagebox


  C. file dialogs

     -----------

    1).askopenfilename

    2).asksaveasfilename

    3).askdirectory


      Declaration In Python:

      ----------------------  

from tkinter import *

from tkinter import filedialog

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 1: Display message box in Python

import tkinter

from tkinter import messagebox


#message box display

messagebox.showerror("Error", "Error message")

messagebox.showwarning("Warning","Warning message")

messagebox.showinfo("Information","Informative message")

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 2: Display Question Dialog in Python

import tkinter

from tkinter import messagebox


#question dialog display

messagebox.askokcancel("Title","The application will be closed")

messagebox.askyesno("Title","Do you want to save?")

messagebox.askretrycancel("Title","Installation failed, try again?")

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 3 : File dialogs

from tkinter import *

from tkinter import filedialog


filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))

filedialog.asksaveasfilename(initialdir = "/",title = "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))

filedialog.askdirectory()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

=======================================================

2. Tk Widgets

 ------------

-Tk widgets(widgets like labels, textbox,buttons, frames, menus etc. to the window)


1. Button

2. Label

3. Entry(textbox)

4. Dropdown

5. RadioButton

6. CheckButton

7. Menubar

8. Listbox

9. Scrollbar

10. Canvas

11. Frame

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 1 : create a window

from tkinter import *

window = Tk()

window.mainloop()

#window.withdraw()

~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 2 : create a window(Title,size & Location)

from tkinter import *

window = Tk()


window.title('Jahab')

window.minsize(500,300) #width,height

#window.geometry('600x400+200+50') #width,height,x,y

#window.resizable(False, False)

#window.attributes('-alpha', 0.5)  

#window.iconbitmap('1.jpg')

window.mainloop()

-------------------------

Python Tkinter Geometry:

-----------------------

-The Tkinter geometry specifies the method by using which, the widgets are represented on display. 

-The python Tkinter provides the following geometry methods.


1) pack() - widget in the block

2) grid() - widget in the tabular form

3) place() - widget to the specific x and y coordinates

-----------------------------

#program 3: Display button

from tkinter import *

window = Tk()

window.title('Button')

window.geometry('100x100')


b1=Button(window,pady=10,padx=10,text="Red",bg="red",fg="yellow",activeforeground = "white",activebackground = "black")  

b1.pack()

window.mainloop()

~~~~~~~~~~~~~~~~~~~~~~~~~~~

Note:

 padx - x axis

 pady - y axis

 fg - Foreground colour

 bg - background colour 

~~~~~~~~~~~~~~~~~~~~~~~~~

#program 4 : using button with click event

from tkinter import *

from tkinter import messagebox


def msg():

    messagebox.showinfo("Hai","Welcome")


window = Tk()

window.title('using fucntion')

window.minsize(500,300) 

b1 = Button(window, text="OK", command=msg)

b1.pack()

window.mainloop()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#program 5: Login Form - Label,Textbox & Button (using Pack)

from tkinter import *

window = Tk()

window.title('Login Form')

window.geometry('200x100')


name=Label(window,text="Name",bg='red',fg='yellow')

t1 = Entry(window)


password=Label(window,text="Password",bg='red',fg='yellow')

t2=Entry(window,show="*")


submit=Button(window,text="Submit")


name.pack()

t1.pack()

password.pack()

t2.pack()

submit.pack()

window.mainloop()  

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#program 6: Login Form - Label,Textbox & Button (using Grid)

from tkinter import *

window = Tk()

window.title('Login Form')

window.geometry('200x100')


name=Label(window,text="Name",bg='red',fg='yellow').grid(row=0,column=0,pady=10,padx=10)

t1 = Entry(window).grid(row=0,column=1,pady=10,padx=10)


password=Label(window,text="Password",bg='red',fg='yellow').grid(row=1,column=0)  

t2=Entry(window,show="*").grid(row=1,column=1)


submit=Button(window,text="Submit").grid(row=4,column=0,columnspan=2,pady=10,padx=10)  

window.mainloop()  

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#program 7: Login Form - Label,Textbox & Button (using place)

from tkinter import *

window = Tk()

window.title('Login Form')

window.geometry('250x150')


name=Label(window,text="Name",bg='red',fg='yellow').place(x=5,y=50)

t1 = Entry(window).place(x=55,y=50)


password=Label(window,text="Password",bg='red',fg='yellow').place(x=5,y=75)

t2=Entry(window,show="*").place(x=70,y=75)


submit=Button(window,text="Submit").place(x=30,y=100)

window.mainloop()  

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#program 8: Display RadioButton

from tkinter import *

window = Tk()


gender=Label(window,text="Gender",bg='red',fg='yellow').grid(row=0,column=0,pady=10,padx=10)

r1=Radiobutton(window,text="male",value=1).grid(row=0,column=1,pady=10,padx=10)

r2=Radiobutton(window,text="female",value=2).grid(row=0,column=2,pady=10,padx=10)

window.mainloop()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#program 9: display CheckButton

from tkinter import *

window = Tk()


hobbies=Label(window,text="Hobbies",bg='red',fg='yellow').grid(row=0,column=0,pady=10,padx=10)

c1=Checkbutton(window,text="sports").grid(row=0,column=1,pady=10,padx=10)

c2=Checkbutton(window,text="Music").grid(row=0,column=2,pady=10,padx=10)

c3=Checkbutton(window,text="TV").grid(row=0,column=3,pady=10,padx=10)

window.mainloop()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 10 : Display Dropdown

from tkinter import *

window = Tk()


variable = StringVar(window)

variable.set("Select City")

city=Label(window,text="city",bg='red',fg='yellow').grid(row=0,column=0,pady=10,padx=10)

d1 = OptionMenu(window,variable,"one", "two", "three").grid(row=0,column=1,pady=10,padx=10)

~~~~~~~~~~~~~~~~~~~~~~~~

#Program 11 : Display Listbox & Scrollbar

from tkinter import *

window = Tk()


scrollbar=Scrollbar(window) 

scrollbar.pack(side= RIGHT,fill = Y ) 

   

a1=Listbox(window,yscrollcommand=scrollbar.set)

for item in ["Select City","Chennai","Salem","Trichy","coimbatore","Madurai","Apple","orange","mango","Banana","tirhy"]:

  a1.insert(END,item)

a1.pack()

window.mainloop()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#program 12: using Menubar

from tkinter import *

master = Tk()


def donothing():

   x = 0


menubar=Menu(master)


filemenu = Menu(menubar, tearoff=0)

filemenu.add_command(label="New", command=donothing)

filemenu.add_command(label="Open", command=donothing)

filemenu.add_command(label="Save", command=donothing)

filemenu.add_separator()

filemenu.add_command(label="Exit", command=master.quit)

menubar.add_cascade(label="File", menu=filemenu)

 

helpmenu = Menu(menubar, tearoff=0)

helpmenu.add_command(label="Help Index", command=donothing)

helpmenu.add_command(label="About...", command=donothing)

menubar.add_cascade(label="Help", menu=helpmenu)

 

master.config(menu=menubar)

master.mainloop()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

--------------------------------------

Python Graphics using Canvas

-------------------------------------

-The Canvas widget provides structured graphics facilities for Tkinter

-It can be used to create charts, custom widgets, or create games.

-It can be used to create Lines, Colours, Shapes, Drawing Image & Drawing Text


The Canvas widget supports the following standard items:

---------------------------------------------------------------------

1) text

2) line

3) rectangle

4) oval (a circle or an ellipse)

5) arc

6) polygon

7) image

8) bitmap

9) window

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 1 : Draw a string using canvas

from tkinter import *

app=Tk()

#app Title

app.title("Display String")


#canvas

canvas = Canvas(app,width=300, height=300, bg='yellow')  

canvas.pack(expand=YES, fill=BOTH)


#Draw string(x,y,string)

canvas.create_text(100, 180, text='Jahab')

canvas.create_text(100, 150, text='Jahab',font=('arial',25),fill='blue')


#calling Main

app.mainloop()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 2 : Draw a Line using canvas

from tkinter import *

app=Tk()

#app Title

app.title("Line")


#canvas

canvas = Canvas(app,width=300, height=300, bg='yellow')  

canvas.pack(expand=YES, fill=BOTH)


#Draw Line(x1,y1,x2,y2)

canvas.create_line(10, 10, 200, 200)

canvas.create_line(20, 50, 100, 100,width=10, fill='green')

canvas.create_line(10, 10, 200, 200,dash=(8, 6))  #4px dash, 2px space


#calling Main

app.mainloop()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 3 : Draw a Rectangle using canvas

from tkinter import *

app=Tk()

#app Title

app.title("Rectangle")


#canvas

canvas = Canvas(app,width=300, height=300, bg='yellow')  

canvas.pack(expand=YES, fill=BOTH)


#Draw Rectangle(x1,y1,width,height)

canvas.create_rectangle(200, 200, 300, 300)

canvas.create_rectangle(100, 100, 200, 200, width=5, fill='red')

canvas.create_rectangle(100, 100, 200, 200, width=5, fill='red',outline='white')


#calling Main

app.mainloop()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 4 : Draw a Oval using canvas

from tkinter import *

app=Tk()

#app Title

app.title("Oval")


#canvas

canvas = Canvas(app,width=300, height=300, bg='yellow')  

canvas.pack(expand=YES, fill=BOTH)


#Draw oval(x1,y1,width,height)

canvas.create_oval(10, 10, 200, 200)

canvas.create_oval(20, 20, 200, 200, width=2, fill='blue')


#calling Main

app.mainloop()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 5 : Draw a arc using canvas

from tkinter import *

app=Tk()

#app Title

app.title("Arc")


#canvas

canvas = Canvas(app,width=300, height=300, bg='yellow')  

canvas.pack(expand=YES, fill=BOTH)


#Draw arc

points=10,10,50,50 #coordinates

canvas.create_arc(points,start=0,extent=270,fill='green')

points1=50,100,150,150 #coordinates

canvas.create_arc(points1,start=180,extent=270)


#calling Main

app.mainloop()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 6 : Draw a polygon using canvas

from tkinter import *

app=Tk()

#app Title

app.title("Polygon")


#canvas

canvas = Canvas(app,width=300, height=300, bg='yellow')  

canvas.pack(expand=YES, fill=BOTH)


#draw polygon

points = [150, 100, 200, 120, 240, 180, 210, 200, 150, 150, 100, 200]

canvas.create_polygon(points, outline='white',fill='red', width=2)


#calling Main

app.mainloop()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 7 : Display Images

from tkinter import *

app=Tk()

#app Title

app.title("Display Image")


#canvas

canvas = Canvas(app,width=300, height=300, bg='yellow')  

canvas.pack(expand=YES, fill=BOTH)


#create image

MyImage=PhotoImage(file='e:\\1.gif')

#MyImage=PhotoImage(file='e:\\1.png')

#MyImage=PhotoImage(file='e:\\2.jpg') #error

canvas.create_image(0,0,anchor=NW,image=MyImage)


#calling Main

app.mainloop()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 8 : create a bitmap(from existing)

from tkinter import *

app=Tk()

#app Title

app.title("Display Image")


#canvas

canvas = Canvas(app,width=300, height=300, bg='yellow')  

canvas.pack(expand=YES, fill=BOTH)


canvas.create_bitmap(50, 50, bitmap='questhead')

canvas.create_bitmap(50, 70, bitmap='error')

canvas.create_bitmap(50, 90, bitmap='hourglass')

canvas.create_bitmap(50, 110, bitmap='info')

canvas.create_bitmap(50, 130, bitmap='question')

canvas.create_bitmap(50, 150, bitmap='warning')


#calling Main

app.mainloop()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Tuesday, 6 August 2024

Python - Image Processing

 -----------------------------------------------

Python Image Processing using Pillow:

----------------------------------------------

PIL(Python Imaging Library):

----

-PIL is a library(Standard Procedures)

-Support file formats : PNG,JPG,JPEG,GIF,PPM,TIFF and BMP

-Operation on Images: Cropping, Resizing, Rotating, Greyscaling and adding text to images  


Installation:

--------------

Step 1: open command prompt

Step 2: type following path : C:\Users\user\AppData\Local\Programs\Python\Python36-32\Scripts

Step 3: pip install Pillow

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 1: Display Image

from PIL import Image

img1=Image.open("Desert.jpg")

img1.show()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Attributes:filename,format,mode,size,width,height

#Program 2: Display Image & Format,size, Mode

from PIL import Image

img1=Image.open("1.jpg")

img1.show()

print("Format :",img1.format)

print("size :",img1.size)

print("Mode :",img1.mode)

----------------------------

#Program 3: Changing Image Type or copy Image

from PIL import Image

img1=Image.open("1.jpg")

img1.save("new.png")

img1.thumbnail((80,80))

img1.show()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 4: Resizing Images

from PIL import Image

img1=Image.open("1.jpg")

img2=img1.resize((250,250))

print("Original Image Size : ",img1.size)

print("Resized Image Size : ",img2.size)

img2.show()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 5: Cropping Image files(portion of the image)

from PIL import Image

img1=Image.open("Desert.jpg")

img2=img1.crop((100,100,150,150))

img2.show()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 6: Rotating Images

from PIL import Image

img1=Image.open("Desert.jpg")

img1.rotate(45).show()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 7: Color Transforms

from PIL import Image

img1=Image.open("Desert.jpg")

img1.convert("L").show()

#note : L - greyscale from RGB and CMYK Images

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 8: Filter an Image

from PIL import Image

from PIL import ImageFilter

img1=Image.open("Desert.jpg")

img1.filter(ImageFilter.EMBOSS).show()


Note:

-----

BLUR,CONTOUR,EDGE_ENHANCE,EDGE_ENHANCE_MORE,EMBOSS,FIND_EDGES

SMOOTH,SMOOTH_MORE,SHARPEN

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 9: Flipping an Image

from PIL import Image

img1=Image.open("Desert.jpg")

img1.show()

img1.transpose(Image.FLIP_LEFT_RIGHT).show()

Note:

-----

FLIP_TOP_BOTTOM,ROTATE_90,ROTATE_180,ROTATE_270

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


Monday, 29 July 2024

Python - Unit V

 

Python Topics

1.      OOP’s Concepts

a.      Features & applications of oops

b.      Concept of oops

c.       Class, object & Methods

d.      Constructor & Destructor

e.       Polymorphism

f.        Inheritance

Python OOPS:

----------------------

-Python is an object oriented programming language.

-Almost everything in Python is an object,

-with its properties or attributes and methods or function

Concept of oops

---------------

1. class

2. Method

3. Object

4. Polymorphism

5. Inheritance

6. Data Abstraction

7. Data Encapsulation

 

1. class:

--------

-Class can be defined as a collection of objects.

-It is a logical entity that has some specific attributes and methods.

For example: if you have an employee class then it should contain an attribute and method i.e.an email id, name, age, salary etc.

Syntax:

----------------

 class class_name:

  sta1

  sta2

   .....

   .....

  sta-N

---------------------------

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

2. Method

-----------

 -Method is a function that is associated with an object.

 -In Python, method is not unique to class instances.

 -Any object type can have methods.

Functions

------------

-A Function is a self block of code which is used to organize the functional code.

-Function can be called as a section of a program that is written once and can be executed whenever required in the program, thus making code reusability.

-Function is a subprogram that works on data and produces some output.

Syntax:

-----------------------------

  def Function_name(args):

      sta-1

      sta-2

      ....

      ....

      sta-n

------------------------------

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~     

3. Object:

---------

-An Object is a real time entity

-An Object it has state and behaviour

-An Object contains Data's and methods

Creating an object in Python

----------------------------

Syntax:

--------------------------

 

class  Class_name:

     def  function_name(parameters):

        statement-1

        statement-2

         ....

        statement-n

object_name = Class_name()  #create object

object_name.Method_name() #invoke Method

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 1: Program for Class, object & Methods

class test:

    def msg(self):

        print("Hi Welcome")

t1=test()

t1.msg()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 2: Addition of two numbers using oops

class test:

    def get1(self):

        self.a=int(input("Enter First Value :"))

        self.b=int(input("Enter Second Value :"))

    def calc1(self):

        self.c=self.a+self.b

    def put1(self):

        print ("Addition Result :",self.c)

obj = test()

obj.get1()

obj.calc1()

obj.put1()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

 #Program 3: Addition of two numbers using oops

class test:

    def get1(self,x,y):

        print ("Inside function")

        self.x=x

        self.y=y

    def calc1(self):

        self.z=self.x+self.y

    def put1(self):

        return(self.z)

obj = test()

print ("Main Program")

a=int(input("Enter first value :"))

b=int(input("Enter Second value :"))

obj.get1(a,b)

obj.calc1()

print(obj.put1())

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

-----------------------------------------------------

Constructor & Destructor

-----------------------------------------------------

Constructor:

-----------

-A constructor is a special type of method (function)

-This Method is used to initialize (assign values) to the instance variables.

-When an object is created constructor will be automatically called.

Syntax:

------------------------------

    def _ _init_ _(self):  

        sta-1

        sta-2

        ....

        sta-n

----------------------------------------------

Destructor

----------

-A Destructor is a special type of method (function)

-This Method is used to destroy (assign values) to the instance variables.

Syntax:

-------------

       def _ _del_ _(self):

        sta-1

        sta-2

        ....

        sta-n

----------------------------------------------

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

 #Program 4: Example Program for constructor & Destructor

class test:

    def __init__(self):

        self.x=int(input("Enter First Input :"))

        self.y=int(input("Enter Second Input :"))

    def __del__(self):

        self.z=self.x-self.y

        print ("Result is ",self.z)

        print ("Delete All objects")

test()  #invoke Constructor & Destructor

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Program 5: Example Program for constructor & Destructor

class test:

    def __init__(self):  #Constructor

        self.x=int(input("Enter First Input :"))

        self.y=int(input("Enter Second Input :"))

    def calc(self):

        self.z=self.x+self.y

        print ("Result is :",self.z)

    def __del__(self):   #destructor

        print ("Delete All objects")

obj = test()

obj.calc()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Python Polymorphism

----------------------------------------------------

Polymorphism:

------------

-Polymorphism is based on the Greek Words Poly (many) and morphism (forms or shape).

-We will create a structure that can take or use many forms of objects

Ex1:      +

-integer addition

-float addition

-string concatenation

Ex2: drawing

 -line

-circle

-rectangle

Ex: button

-single click

-double click

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Ex for polymorphism

1) Function (method) Overloading

2) Operator Overloading

3) Method Overriding

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Function overloading:

--------------------------------

-same name assign to multiple method but passing different arguments

#Program 1: Program for function Overloading

def msg(x=1,y=2,z=3):

        print(x+y+z)

msg()

msg(10)

msg(10,20)

msg(10,20,30)

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

2. Python Operator Overloading:

  ------------ ---------------------------

-Python operators work for built-in classes.

-Operator assign to function name

-For example, the + operator will, perform arithmetic addition on two numbers, merge two lists and concatenate two strings.

 Operator overloading special functions in Python:

----------------------------------------------------------

1) __add__

2) __sub__

3) __mul__

4) __mod__

4) __pow__

5) __and__

6) __or__

7) __xor__

8) __invert__

9) __str__

Comparison operator overloading in Python:

------------------------------------------

1) __lt__

2) __le__

3) __eq__

4) __ne__

5) __gt__

6) __ge__

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Example program for operator overloading

class test:

    def __init__(self):  #constructor

        self.x=0

        self.y=0

    def __add__(self):

        self.x=10

        self.y=20

    def __mul__(self):

        self.x=-self.x

        self.y=-self.y

     def display(self):

        print("x :",self.x)

        print("y :",self.y)

    def __del__(self):     #destructor

        print("Destroy All Objects")  

    

obj=test()

obj.display()

obj.__add__()

obj.display()

obj.__mul__()

obj.display()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`

Method Overriding:

 ------------------------

 -Same method name assign to different class

-derived class can have override the base class method

Syntax:

  class one:

      def msg(self):

         print("base class method")

  class two(one):

      def msg(self):

         print("derived class method")

t1=two()

t1.msg()   

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

 

Python Inheritance

 

Inheritance:

----------------

-Inheritance is a feature of Object Oriented Programming.

-Deriving a new class (derived class or child class or sub class) from an old one (Super class or base class or parent class)

 

Advantages

-------------

-Derived class can have access the base class Properties and methods without re-declaration

-Reusability of code, To Reduced size of our program

-To Avoid Complexity of our program

-Easy to find (Bugging) and remove (Debugging) errors

Types of Inheritance

--------------------

1. Single Inheritance

2. Multiple Inheritance

3. Multilevel Inheritance

4. Hybrid Inheritance

5. Hierarchical Inheritance

                      



1. Single Inheritance

---------------------

-Its Consist of one base class and one derived class

-A single inheritance is when a single class inherits from a class.

Syntax:

-------

class base:

   #variable & functions

 class derived(base):

   #variable &functions

#Example 1: Program for single inheritance

class fruit:

    def __init__(self):

        print("I'm a fruit")                         

class citrus(fruit):

    def __init__(self):

        super().__init__()

        print("I'm citrus")

t1=citrus()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Example 2: Program for single inheritance

class one:

   def get1(self):

       self.a=int(input("Enter First value :"))

       self.b=int(input("Enter Second value :"))

class two(one):

    def out1(self):

        super().get1()

        self.c=self.a+self.b

        print("Result is :",self.c)

t1=two()

t1.out1()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

2. Multiple Inheritance

---------------------

-Its Consist of More than one base class and only one derived class

Syntax:

-------

class base1:

   #variable

   #functions

class base2:

   #variable

   #functions

class derived(base1,base2):

   #variable

   #functions

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Example 1: Program for Multiple Inheritance

class base1:

   def get1(self):

       self.a=int(input("Enter First value :"))

class base2:

   def get2(self):

       self.b=int(input("Enter Second value :"))

class derived(base1,base2):

    def out1(self):

        super().get1()

        super().get2()

        self.c=self.a+self.b

        print("Result is :",self.c)

t1=derived()

t1.out1()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

3. Multilevel Inheritance

---------------------

-When one class inherits from another, which in turn inherits from another,

 it is multilevel python inheritance.

Syntax:

-------

class one:

   #variable & functions

class two(one):

   #variable

   #functions

class three(two):

   #variable & functions

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Example 1: Program for Multilevel Inheritance

class one:

   def get1(self):

       self.a=int(input("Enter First value :"))

class two(one):

   def get2(self):

       super().get1()

       self.b=int(input("Enter Second value :"))

class three(two):

    def out1(self):

        super().get2()

        self.c=self.a+self.b

        print("Result is :",self.c)

t1=three()

t1.out1()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

 

4. Hierarchical Inheritance

--------------------------------

-Only one base class but more than one derived class

Syntax:

-------

class one:

   #variable & functions

class two(one):

   #variable & functions

class three(one):

   #variable & functions

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Example 1: Program for Hierarchical Inheritance

class one:

   def get1(self):

       self.a=int(input("Enter First value :"))

       self.b=int(input("Enter Second value :"))

class two(one):

   def add(self):

       super().get1()

       self.c=self.a+self.b

       print("Addition is :",self.c)

class three(one):

   def sub(self):

       super().get1()

       self.c=self.a-self.b

       print("Subtraction is :",self.c)

t1=two()

t1.add()

t2=three()

t2.sub()

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

5. Hybrid Inheritance

---------------------

-Combine Hierarchical and Multiple Inheritance

Syntax:

-------

class one:

   #variable & functions

class two(one):

   #variable & functions

class three(one):

   #variable & functions

class four(two,three):

   #variable & functions

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

#Example 1: Program for Hybrid Inheritance (Hierarchical + Multiple)

class one:

   def get1(self):

       self.a=int(input("Enter First value :"))

       self.b=int(input("Enter Second value :"))

class two(one):

   def add(self):

       super().get1()

       self.c=self.a+self.b

       print("Addition is :",self.c)

class three(one):

   def sub(self):

       super().get1()

       self.c=self.a-self.b

       print("Subtraction is :",self.c)

 

 

class four(one):

   def mul(self):

       super().get1()

       self.c=self.a*self.b

       print("Multiplication is :",self.c)

class five(one):

   def div(self):

       super().get1()

       self.c=self.a/self.b

       print("Division is :",self.c)

class six(one):

   def rem(self):

       super().get1()

       self.c=self.a%self.b

       print("Remainder is :",self.c)

class derived (two, three, four, five, six):

    def output(self):

        super().add()

        super().sub()

        super().mul()

        super().div()

        super().rem()

 

t1=derived

t1.output()

~~~~~~~~~~~~~~~~~~~~~~~~~~~