0% found this document useful (0 votes)
14 views162 pages

Introduction to Python Programming

Uploaded by

animal05132
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views162 pages

Introduction to Python Programming

Uploaded by

animal05132
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PYTHON

A GENERAL PURPOSE
PROGRAMMING LANGUAGE
What is Python?
• Python is a popular programming language.
• It was created by Guido van Rossum, and released in 1991.
• Python is a high-level programming language, with applications in numerous
areas, including web programming, scripting, scientific computing, and
artificial intelligence.
• Python is processed at runtime by the interpreter. There is no need to
compile your program before executing it.
• It is very popular and used by organizations such as Google, NASA, the CIA,
and Disney.

[Link]/[Link]
What can Python do?
• Python can be used on a server to create web applications.
• Python can be used alongside software to create workflows.
• Python can connect to database systems.
• It can also read and modify files.
• Python can be used to handle big data and perform complex mathematics.
• Python can be used for rapid prototyping, or for production-ready software
development.

[Link]/[Link]
Why Python?
• Python works on different platforms (Windows, Mac, Linux, Raspberry Pi,
etc)
• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write programs with fewer lines
than some other programming languages.
• Python runs on an interpreter system, meaning that code can be executed as
soon as it is written. This means that prototyping can be very quick.
• Python can be treated in a procedural way, an object-orientated way or a
functional way.

[Link]/[Link]
Scope of Python
• Artificial Intelligence
• Machine Learning
• Big Data
• Networking
• Information Security
• Web Development
• Desktop Application
• Games & 3D Graphics
• Scientific & Numeric

[Link]/[Link]
Python Installation
• Download Python:
• [Link]

[Link]/[Link]
Python Command Line
• To test a short amount of code in python sometimes it is quickest and
easiest not to write the code in a file.
• This is made possible because Python can be run as a command line itself.
• Type the python on the Windows, Mac or Linux command line:

[Link]/[Link]
Let’s start with Default IDLE
• IDLE is an integrated development environment for Python

[Link]/[Link]
Simple Basics Operations

[Link]/[Link]
String Operations

[Link]/[Link]
Variables
• Variables are "containers" for storing information.

Variable Name
(Glass)

Value
(Water)

[Link]/[Link]
Variables

[Link]/[Link]
String Variable Operation

-8 -7 -6 -5 -4 -3 -2 -1

S UR E NDE R
0 1 2 3 4 5 6 7

[Link]/[Link]
Lists
• List is a collection which is ordered and changeable.
• Allows duplicate members.
• Defining lists

nums = [23,34,46,67,89]

List Name Elements


fruits = ["apple", "banana", "cherry"]

[Link]/[Link]
Lists
• Accessing Elements

-5 -4 -3 -2 -1

nums = [23,34,46,67,89]
0 1 2 3 4

[Link]/[Link]
Lists
• Lists can have heterogeneous values

-3 -2 -1

values = [5.7,'Surender',23]
0 1 2

[Link]/[Link]
Lists
• Multi Dimensional Lists

names = ['Ashu','Surender','Harminder']
value = [1,2,3,4]
mix = [names,value]

[Link]/[Link]
Lists
• Lists are Mutable:
• append(value): Appending a Element
• insert(index,value): Inserting an Element
• remove(value): Removing an Element
• pop(index_number): Removing an Element using index
• pop(): Removing an Element from Last
• del nums[0:2]: Removing multiple Elements

[Link]/[Link]
Lists
• Lists are Mutable:
• [Link]([4,5,6]): Adding multiple Elements
• min(nums): Searching Min Value in a List
• max(nums) : Searching Max Value in a List
• sum(nums): Calculate Sum of a List
• [Link](): Sorting a List
• [Link](reverse=True): Sorting a List in Descending

[Link]/[Link]
Tuples
• Tuple is a collection which is ordered and unchangeable.
• Allows duplicate members.
• Defining tuple

nums = (23,34,46,67,89)

Tuple Name Elements


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

[Link]/[Link]
Tuples
• Accessing Elements

-5 -4 -3 -2 -1

nums = (23,34,46,67,89)
0 1 2 3 4

[Link]/[Link]
Tuples
• Lists can have heterogeneous values

-3 -2 -1

values = (5.7,'Surender’,23)
0 1 2

[Link]/[Link]
Tuples
• Multi Dimensional Tuple

names = ('Ashu','Surender','Harminder')
value = (1,2,3,4)
mix = (names,value)

[Link]/[Link]
Tuples
• Tuples are Immutable:

[Link]/[Link]
Sets
• Set is a collection which is unordered and unindexed.
• No duplicate members.
• Defining set

nums = {23,34,46,67,89}

Set Name Elements


fruits = {"apple", "banana", "cherry"}

[Link]/[Link]
Sets
• Sets can have heterogeneous values

values = {5.7,'Surender',23}

[Link]/[Link]
Sets
• Sets are Mutable:
• print("Surender" in values): Check if element exists in SET
• [Link]("Axpino"): Adding Element to SET
• [Link]([9,14]): Adding Multiple Element to SET
• [Link]("Surender"): Removing Element From SET
(Gives an Error when Item is not in Set)
• [Link](9): Removing Element From SET
(No Error when Item is not in Set)
• [Link](): Removing Random Element From SET
• [Link](): Clearing SET

[Link]/[Link]
Dictionary
• Dictionary is a collection which is unordered, changeable and indexed.
• No duplicate members.
• They have keys and values.
• Defining Dictionary
profile = {'name':'Surender', 'skill':'Hacking', 'id':5}

Dictionary Name Elements

[Link]/[Link]
Dictionary
• Dictionary are Mutable:
• [Link](): Accessing Keys
• [Link](): Accessing Values
• profile['id']: Accessing Specific Index
• profile['skill'] = 'Cyber Security': Change Values
• [Link]('id'): Removing Items

[Link]/[Link]
Setting Path for Windows
• Checking if path already set or not

• Copy Following Paths:


• C:\Users\username\AppData\Local\Programs\Python\Python37-32
• C:\Users\username\AppData\Local\Programs\Python\Python37-32\Scripts

[Link]/[Link]
Setting Path for Windows
• Go to your computer’s properties and then Advanced system settings

[Link]/[Link]
Setting Path for Windows
• Environment Variables > Edit Paths

[Link]/[Link]
Setting Path for Windows
• Add both the paths (Python and Python Script)
• Click OK

[Link]/[Link]
Setting Path for Windows
• Verifying Path is set

[Link]/[Link]
Variable Memory Concept
• Variable Storage num = 5
5 num

<Memory Address>

• Getting Address

>>> num = 5
>>> id(num) 5 num

1583375600 <1583375600>

[Link]/[Link]
Variable Memory Concept
• Variables with Same value has same memory Address

>>> a = 5
>>> b = 5
>>> id(a) a 5 b

1583375600 <1583375600>

>>> id(b)
1583375600

[Link]/[Link]
Variable Memory Concept
• Concept of Garbage Value
5

<1583375600>

a 10 k

<1583375680>

8 b

<1583375648>

[Link]/[Link]
Variable Memory Concept
• Memory allocation thresholds is -5 to 256
• It doesn’t also work for float value

[Link]/[Link]
Type of a Variable
• Built-in Data Types:

None

Numeric

Sequence

Dictionary

Set

[Link]/[Link]
Data Types
INT
Int
>>num=5
>>type(num) FLOAT
<class ‘Int’>
>>num=5.7
>>type(num)
<class ‘float’>
Bool Numeric Float

BOOL
>>a=5
Complex
>>b=6
>>a<b
Complex >>num = 6+9j
True
>>type(num)
<class ‘complex’>

[Link]/[Link]
Data Types
• Built-in Data Types:

INT FLOAT FLOAT INT

>>num=5 >>num=5.7
>>float(num) >>int(num)
>>num >>num
5.0 5

INT COMPLEX BOOL INT


>>a = 6 >>a=5
>>b = 7 >>b=6
>>c = complex(a,b) >>c = a<b
>>c >>int(c)
6+7j 1
[Link]/[Link]
Data Types
LIST
LISTS
>>a= [1,2,3,4]
>>type(a) RANGE
<class ‘List’>
>>a=range(0,10,2)
>>type(a)
TUPLE Sequence RANGE <class ‘Range’>

TUPLE

STRING
>>a=(1,2,3,4)
>>type(a)
<class ‘Tuple’> STRING >>str = ‘Surender’
>>type(str)
<class ‘String’>
[Link]/[Link]
Operators
Arithmetic Operators

Assignment Operators

Comparison Operators

Logical Operators

Identity Operators

Membership Operators

[Link]/[Link]
Operators
• Arithmetic Operators:
Operator Name Example
+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

% Modulus x%y

** Exponentiation x ** y

// Floor division x // y

[Link]/[Link]
Operators
• Assignment Operators:
= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

//= x //= 3 x = x // 3

**= x **= 3 x = x ** 3

&= x &= 3 x=x&3

|= x |= 3 x=x|3

[Link]/[Link]
Operators
• Comparison Operators:

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

[Link]/[Link]
Operators
• Logical Operators:

and Returns True if both statements x < 5 and x < 10


are true
or Returns True if one of the x < 5 or x < 4
statements is true
not Reverse the result, returns False if not(x < 5 and x < 10)
the result is true

[Link]/[Link]
Operators
• Identity Operators:

is Returns true if both variables are x is y


the same object
is not Returns true if both variables are x is not y
not the same object

[Link]/[Link]
Operators
• Membership Operators:

in Returns True if a sequence with x in y


the specified value is present in
the object
not in Returns True if a sequence with x not in y
the specified value is not present
in the object

[Link]/[Link]
Bitwise Operators

AND (&)

OR (|)

XOR (^)

Left Shift (<<)

Right Shift (>>)

[Link]/[Link]
Bitwise Operators
• Decimal to Binary Conversion

12 1100
2 12
2 6 0
2 3 0
1 1
[Link]/[Link]
Bitwise Operators
• Binary to Decimal Conversion

1100 12
1 1 0 0
23 + 22 + 21 + 20

[Link]/[Link]
Bitwise Operators
• Bitwise (AND)

12 & 13 = 12
00001100 -> 12
00001101 -> 13
00001100 -> 12
[Link]/[Link]
Bitwise Operators
• Bitwise (OR)

12 | 13 = 13
00001100 -> 12
00001101 -> 13
00001101 -> 13
[Link]/[Link]
Bitwise Operators
• Bitwise (XOR)

12 ^ 13 = 1
00001100 -> 12
00001101 -> 13
00000001 -> 1
[Link]/[Link]
Bitwise Operators
• Left Shift (<<)

10 << 2 = 40
00001010.000 -> 10
0000101000.0 -> 40

[Link]/[Link]
Bitwise Operators
• Right Shift (>>)

10 >> 2 = 2
00001010.000 -> 10
000010.10000 -> 2

[Link]/[Link]
Math Module
• Importing Math Module

>>>import math
• Finding Square Root >>>x = [Link](25)
>>>x
5.0

[Link]/[Link]
Math Module
• Math Functions Ceiling

5 Floor Ceil

>>x=[Link](4.9)
>>x=[Link](4.1)
>>x
>>x
4
5

Power

>>x=[Link](4,2)
4 >>x
16
Floor

[Link]/[Link]
Math Module
• Alias Math Module >>>import math as m
>>>x = [Link](25)
>>>x
5.0
• Importing Specific functions of Math Module

>>> from math import sqrt

[Link]/[Link]
Creating & Running Python Files
• Write a Program on Notepad/IDE
• Save file with .py Extension

[Link]/[Link]
Creating & Running Python Files
• Open CMD and Change path to file's location
• Call the python file

[Link]/[Link]
User Input
• Input Function
• input("Please Enter Your Input")

• x=input("Please Enter First Number")


• y=input("Please Enter Second Number")
• z=x+y
• print(z)

• Input function only accept strings

[Link]/[Link]
Passing Argument Input in CMD
• import sys
• x=[Link][1]
• y=[Link][2]
• z=x+y
• print(z)

[Link]/[Link]
Control Flow Statements
• Central Processing Unit

Control Unit

Arithmetic/Logical Unit

Memory Unit

[Link]/[Link]
Control Flow Statements
• IF Statement
Suite

x=5
if x==5:
print("equal to five")

• IF Statement Needs Indentation


x=5
if x==3:
print("equal to five")
print("hello")
[Link]/[Link]
Control Flow Statements
• Else Statement
x=3
if x==5:
print("equal to five")
else:
print("Not Equal")

• Nested IF Statement x=5


if x>=5:
print("x is greater")
if x==5:
print("x is equal")
else:
[Link]/[Link] print("x is smaller")
Control Flow Statements
• Multiple Expressions
x=5
if x==1:
print("One")
elif x==2:
print("Two")
elif x==3:
print("Three")
else:
print("Wrong Input")

[Link]/[Link]
Loops
• Python has two primitive loop commands:
• while loops
• for loops

Condition

False
True

Statement

[Link]/[Link]
Loops
• while loop

x=0 Initialization

while x<=5:
print(x)
x=x+1
Condition

Increment

[Link]/[Link]
Loops
• while loop (reverse)

x=5 Initialization

while x>=0:
print(x)
x=x-1
Condition

Decrement

[Link]/[Link]
Loops
• while loop (nested)
x=0
while x<=5:
print("Python",end="")
j=0
while j<=5:
print("Rocks",end="")
j=j+1
x=x+1
print()

[Link]/[Link]
Loops
• for loop with List
a = [“Dabur",1,"Surender"]

for i in a:
print(i)
• for loop with String

a = "Surender"

for i in a:
print(i)

[Link]/[Link]
Loops
• for loop with Tuple
a = (“Dabur",1,"Surender")

for i in a:
print(i)
• for loop with Set

a = {“Dabur",1,"Surender"}

for i in a:
print(i)

[Link]/[Link]
Loops
• for loop with Range
for i in range(10):
print(i)

for i in range(10,21,1):
print(i)

for i in range(20,0,-1):
print(i)

[Link]/[Link]
Loops
• nested for loop
for i in range(5):
for j in range(5):
print(j,end="")
print()

[Link]/[Link]
Loops
• Break Statement
for i in range(1,10,1):
if i==5:
break
print(i)
• Continue Statement

for i in range(1,10,1):
if i==5:
continue
print(i)

[Link]/[Link]
Loops
• Pass Statement
for i in range(1,100,1):
if i%2!=0:
pass
else:
print(i)

[Link]/[Link]
Loops
• for else
a=[1,2,3,4,5,6,7,10]
for i in a:
if i%5==0:
print("Found")
break
else:
print("Not Found")

[Link]/[Link]
Functions
• A function is a block of code which only runs when it is called.
• You can pass data, known as parameters, into a function.
• A function can return data as a result.
• function is defined using the def keyword:

def greet():
print("Hello")
print("Good Morning")

greet()

[Link]/[Link]
Functions
• Passing Parameter to function
Formal Arguments

def add(x,y):
c=x+y
print(c)

add(4,5)

Actual Argument

[Link]/[Link]
Functions
• Types of arguments

Position

Keyword

Default

Variable length

[Link]/[Link]
Functions
• Position Argument
def person(name,age):
print(name)
print(age)
person("Surender",26)

• Keyword Argument
def person(name,age):
print(name)
print(age)
person(age=26,name="Surender")
[Link]/[Link]
Functions
• Default Argument
def person(name="Surender",age=26):
print(name)
print(age)
person()

• Variable Length Argument


def sum(a,*b):
print(a)
print(b)
sum(2,4,6)
[Link]/[Link]
Functions
• Keyworded Variable Length Argument
def person(a,**b):
print(a)
print(b)
person("Surender",city="Faridabad", age=26)

def person(a,**b):
print(a)
for i,j in [Link]():
print(i,j)
person("Surender",city="Faridabad", age=26)
[Link]/[Link]
Functions
• Returning values from function def add(x,y):
c=x+y
return c
a=add(4,5)
print(a)
• Returning multiple values from function
def add_sub(x,y):
c=x+y
d=x-y
return c,d
a,b=add_sub(4,5)
print(a,b)
[Link]/[Link]
Functions
• Global & Local Variables a=10
def hello():
a=15
print(a)
hello()
print(a)
• Local Variables can only be used inside function
def hello():
a=15
print(a)
hello(a)
[Link]/[Link]
Functions
• Changing Value of a Global Variable

a=10
def hello():
global a
a=15
print(a)
hello()
print(a)

[Link]/[Link]
Functions
• Passing List / Tuple / Set to a function
def hello(a,b,c):
print(a)
print(b)
print(c)

a=[1,2,3,4,5]
b=(1,2,3,4,5)
c={1,2,3,4,5}

hello(a,b,c)
[Link]/[Link]
Anonymous Function (LAMBDA)
• A lambda function is a small anonymous function.
• A lambda function can take any number of arguments, but can
only have one expression.
• Syntax:
• lambda arguments : expression

f = lambda a,b:a+b
result = f(5,6)
print(result)

[Link]/[Link]
Using filter with lambda
• The filter() method filters the given sequence with the help of a
function that tests each element in the sequence to be true or
not.
• filter() method always return the true values
• Syntax:
• filter(function, sequence) nums = [2,3,45,6,7,8,80]

r= filter(lambda n:n%2==0,nums)

for i in r:
print(i)
[Link]/[Link]
Using map with lambda
• map() function returns a list of the results after applying the given
function to each item of a given iterable (list, tuple etc.)
• Syntax:
• map(function, sequence)

nums = [2,3,45,6,7,8,80]

r= map(lambda n:n*2,nums)

for i in r:
print(i)
[Link]/[Link]
Using reduce with lambda
• The reduce() function in Python takes in a function and a list as
argument.
• This performs a repetitive operation over the pairs of the list.
• This is a part of functools module.
• Syntax:
• reduce(function, sequence) from functools import reduce
nums = [2,3,45,6,7,8,80]

r = reduce(lambda a,b:a+b,nums)

print(r)
[Link]/[Link]
Creating Modules in Python
• Create a .py file and define all the functions in it.
• For e.g.
• [Link] def add(a,b):
c=a+b
return c
def sub(a,b):
c=a-b
return c
def mul(a,b):
c=a*b
return c
[Link]/[Link]
Using User Defined Modules
• Import module file
• Use functions which are defined in that file

import hello as h

r = [Link](3,4)

print(r)

[Link]/[Link]
__name__ Special Variable
• __name__ is a built-in variable which evaluates to the name of
the current module

[Link] [Link]

import module def hello():


[Link]() print("Hello")

if __name__=="__main__":
hello()
[Link]/[Link]
OOP
Object Oriented Programming
OOP class & object
• A class is a user defined blueprint or prototype from which
objects are created.
• Objects have member variables and have behavior associated
with them.
class a:
def hello(self):
print("This is hello function")

obj = a()
[Link](obj)
[Link]()
[Link]/[Link]
OOP Objects
• Multiple object of a class

class a:
def hello(self):
print("This is hello function")

obj = a()
obj2 = a()
[Link]()
[Link]()

[Link]/[Link]
Constructor
• __init__ Method
• __init__ is the constructor for a class
• The __init__() function is called automatically every time the class is being used to
create a new object.

class a:
def __init__(self):
print("This is init function")

obj = a()

[Link]/[Link]
Destructor
• Destructors are called when an object gets destroyed.
• In Python, destructors are not needed as much needed in C++
because Python has a garbage collector that handles memory
management automatically.
• __del__ is the destructor for a class
• The __del__() method is known as a destructor method in python. It is called when all
references to the object have been deleted i.e. when an object is garbage collected.

[Link]/[Link]
Constructor & Destructor
• Simple example of destructor without further reference of object

class Abc:
def __init__(self):
print(‘Constructor called.')
def __del__(self):
print('Destructor called.')

Abc()
print(“End of Program.”)

[Link]/[Link]
Constructor & Destructor
• Simple example of destructor with further reference of object

class Abc:
def __init__(self):
print(‘Constructor called.')
def __del__(self):
print('Destructor called.’)

Obj = Abc()
print(“End of program.”)

[Link]/[Link]
Constructor & Destructor
• Example of destructor with class and function
class Employee:
def __init__(self):
print('Employee created')
def __del__(self):
print("Destructor called")
def Create_obj():
print('Making Object...')
obj = Employee()
print('function end...')
return obj

print('Calling Create_obj() function...')


obj = Create_obj()
print('Program End...')
[Link]/[Link]
Arguments in Methods
• Passing Arguments to a Method

class person:
def a(self,name):
print("Hi",name)

obj = person()
obj.a("Surender")

[Link]/[Link]
OOP Variables
• Accessing Variable

class a:
x=1

obj = a()
print(obj.x)
print(a.x)

[Link]/[Link]
OOP Variables
class a:
• Binding variable to object
def b(self,k=5,n=4):
self.k=k
self.n=n
def c(self):
print(self.k,self.n)
obj = a()
obj.b(44,67)
obj.c()
obj2 = a()
obj2.b()
obj2.c()
[Link]/[Link]
OOP Variables
• Binding variable to object using __init__
class a:
def __init__(self,k=5,n=4):
self.k=k
self.n=n
def c(self):
print(self.k,self.n)
obj = a(44,67)
obj.c()
obj2 = a()
obj2.c()
[Link]/[Link]
OOP Variables
• Instance Variable
class a:
def __init__(self):
self.b=5

c1=a()
c2=a()
print(c1.b)
print(c2.b)
c1.b=10
print(c1.b)
print(c2.b)
[Link]/[Link]
OOP Variables
• Class or Static Variable class a:
x=4
def __init__(self):
self.b=5
c1=a()
c2=a()
print(c1.x)
print(c2.x)
a.x=15
print(c1.x)
print(c2.x)
c1.x=55
print(c1.x)
[Link]/[Link]
print(c2.x)
OOP Methods
• Types of Methods (Instance Methods)
class student:
def __init__(self,m1,m2,m3):
self.m1=m1
self.m2=m2
self.m3=m3
def avg(self):
return (self.m1+self.m2+self.m3)/3

s1 = student(23,56,44)
s2 = student(90,89,45)
print([Link]())
print([Link]())
[Link]/[Link]
OOP Methods
• Types of Methods (Instance Methods)

Accessors Mutators
class student:
def __init__(self):
self.a="Surender"

def get_a(self):
print(self.a)

s1 = student()
s1.get_a()
[Link]/[Link]
OOP Methods
• Types of Methods (Instance Methods)

class student:
Accessors Mutators def __init__(self):
self.a="Surender"

def set_a(self):
self.a=“SK Dabur"
return self.a
s1 = student()
print(s1.a)
s1.set_a()
print(s1.a)
[Link]/[Link]
OOP Methods
• Types of Methods (Class Methods)

class student:
university=“SKDeft"

@classmethod
def get_university(cls):
print([Link])

s1=student()
student.get_university()

[Link]/[Link]
OOP Methods
• Types of Methods (Static Methods)

class student:
@staticmethod
def a():
print("hi")

s1=student()
s1.a()

[Link]/[Link]
Nested class
• Inner Class
class student:
def a(self):
print("hi")
[Link] = self.b()
[Link]()

class b:
def hello(self):
print("hello")

s1=student()
s1.a()
[Link]/[Link]
Nested class
• Inner Class:
• (using Object of inner class outside main class)
class student:
def a(self):
print("hi")
[Link] = self.b()

class b:
def hello(self):
print("hello")
s1=student()
s1.a()
[Link]()
[Link]/[Link]
Nested class
• Inner Class:
• (Defining Object of inner class outside main class)
class student:
def a(self):
print("hi")

class b:
def hello(self):
print("hello")
s1=student()
obj=s1.b()
[Link]()

[Link]/[Link]
Inheritance
• Inheritance allows us to define a class that inherits all the
methods and properties from another class.
class a:
def feature1(self):
print("Feature 1 is working")
def feature2(self):
print("Feature 2 is working")
class b(a):
def feature3(self):
print("Feature 3 is working")
def feature4(self):
print("Feature 4 is working")

obj1 = b()
obj1.feature1()
[Link]/[Link]
Inheritance
• Multi Level Inheritance class a:
def feature1(self):
print("Feature 1 is working")
def feature2(self):
print("Feature 2 is working")
class b(a):
def feature3(self):
print("Feature 3 is working")
def feature4(self):
print("Feature 4 is working")
class c(b):
def feature5(self):
print("Feature 5 is working")
obj1 = c()
obj1.feature1()
[Link]/[Link]
Inheritance
• Multiple Inheritance class a:
def feature1(self):
print("Feature 1 is working")
def feature2(self):
print("Feature 2 is working")
class b:
def feature3(self):
print("Feature 3 is working")
def feature4(self):
print("Feature 4 is working")
class c(a,b):
def feature5(self):
print("Feature 5 is working")
obj1 = c()
obj1.feature1()
[Link]/[Link]
Inheritance
• Constructor Behavior in class a:
Single/Multi level Inheritance def __init__(self):
print("Init of a")
def feature1(self):
print("This is feature 1")
class b(a):
def __init__(self):
super().__init__()
print("Init of b")
def feature3(self):
print("This is feature 3")
k = b()

[Link]/[Link]
Inheritance
• Constructor Behavior in Multiple class a:
def __init__(self):
Inheritance Method Resolution super().__init__()
Order (MRO) print("Init of a")
def feature1(self):
print("This is feature 1")
class b:
def __init__(self):
super().__init__()
print("Init of b")
def feature3(self):
print("This is feature 3")
class c(a,b):
def __init__(self):
super().__init__()
print("Init of c")
def feat(self):
print("This is feat")
k = c()

[Link]/[Link]
Decorator
• Decorators:
• A Decorator function is a function that accepts a function as parameter and
returns a function.
• or
• A decorator takes the result of a function, modifies the result and return it.
• or
• In decorators, functions are taken as the argument into another function and
then called inside the wrapper function.
• We use @function_name to specify a decorator to be applied on another
function.

[Link]/[Link]
Decorator
• Decorators without @ def decor(fun):
def inner():
print("Before function")
fun()
print("After function")
return inner

def hello():
print("This is hello")

res = decor(hello)
res()

[Link]/[Link]
Decorator
• Decorators with @ def decor(fun):
def inner():
print("Before function")
fun()
print("After function")
return inner

@decor
def hello():
print("This is hello")

hello()

[Link]/[Link]
Decorator
• Nested Decorators without @ def decor1(fun):
def inner():
a = fun()
multi = a*5
return multi
return inner

def decor(fun):
def inner():
b = fun()
add = b+5
return add
return inner

def hello():
return 10
res = decor(decor1(hello))
print(res())
[Link]/[Link]
Decorator
def decor1(fun):
• Nested Decorators with @ def inner():
a = fun()
multi = a*5
return multi
return inner

def decor(fun):
def inner():
b = fun()
add = b+5
return add
return inner

@decor
@decor1
def hello():
return 10
print(hello())
[Link]/[Link]
Polymorphism
• It refers to the use of a single type entity (method, function,
operator or object) to represent different types in different
scenarios.

[Link]/[Link]
Polymorphism
• Types

Duck Typing

Operator Overloading

Method Overriding

[Link]/[Link]
Polymorphism
• Using methods in other classes

class b:
def k(self):
print("This is k function")
class a:
def a(self,obj2):
obj2.k()
obj2 = b()
obj = a()
obj.a(obj2)

[Link]/[Link]
Polymorphism
class Sparrow:
• Duck Typing def fly(self):
print("Sparrow flying")
class Airplane:
def fly(self):
print("Airplane flying")
class Whale:
def swim(self):
print("Whale swimming")
def lift_off(entity):
[Link]()

sparrow = Sparrow()
airplane = Airplane()
whale = Whale()

lift_off(sparrow)
lift_off(airplane)
lift_off(whale) #Error at this line
[Link]/[Link]
Polymorphism
• Operator Overloading

Operator

5+2
Operands

[Link]/[Link]
Polymorphism
• Operator Overloading
(Everything in python is a class)

a=4
b=5
c=a+b
print(c)

print(int.__add__(a,b))

[Link]/[Link]
Polymorphism
• Magic Methods
(int class has various methods)

+ •__add__()
- •__sub__()
* •__mul__()
/ •__truediv__()
[Link]/[Link]
Polymorphism
• Overloading Addition Operator
class a:
def __init__(self,m1,m2):
self.m1=m1
self.m2=m2
def __add__(obj1,obj2):
x = obj1.m1+obj2.m1
y = obj1.m2+obj2.m2
z = a(x,y)
return z
s1 = a(3,4)
s2 = a(44,55)

s3 = s1+s2
print(s3.m1)
[Link]/[Link]
Polymorphism
• Overloading Greater than Operator
class a:
def __init__(self,m1,m2):
self.m1=m1
self.m2=m2
def __gt__(obj1,obj2):
x = obj1.m1+obj1.m2
y = obj2.m1+obj2.m2
if x>y:
return True
else:
return False
s1 = a(3,4)
s2 = a(44,55)
if s1>s2:
print("s1 wins")
else:
[Link]/[Link] print("s2 wins")
Polymorphism
• Method Overriding:
• Overriding is the property of a class to change the
implementation of a method provided by one of its base classes.
class a:
def greet(self):
print("Welcome to class a")
class b(a):
def greet(self):
print("Welcome to class b")
obj = b()
[Link]()
[Link]/[Link]
Iterator
• In Python, objects can be broadly classified into one of the two
groups, iterable or non-iterable.

• If an object is capable of returning its member value one by one its


iterable; if it is not capable, it is non-iterable.

• For non-iterable objects, we have to treat the content as a single unit


only; however, an iterable object’s content is like a collection of
elements that can be individually traversed.

• Some common examples of iterable objects are lists, tuples, sets, and
dictionaries.

[Link]/[Link]
Iterator
• Iterators are implemented using two methods, iter() and next(),
that are commonly known as iterator protocol.
• The task of iter() is to initialize the method; whereas, next() is
used to perform an iteration over the iterable object.
• If all the values from an iterator have been returned, a
subsequent next() call raises a StopIteration exception when; any
further attempts to obtain values from the iterator will fail.
a = [2,33,45,67,890,3]
c = iter(a)
print(c.__next__()) # print(next(c))
for i in a:
print(c.__next__())
[Link]/[Link]
Iterator
• Create User Defined Iterators class a:
def __init__(self):
[Link] = 1
def __iter__(self):
return self
def __next__(self):
if [Link] <= 10:
val = [Link]
[Link] += 1
return val
else:
raise StopIteration
vals = a()
print(next(vals))

for i in vals:
[Link]/[Link] print(i)
Generator
• Generators are used to create iterators.
• Generators are simple functions which return an iterable.
• Any python function with a keyword "yield" may be called as
generator. def hello():
yield 1
yield 2

values=hello()

print(values.__next__())
print(values.__next__())
[Link]/[Link]
Object Oriented Programming
• Generators Example 2
def abc():
n=1
while n<=10:
yield n
n+=1
values=abc()

print(next(values))
for i in values:
print(i)
[Link]/[Link]
Object Oriented Programming
• Generators Example 3
def sq():
n=1
while n<=10:
yield n*n
n+=1
values=sq()

print(next(values))
for i in values:
print(i)
[Link]/[Link]
Exception Handling
• Types of Errors

Compile Time

Logical

Runtime Error

[Link]/[Link]
Exception Handling
• Types of Statements

a=25 Normal Statement

b=5

c=a/b Critical Statement

[Link]/[Link]
Exception Handling
• Runtime Error Example
a=25
b=0
print(a/b)

[Link]/[Link]
Exception Handling
• Runtime Error Example

a=5
b=0
try:
print(a/b)
except:
print("You cannot divide a number by zero")

print("bye")

[Link]/[Link]
Exception Handling
• try / except / finally
a=5
b=2
try:
print("Calculation mode started")
print(a/b)
except:
print("You cannot divide a number by zero")
finally:
print("Calculation mode closed")

[Link]/[Link]
Exception Handling
• Handling Specific Errors
a=5
b=0
try:
print("Calculation mode started")
print(a/b)
except ZeroDivisionError:
print("You cannot divide a number by zero")
finally:
print("Calculation mode closed")

[Link]/[Link]
Exception Handling
• Handling any Errors & get error
a=5
b=0
try:
print("Calculation mode started")
print(a/b)
except Exception as e:
print(“Note:", e)
finally:
print("Calculation mode closed")

[Link]/[Link]
Exception Handling
• try and else block
• else block only works when program executes without exception
a=5
b=0
try:
print(a/b)
except Exception as e:
print(“Note:", e)
else:
print(“Successfully Executed!")

[Link]/[Link]
Exception Handling
• raise an Exception
try:
age = int(input(“Enter age: ”))

if age<18:
raise ValueError
else:
print(“Valid age”)

except ValueError:
print(“Not Valid”)
[Link]/[Link]
Multi Threading
• Multithreading is a threading technique in Python programming
to run multiple threads concurrently by rapidly switching between
threads with a CPU help (called context switching).
• Besides, it allows sharing of its data space with the main threads
inside a process that share information and communication with
other threads easier than individual processes.
• Multithreading aims to perform multiple tasks simultaneously,
which increases performance, speed and improves the rendering
of the application.

[Link]/[Link]
Multi Threading from threading import *
from time import sleep
class hello(Thread):
def run(self):
for i in range(0,50):
print("hello")
sleep(1)
class hi(Thread):
def run(self):
for i in range(0,50):
print("hi")
sleep(1)
t1=hello()
t2=hi()

[Link]()
sleep(0.2)
[Link]()

[Link]/[Link]
Multi Threading from threading import *
from time import sleep
class hello(Thread):
• Concept of Join def run(self):
for i in range(0,10):
print("hello")
sleep(1)
class hi(Thread):
def run(self):
for i in range(0,10):
print("hi")
sleep(1)
t1=hello()
t2=hi()
[Link]()
sleep(0.2)
[Link]()
[Link]()
print("bye")
[Link]/[Link]
File Handling
• Opening a file
• Syntax: open("filename","mode")
• Modes:
• "r" - Read - Default value. Opens a file for reading, error if the file does
not exist

• "a" - Append - Opens a file for appending, creates the file if it does not
exist

• "w" - Write - Opens a file for writing, creates the file if it does not exist

• "x" - Create - Creates the specified file, returns an error if the file exists

[Link]/[Link]
File Handling
• Reading Complete file
f = open("[Link]","r")

print([Link]())
• Reading bits of a file
f = open("[Link]","r")

print([Link](6))

[Link]/[Link]
File Handling
• Reading one line at a time
f = open("[Link]","r")
print([Link]())
print([Link]())
• Reading Bits of a line
f = open("[Link]","r")
print([Link]())
print([Link](3))

[Link]/[Link]
File Handling
• Writing a file
f = open("[Link]","w")
[Link]("hi who are you??")

• Append to a file
f = open("[Link]",“a")
[Link](“This is second line")

[Link]/[Link]
File Handling
• Copy data of one file to another using for loop with file handler:

f = open("[Link]","r")

f1 = open("[Link]","a")

for i in f:
[Link](i)

[Link]/[Link]
File Handling
• Removing a file
import os
[Link]("[Link]")

• Removing a file if exists


import os
if [Link]("[Link]"):
[Link]("[Link]")
else:
print("no file")
[Link]/[Link]

You might also like