0% found this document useful (0 votes)
10 views74 pages

advance python-1

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
10 views74 pages

advance python-1

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 74

PYTHON

INTRODUCTION
What is Python:
Python is a popular programming language. It was created by Guido van Rossum, and released in 1991.
It is used for:
● web development (server-side),
● software development,
● mathematics,
● System scripting.
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.
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-oriented way or a functional way.
Good to know
● The most recent major version of Python is Python 3, which we shall be using in this tutorial. However,
Python 2, although not being updated with anything other than security updates, is still quite popular.
● In this tutorial Python will be written in a text editor. It is possible to write Python in an Integrated
Development Environment, such as Thonny, Pycharm, Netbeans or Eclipse which are particularly useful
when managing larger collections of Python files.
Python Syntax compared to other programming languages:
● Python was designed for readability, and has some similarities to the English language with influence
from mathematics.
● Python uses new lines to complete a command, as opposed to other programming languages which
often use semicolons or parentheses.
● Python relies on indentation, using whitespace, to define scope; such as the scope of loops, functions
and classes. Other programming languages often use curly-brackets for this purpose.

Where we can use Python:


We can use everywhere. The most common important application areas are
● For developing Desktop Applications
● For developing web Applications
● For developing database Applications
● For Network Programming
● For developing games
● For Data Analysis Applications
● For Machine Learning
● For developing Artificial Intelligence Applications
● For IoT
Note:
Internally Google and Youtube use Python coding.
NASA and Nework Stock Exchange Applications developed by Python.
Top Software companies like Google, Microsoft, IBM, Yahoo using Python.

IDENTIFIERS:
A Name in Python Program is called Identifier.
It can be Class Name OR Function Name OR Module Name OR Variable Name.

VARIABLES
A variable is address of the memory location.
a = 10

Variable Types
1.camel: Each word, except the first, starts with a capital letter (eg: goodMorning)
2. pascal case: Each word starts with a capital letter(eg: Goodmorning)
3.snake case: Each word is separated by an underscore character(eg: hi_good_morning)

Rules to define Identifiers in Python:


1. The only allowed characters in Python are
alphabet symbols(either lower case or upper case)
digits(0 to 9)
underscore symbol(_)

By mistake if we are using any other symbol like $ then we will get syntax error.
cash = 10 √
ca$h =20

2. Identifier should not starts with digit


123total
total123 √

3. Identifiers are case sensitive. Of course Python language is case sensitive language.
total=10
TOTAL=999
print(total) #10
print(TOTAL) #999

Identifier:
1) Alphabet Symbols (Either Upper case OR Lower case)
2) If Identifier is start with Underscore (_) then it indicates it is private.
3) Identifier should not start with Digits.
4) Identifiers are case sensitive.
5) We cannot use reserved words as identifiers
Eg: def = 10
6) There is no length limit for Python identifiers. But not recommended to use too lengthy identifiers.
7) Dollor ($) Symbol is not allowed in Python.
Note:
1) If identifier starts with _ symbol then it indicates that it is private
2) If identifier starts with __(Two Under Score Symbols) indicating that strongly private identifier.
3) If the identifier starts and ends with two underscore symbols then the identifier is language defined special
name, which is also known as magic methods.

4) Eg: __add__

Keywords

A keyword is a predefined word. It’s meaning already known to the interpreter and compiler.
Example:
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally',
'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while',
'with', 'yield']

Creating a Comment
Comments can be used to explain Python code.
Comments can be used to make the code more readable.
Comments can be used to prevent execution when testing code.
Comments starts with a #, and Python will ignore them:
Example
#This is a comment
print("Hello, World!")

Since Python will ignore string literals that are not assigned to a variable, you can add a multiline string (triple
quotes) in your code, and place your comment inside it:
Example
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
OPERATORS

Operators are used to perform operations on variables and values.

1. ARTHEMATIC OPERATOR
Arithmetic operators are used with numeric values to perform common mathematical operations:
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

EXAMPLE:

a=int(input(“enter a value”))
b=int(input(“enter a value”))
print(X+Y)

2.ASSIGNMENT OPERATOR

Assignment operators are used to assign values to variables:

Operator Example Same


As

= 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

^= x ^= 3 x=x^
3

>>= x >>= 3 x = x >>


3

<<= x <<= 3 x = x <<


3

3.COMPARISON OPERATOR

Comparison operators are used to compare two values:


Operator Name Example

== 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

4.LOGICAL OPERATOR

Logical operators are used to combine conditional statements:


Operator Description Example

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

Or Returns True if one of the statements is true x < 5 or x < 4

Not Reverse the result, returns False if the result is true not(x < 5 and x < 10

BRANCHING
Branching is used to break the sequential order of a program.
If
ELIF
ELSE
Python supports the usual logical conditions from mathematics:
● Equals: a == b
● Not Equals: a != b
● Less than: a < b
● Less than or equal to: a <= b
● Greater than: a > b
● Greater than or equal to: a >= b
These conditions can be used in several ways, most commonly in "if statements" and loops.
IF
An "if statement" is written by using the if keyword
Example
If statement:
a = 33
b = 200
if b > a:
print("b is greater than a")

In this example we use two variables, a and b, which are used as part of the if statement to test whether b is
greater than a. As a is 33, and b is 200, we know that 200 is greater than 33, and so we print to screen that "b
is greater than a".
Indentation
Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Other
programming languages often use curly-brackets for this purpose.
Example
If statement, without indentation (will raise an error):
a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error
Elif:
The elif keyword is Python's way of saying "if the previous conditions were not true, then try this condition".
Example
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
In this example a is equal to b, so the first condition is not true, but the elif condition is true, so we print to
screen that "a and b are equal".
Else
The else keyword catches anything which isn't caught by the preceding conditions.
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")

Loops
Python has two primitive loop commands:
● while loops
● for loops
while Loop
With the while loop we can execute a set of statements as long as a condition is true.
Example
i=1
while i < 6:
print(i)
i += 1
break Statement
With the break statement we can stop the loop even if the while condition is true:
Example
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
continue Statement
With the continue statement we can stop the current iteration, and continue with the next:
Example
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
else Statement
With the else statement we can run a block of code once when the condition no longer is true:

Example
i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
Python For Loops
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
This is less like the for keyword in other programming languages, and works more like an iterator method as
found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
Example
a=int(input(“enter a value”))
for I in range(1,21,1):
print(a,”*”,I,”=”,a*i)
else:
print(“complete”)
break Statement
With the break statement we can stop the loop before it has looped through all the items:
Example
for I in range(1,10):
If(i==5):
break:
else:
print(i)

continue Statement
With the continue statement we can stop the current iteration of the loop, and continue with the next:
Example
for I in range(1,10):
If(i==5):
continue:
else:
print(i)
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.

Creating a Function
In Python a function is defined using the def keyword:
Example
def my_function():
print("Hello from a function")
Calling a Function
To call a function, use the function name followed by parenthesis:

Example
def my_function():
print("Hello from a function")

my_function()

A function is a self contained block of statements.


Function is divided into 2 types
1. built-in function
2. user-define function

Built-in functions with List


ALL()
Return true if all elements is true or if the list is empty
Example
a =[1,2,3,4]
print(all(a))
ANY()
Return true if any element of the list is true.if the list is empty,return false
Example
a =[1,2,3,4,5]
print(any(a))

MAP()
Returns a list of the results after applying the given function to each item of a given iterable
Example
a =[1,2,3,4,5]
Print(list(map(lambda b:b**2,a)))

REDUCE()
Apply a particular function passed in its argument to all of the list elements stores the intermediate result and
only returns the final summation value
Example
From functools import reduce
a =[1,2,3,4,5]
Print((reduce(lambda a,b:a+b,a)))

FILTER()
Tests if each element of a list is true or not
Example
a =[1,2,3,4,5]
Print(list(filter(lambda b:b%2==0,a)))

User-define functions
User –define function is again divided into 7 types. They are:
1.A function without arguments without return type.
2.A function with arguments without return type.
3.A function without arguments with return type.
4.A function with arguments with return type.
5.Recursive function.
6.Lambda function.
7.Type casting.

Syntax:
def Abc():
Print(“hello world”)
Abc()
def abc():
Print(“HI”)
def bca():
print(“welcome”)
abc()
bca()

1. A function without arguments without return type.

def add():
a= int(input(“enter a value”))
b= int(input(“enter a value”))
c=a+b
print(“sum =”,c)
add()

2. A function with arguments and without return type.

def add(a,b):
print(“sum =”,a+b)
c=int(input(“enter a value”))
d=int(input(“enter a value”))
add(c,d)
ex: using while:
def table(x,y):
x=int(input(“enter a value”))
y=0
while(y<=20):
print(x,”*”,y,”=”,x*y)
i=i+1
table()

3. A function without arguments with return type.


def add():
a=int(input(“enter a value”))
b=int(input(“enter a value”))
print(“sum =”,a+b)
return 0
add()

4. A function with arguments with return type.

def add(a,b):
print(“sum =”,a+b)
return 0
a=int(input(“enter a value”))
b=int(input(“enter a value”))
add(a,b)

5. Recursive function
A function it’s self it’s called recursive function.
def fact(n):
if(n==0):
return 1
else:
return n*fact(n-1)
n=int(input(“enter a value”))
d=fact(n)
print(“factorial of number =”,d)

6.Lambda function:

A lambda function is a small anonymous function.


A lambda function can take any number of arguments, but can only have one expression.
x=lambda a,b:a+b
print(x(2,3))

default arguments:

def abc(x=10):
print(x)
abc()
abc(20)
abc()

keyword arguments:

def abc(a,b,c):
print(a,b,c)
abc(b=9,c=8,a=7)
variable no.of arguments
def abc(*a):
for I in a:
print(i)
add(1,2,3,4,5,6,7,8,9)
START
Starts returns an integer that is the position in the text where the match starts.
def add(start, *a):
sum=start
for i in a :
sum = sum +i
print(“total =”,sum)
add(7,7,8,9,2,4,6)
PATTERN
Patterns encode programs in different shapes and formats to create recognized patterns. These patterns are
built using different combinations of codes to allow programmers logical practice to implement the same
strategy in real-life courses and improve programming skills.
for I in range(1,6):
for j in range(1,i+1):
print(“*”,end=” ”)
print()
REVERSE OF NUMBER:
The reverse() method reverse the sorting order of the elements.
a=int(input(“enter a value”))
n=1
rev=0
while(a!=0):
r=n%10
rev=(rev * 10)+r
a=a//10
print(“reverse of number =”,rev)

PALINDROME:
Hold the letter or number in a temporary variable. Reverse the letter or number. Compare the temporary
variable with reverses letter or number. If both letters or numbers are the same, print “this string/number is a
palindrome.”
a=int(input(“enter a value”))
m=a
sum=0
while(a!=0):
r=n%10
sum=(sum*10)+r
a=a//10
print(“palindromes numbers =”, sum)
if(sum==m):
print(“palindrome”)
else:
print(“not a palindrome”)

ARMSTRONG NUMBERS:

An Armstrong number in python is a positive integer of base n, and the sum of each digit of the Armstrong
number of order n is equal to the number itself.
n=int(input(“enter a value”))
m=n
sum=0
while(n!=0):
r=n%10
sum=(r*r*r)+sum
n=n//10
if(sum==m):
print(“Armstrong”)
else:
print(“not an Armstrong”)

DATA TYPES

LIST
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set,
and Dictionary, all with different qualities and usage.
Lists are created using square brackets:
Example
a=[1,8.3,”hello”,’c’]
print(a)
List Length
To determine how many items a list has, use the len() function:
Example
a = [1,2,3,4,5]
print(len(a))
list type()
From Python's perspective, lists are defined as objects with the data type 'list':
Example
a = [1,2,3,4,5]
print(type(a))
copy the list
There are ways to make a copy, one way is to use the built-in List method copy().
Example
Make a copy of a list with the copy() method:
a = [1,2,3,4]
a.copy()
b=a
print(b)

LIST CAN DIVIDED INTO 2 TYPES


1. INDEX
2. SLICE
Index can divided into 2 types
a.Positive index
b.Negative index
Slice can divided into 2 types
a. Positive
b. Negative
Index
Positive Indexing
List items are indexed, the first item has index [0], the second item has index [1] etc.
Example
a = [1,2,3,4,5]
print(a[3])
Negative
Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.
Example
a = [1,3,5,7,9]
print(a[-2])
slice
Positive slice
List items are indexed, the first item has index [0], the second item has index [1] etc.
Example
a = [1,2,3,4,5]
print(a[3])
Negative slice
Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.
Example
a = [1,3,5,7,9]
print(a[-2])
ADD LIST ITEMS
● TO INSERT THE VALUE IN LIST VARIABLE. THEY ARE 2 TYPES
1. INSERT
2. APPEND
Insert Items
To insert a list item at a specified index, use the insert() method.
The insert() method inserts an item at the specified index:
Example
Insert an item as the second position:
a = [1,2,3,4,5]
print(a.insert(2,6))

Append Items
To add an item to the end of the list, use the append() method:
Example
Using the append() method to append an item:
a = [1,2,3,4,5]
print(a.append(8)

EXDEND
To append elements from another list to the current list, use the extend() method.
Example
a = [1,2,3,4,5]
b = [6,7,8,9,9]
a.extend(b)
print(a)
print(b)

REVERSE
What if you want to reverse the order of a list, regardless of the alphabet?
The reverse() method reverses the current sorting order of the elements.
Example
a = [1,2,3,4]
a.reverse()
a=b
print(b)
SORT
To sort descending, use the keyword argument reverse = True:
Example
a = [9,8,7,6,5,4,3,2,1]
a.sort
b=a
print(b)

Remove List Items


TO DELETE THE LIST WE CAN USE THIS ITEMS
● DEL
● POP
● CLEAR
● UPDATION
DEL
The del keyword also removes the specified index:
Example
Remove the first item:
a = ["apple", "banana", "cherry"]
del a[0]
print(a)
POP
If you do not specify the index, the pop() method removes the last item.
Example
Remove the last item:
a = [1,2,3,4,5]
a.pop()
print(a)
CLEAR
The clear() method empties the list.
The list still remains, but it has no content.
Example
Clear the list content:
a = ["apple", "banana", "cherry"]
a.clear()
print(a)
UPDATION
To update the list values
Example
a=[1,2,3,4,5]
a[1]=8
print(a)

LIST OPERATORS
+ (add the list values)
Example
a = [1,2,3,4,5]
b = [9,8,7,6,5]
c=a+b
print(c)
* (double the list value)
Example
a = [1,2,3,4]
print(a*2)
==(list values are equal)
Example
a = [1,2,3,5]
b=[9,5,4,3,2]
print(a==b)
!=( list values are not equal)
Example
a =[1,2,6,8,7]
b=[1,2,3,4,5]
print(a!=b)
Identity Operators
IS
Returns True if both variables are the same object
Example
x is y
x=[1,2,3,4]
y=[1,2,3,4]
print(x is y)
IS NOT

Returns True if both variables are not the same object


Example
x is not y
x=[1,2,3,4]
y=[1,2,3,4]
print(x is not y)
Membership Operators
IN
Returns True if a sequence with the specified value is present in the object
Example
a =[1,2,3,4,5]
print(2 in a)

NOT IN
Returns True if a sequence with the specified value is not present in the object
Example
a =[1,2,3,4,5]
print(2 not in a)

Built-in functions with List


ALL()
Return true if all elements is true or if the list is empty
Example
a =[1,2,3,4]
print(all(a))

ANY()
Return true if any element of the list is true. if the list is empty, return false
Example
a =[1,2,3,4,5]
print(any(a))

MAP()
Returns a list of the results after applying the given function to each item of a given iterable.
Example
a =[1,2,3,4,5]
Print(list(map(lambda b:b**2,a)))

REDUCE()
Apply a particular function passed in its argument to all of the list elements stores the intermediate result and
only returns the final summation value
Example
From functools import reduce
a =[1,2,3,4,5]
Print((reduce(lambda a,b:a+b,a)))
FILTER()
Tests if each element of a list is true or not
Example
a =[1,2,3,4,5]
Print(list(filter(lambda b:b%2==0,a)))

TUPLES

Tuples are used to store multiple items in a single variable.


Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set,
and Dictionary, all with different qualities and usage.
A tuple is a collection which is ordered and unchangeable.
Tuples are written with round brackets.
Tuple Items
Tuple items are ordered, unchangeable, and allow duplicate values.
Tuple items are indexed, the first item has index [0], the second item has index [1] etc.
Tuple Length
To determine how many items a tuple has, use the len() function:
Example
a=(1,2,3,4,5,6,7)
print(len(a))
type()
From Python's perspective, tuples are defined as objects with the data type 'tuple'.
Example
a=(1,2,3,4)
print(type(a))
packing – Assign a variable to tuple.
Un-packing – Assign a variables to a tuple variable.
Ex: a=(“abc”,”bca”,”cab”)
(a*b)=a
Print(a)=abc
For in b:
Print(i)
To print in tuple we should separate the values with comma(,) otherwise it will print in data types
>> insert,append , del , it will not workout in tuples
>> if we want to insert the value in tuple we have to convert into list.
Ex:
a=(1,2,3,4)
b=list(a)
print(a)
print(b)
b.insert(2,6)
print(b)
b=append(7)
a=tuple(b)
print(a)
UPDATION
a=(1,2,3,4,5)
a[0]=5
print(a)
TUPLE OPERATORS
+ (add the tuple values)
Example
a = (1,2,3,4,5)
b = (“abc”,”bca”,0.9)
c=a+b
print(c)
* (double the tuple value)
Example
a = (1,2,3,4)
print(a*2)
ASSIGNMENTAL OPERATOR
EX:
a=1
b=2
a+=b
a=a+b
a=(1,2,3)
b=(6,7,8)
a+=b
print(a)
b+=a
print(b)
Identity Operators
IS
Returns True if both variables are the same object
Example
x is y
x=(1,2,3,4)
y=(1,2,3,4)
print(x is y)
IS NOT

Returns True if both variables are not the same object


Example
x is not y
x=(1,2,3,4)
y=(1,2,3,4)
print(x is not y)
Membership Operators
IN
Returns True if a sequence with the specified value is present in the object
Example
a =(1,2,3,4,5)
print(2 in a)

NOT IN
Returns True if a sequence with the specified value is not present in the object
Example
a =(1,2,3,4,5)
print(2 not in a)
Built-in functions with Tuples
ALL()
Return true if all elements is true or if the list is empty
Example
a =(1,2,3,4)
print(all(a))
ANY()
Return true if any element of the list is true.if the list is empty,return false
Example
a =(1,2,3,4,5)
print(any(a))

MAP()
Returns a list of the results after applying the given function to each item of a given iterable
Example
a =(1,2,3,4,5)
Print(list(map(lambda b:b**2,a)))

REDUCE()
Apply a particular function passed in its argument to all of the list elements stores the intermediate result and
only returns the final summation value
Example
From functools import reduce
a =(1,2,3,4,5)
Print((reduce(lambda a,b:a+b,a)))

FILTER()
Tests if each element of a list is true or not
Example
a =(1,2,3,4,5)
Print(list(filter(lambda b:b%2==0,a)))

SETS
Sets are used to store multiple items in a single variable.
Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Tuple,
and Dictionary, all with different qualities and usage.
A set is a collection which is unordered, unchangeable*, and unindexed.
EX:
a={1,2,3,4}
a.add(6)
print(a)
Set Items
Set items are unordered, unchangeable, and do not allow duplicate values.
Unordered
Unordered means that the items in a set do not have a defined order.
Set items can appear in a different order every time you use them, and cannot be referred to by index or key.
Unchangeable
Set items are unchangeable, meaning that we cannot change the items after the set has been created.
Once a set is created, you cannot change its items, but you can remove items and add new items.
Ex: Update
a={“abc”,”bca”}
a.update(“cab”)
print(a)
Duplicates Not Allowed
Sets cannot have two items with the same value.
a={1,2,3,3,4,5,}
print(a)
Get the Length of a Set
To determine how many items a set has, use the len() function.
a={1,2,3,4,5,6,7}
print(len(a))
type()
From Python's perspective, sets are defined as objects with the data type 'set':
a={1,2,6,8,9,4}
print(type(a))
Remove set Items
TO DELETE THE SET WE CAN USE THIS ITEMS
● DEL – It will delete all the set
● POP – It will delete the last element of the set
● CLEAR - It will clear set values
● DISCARD – We can give a value is not in set it will give output without errors
● REMOVE – We can give a value is not in set it will give errors
Ex:
a={1,”abc”,9,3.9}
a.remove(9)
print(a)
a.discard(8)
print(a)
a.pop()
a.clear()
del a
Join Two Sets
There are several ways to join two or more sets in Python.
You can use the union() method that returns a new set containing all items from both sets, or
the update() method that inserts all the items from one set into another:
The union() method returns a new set with all items from both sets:
Example
a={1,2,3,4}
b={5,6,7,8}
c=a.union(b)
print(c)
The update() method inserts the items in set2 into set1:
Example
a={1,2,5}
b={9,8,7}
a.update(b)
print(a)
Keep ONLY the Duplicates
The intersection() method will return a new set, that only contains the items that are present in both sets.
Example
Update:
a={1,2,5}
b={9,8,7}
a.intersection_update(b)
print(a)
union:
a={1,2,5}
b={9,8,7}
c=a.intersection(b)
print(c)
Keep All, But NOT the Duplicates
The symmetric_difference() method will return a new set, that contains only the elements that are NOT
present in both sets.
Example
Update:
a={1,2,5}
b={9,8,7}
a.symmetric_difference.update(b)
print(a)
union:
a={1,2,5}
b={9,8,7}
c=a.symmetric_difference(b)
print(c)
DICTONARYS
Dictionaries are used to store data values in key: value pairs.
A dictionary is a collection which is ordered*, changeable and do not allow duplicates.
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.
Dictionaries are written with curly brackets, and have keys and values:
Dictionary Items
Dictionary items are ordered, changeable, and does not allow duplicates.
Dictionary items are presented in key:value pairs, and can be referred to by using the key name.
a={“name”:”abc”,”rollno”:9}
print(a.key())
print(a.values())
print(a.items())

Ordered or Unordered?
As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.
When we say that dictionaries are ordered, it means that the items have a defined order, and that order will
not change.
Unordered means that the items does not have a defined order, you cannot refer to an item by using an index.

Changeable
Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been
created.

Duplicates Not Allowed


Dictionaries cannot have two items with the same key:
Dictionary Length
To determine how many items a dictionary has, use the len() function
a={“name”:”abc”,”rollno”:9}
print(len(a))
copy the sets
There are ways to make a copy, one way is to use the built-in List method copy().
Example
Make a copy of a sets with the copy() method:
a={“name”:”abc”,”rollno”:9}
b=a.copy()
type()
From Python's perspective, dictionaries are defined as objects with the data type 'dict':
a={“name”:”abc”,”rollno”:9}
print(type(a))

Remove set Items


TO DELETE THE SET WE CAN USE THIS ITEMS
● DEL – It will delete all the set
● POP – It will delete the last element of the set
● CLEAR - It will clear set values
EX:
a={“name”:”abc”,”rollno”:9,”class”:10,”class”:12}
a.pop([“name”])
a.popitem()
a.clear()
del a[“class”]
print(a)
Nested Dictionaries
A dictionary can contain dictionaries, this is called nested dictionaries.
Example
Create three dictionaries, then create one dictionary that will contain the other three dictionaries:
a={“child 1”:{“name”:”abc”,”age”:24},
“child 2”:{“name”:”bca”,”age”:25},
“child 3”:{“name”:cab”,”age”:26}}
Print(a[“child 1”][“name”])
a[“child 1”][“name”]=”kc”
STRINGS
Strings in python are surrounded by either single quotation marks, or double quotation marks.
'hello' is the same as "hello".
You can display a string literal with the print() function:
EX:
a=”how are you”
b=a.upper()
print(b)
c=b.lower()
print(c)
Assign String to a Variable
Assigning a string to a variable is done with the variable name followed by an equal sign and the string:
a=”hello”
print(a)
String Length
To get the length of a string, use the len() function.
a=”hello world”
print(len(a))
Remove Whitespace
Whitespace is the space before and/or after the actual text, and very often you want to remove this space.
Example
The strip() method removes any whitespace from the beginning or the end:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
String Methods
Python has a set of built-in methods that you can use on strings.
Note: All string methods return new values. They do not change the original string.
Method Description

capitalize() Converts the first character to upper case

casefold() Converts string into lower case

center() Returns a centered string

count() Returns the number of times a specified value occurs in a string

encode() Returns an encoded version of the string

endswith() Returns true if the string ends with the specified value

find() Searches the string for a specified value and returns the position of where it was found

format() Formats specified values in a string

format_map() Formats specified values in a string

index() Searches the string for a specified value and returns the position of where it was found

isalnum() Returns True if all characters in the string are alphanumeric

isalpha() Returns True if all characters in the string are in the alphabet

isdecimal() Returns True if all characters in the string are decimals

isdigit() Returns True if all characters in the string are digits

isidentifier() Returns True if the string is an identifier

islower() Returns True if all characters in the string are lower case

isnumeric() Returns True if all characters in the string are numeric

isprintable() Returns True if all characters in the string are printable

isspace() Returns True if all characters in the string are whitespaces

istitle() Returns True if the string follows the rules of a title

isupper() Returns True if all characters in the string are upper case

join() Joins the elements of an iterable to the end of the string

ljust() Returns a left justified version of the string


lower() Converts a string into lower case

lstrip() Returns a left trim version of the string

maketrans() Returns a translation table to be used in translations

partition() Returns a tuple where the string is parted into three parts

replace() Returns a string where a specified value is replaced with a specified value

rfind() Searches the string for a specified value and returns the last position of where it was found

rindex() Searches the string for a specified value and returns the last position of where it was found

rjust() Returns a right justified version of the string

rpartition() Returns a tuple where the string is parted into three parts

rsplit() Splits the string at the specified separator, and returns a list

rstrip() Returns a right trim version of the string

split() Splits the string at the specified separator, and returns a list

splitlines() Splits the string at line breaks and returns a list

startswith() Returns true if the string starts with the specified value

strip() Returns a trimmed version of the string

swapcase() Swaps cases, lower case becomes upper case and vice versa

title() Converts the first character of each word to upper case

translate() Returns a translated string

upper() Converts a string into upper case

zfill() Fills the string with a specified number of 0 values at the beginning
STRING CAN DIVIDED INTO 2 TYPES
1.INDEX
2.SLICE
Index can divided into 2 types
a.Positive index
b.Negative index
Slice can divided into 2 types
c. Positive
d. Negative
Index
Positive Indexing
String items are indexed, the first item has index [0], the second item has index [1] etc.
Example
a =”hello world”
print(a[0:6])
Negative
Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.
Example
a = “hello world”
print(a[-6:-2])
slice
Positive slice
String items are indexed, the first item has index [0], the second item has index [1] etc.
Example
a = “hello world”
print(a[0:3])
Negative slice
Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.
Example
a = “hello world”
print(a[-4:-2])
Add strings & integers
a=”hello world{}”
b=9
c=a.format(b)
print(c)
String Reverse
a=”hello world”
print(a[-1: :-1])

ARRAYS
Note: This page shows you how to use LISTS as ARRAYS, however, to work with arrays in Python you will have
to import a library, like the NumPy library.
Arrays are used to store multiple values in one single variable:
Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.
What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables could look like
this:
car1 = "Ford"
car2 = "Volvo"
car3 = "BMW"
However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars,
but 300?
The solution is an array!
An array can hold many values under a single name, and you can access the values by referring to an index
number.
How to declare an Array
First import array
Syntax:
array.array(data type, list of values)
‘b’ – Signed char int
‘B’ – Unsigned char int
i – signed int
I – unsigned int
l – signed long int
L – unsigned long int
f – float
d – double
TYPE KNOWS
From array import *
a=array.typecodes(a=array(int[9,8,7])
print(a)
CREATION OF ARRAY
From array import as a
b=a.array(‘i’,[1,2,3,4])
print(b)
c=a.array(‘f’,[1,2,3,4,5])
print(c)
ARRAY INDEXING
Positive index
Import array as a
b=a.array(‘i’,[1,2,3,4])
print(a[0])
negative index
Import array as a
b=a.array(‘i’,[1,2,3,4])
print(a[-1])
ARRAY SLICING
Variable name[start:step-1:step]
Import array as a
a=a.array(‘i’,[1,2,3,4,5])
print(a[0:4])
print(a[0:len(a)])
step value: print(a[0:len(a):1])
ARRAY METHODS
INSERTION METHOD
Append()
To insert elements at the end of the array.
EX: import array as a
b=a.array(‘i’,[1,2,3,4,5])
b.append(6)
print(b)
Insert()
By using insert method element in any index.
>> If you give a out of index, it takes last position are using –ve index also.
Ex: import array as a
b=a.array(‘i’,[1,2,3,4,])
b.insert(5,10)
print(b)
Extend()
Add the elements of a list (or any iterable), to the end of the current list.
Syntax:
import array as a
array.extend(iterable)
b=a.array(‘i’,[1,2,3,4,])
c=[5,6,7,8]
b.extend(c)
From list()
Syntax:
import array as a
Array.fromlist(list)
We can add one list type only
C=[7,8,9]
b.extend(c)
print(b)

Removing Array Elements


POP()
You can use the pop() method to remove an element from the array.
a=a.array(‘i’,[1,2,3,4,5])
a.pop()
REMOVE()
You can also use the remove() method to remove an element from the array.
a=a.array(‘i’,[1,2,3,4,5])
a.remove(5)
OTHER METHODS
Reverse()
Reverses the order of the list
a=[1,2,3,4,5]
a.reverse
Count()
Returns the number of elements with the specified value
a=[1,2,3,4,5]
a.count(1)
Index()
Returns the index of the first element with the specified value
a=[1,2,3,4,5]
a.index(1)
to list()
convert the array into list
BULTIN FUNCTION
MAX()
Gives a maximum value
a=[1,2,3,4,5]
max(a)
MIN()
Give a minimum value
Min(a)
LEN()
Give length of array
Len(a)
SORTED()
Array a assigning order as convert into list
Sorted(a)
SUM()
Sum of array
Sum(a)
MODULES
Consider a module to be the same as a code library.
A file containing a set of functions you want to include in your application.
Import From Module
You can choose to import only parts from a module, by using the from keyword.

Example
The module named my module has one function and one dictionary:
def greeting(name):
print("Hello, " + name)

person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}

Example
Import only the person1 dictionary from the module:
from my module import person1

print (person1["age"])

SWAPING USING 3rd VARIABLE


a=10
b=20
print(“before swapping”)
print(a)
print(b)
c=a
a=b
b=c
print(“after swapping”)
print(a)
print(b)

OOPS
What is Class:
In Python everything is an object. To create objects we required some Model or Plan or Blue print, which is
nothing but class.
We can write a class to represent properties (attributes) and actions (behavior) of object.
Properties can be represented by variables Actions can be represented by Methods.
Hence class contains both variables and methods.
How to define a Class?
We can define a class by using class keyword.

Syntax:
class className:
''' documentation string '''
variables: instance variables, static and local variables methods: instance methods, static methods ,class
methods
Documentation string represents description of the class. Within the class doc string is always optional. We can
get doc string by using the following 2 ways.
print(classname.doc )
help(classname)
Example:
class Student:

print(Student.doc )

Within the Python class we can represent data by using variables. There are 3 types of variables are allowed.
Instance Variables (Object Level Variables)
Static Variables (Class Level Variables)
Local variables (Method Level Variables)

Within the Python class, we can represent operations by using methods. The following are various types of
allowed methods

Instance Methods
Class Methods
Static Methods
Example for Class:

1) class Student:
2) '''''Developed by durga for python demo'''
3) def init (self):
4) self.name='durga'
5) self.age=40
6) self.marks=80
7)
8) def talk(self):
9) print("Hello I am :",self.name)
10) print("My Age is:",self.age)
11) print("My Marks are:",self.marks)

What is Object:
Physical existence of a class is nothing but object. We can create any number of objects for a class.
Syntax to Create Object: reference variable = classname()
Example: s = Student()
What is Reference Variable?
The variable which can be used to refer object is called reference variable. By using reference variable, we can
access properties and methods of object.
Self-Variable:
self is the default variable which is always pointing to current object (like this keyword in Java)
By using self we can access instance variables and instance methods of object.

Note:
self should be first parameter inside constructor def init (self):
self should be first parameter inside instance methods def talk(self):
Constructor Concept:
Constructor is a special method in python.
The name of the constructor should be __init__(self).
Constructor will be executed automatically at the time of object creation.
The main purpose of constructor is to declare and initialize instance variables.
Per object constructor will be executed only once.
Constructor can take at least one argument(at least self)
Example:
class Abc:
def __init__(self,a,b):
self.name=a
self.roll=b
def disp(self):
print("name:",self.name)
print("roll:",self.roll)
t=Abc("siva",45)
t.disp()

output:
name: siva
roll: 45

Difference b/w method constructor:


Method Constructor
1) Name of method can be any 1) Constructor name should be
name always init
2) Method will be executed if we call 2) Constructor will be executed
that automatically at
method the time of object creation.
3) Per object, method can be called 3) Per object, Constructor will be
any number executed only
of times. once
4) Inside method we can write 4) Inside Constructor we have to
business logic declare and
initialize instance variables

Types of Variables:
Inside Python class 3 types of variables are allowed.

● Instance Variables (Object Level Variables)


● Static Variables (Class Level Variables)
● Local variables (Method Level Variables)

Instance Variables:
If the value of a variable is varied from object to object, then such type of variables are called instance
variables.
For every object a separate copy of instance variables will be created.
Where we can declare Instance Variables:
Inside Constructor by using self-variable
Inside Instance Method by using self-variable
Outside of the class by using object reference variable

Inside Constructor by using Self Variable:


We can declare instance variables inside a constructor by using self-keyword. Once we creates object,
automatically these variables will be added to the object.

Example:
class Abc:
def __init__(self,a,b):
self.name=a
self.roll=b
def disp(self):
print("name:",self.name)
print("roll:",self.roll)
t=Abc("siva",45)
t.disp()

output:
name: siva
roll: 45

Inside Instance Method by using Self Variable:


We can also declare instance variables inside instance method by using self variable. If any instance variable
declared inside instance method, that instance variable will be added once we call that method.

class Abc:
def __init__(self,a,b):
self.name=a
self.roll=b
def disp(self,x):
self.age=x
print("name:",self.name)
print("roll:",self.roll)
print(“age:”,self.age)
t=Abc("siva",45)
t.disp(45)

output:
name: siva
roll: 45
age:45

How to Access Instance Variables:


We can access instance variables with in the class by using self-variable and outside of the class by using object
reference.
How to delete Instance Variable from the Object:
Within a class we can delete instance variable as follows del self.variableName
From outside of class we can delete instance variables as follows del objectreference.variableName

Static Variables:
If the value of a variable is not varied from object to object, such type of variables we have to declare with in
the class directly but outside of methods. Such types of variables are called Static variables.
For total class only one copy of static variable will be created and shared by all objects of that class.
We can access static variables either by class name or by object reference. But recommended to use class
name.

How to access Static Variables:


inside constructor: by using either self or classname
inside instance method: by using either self or classname
inside class method: by using either cls variable or classname
inside static method: by using classname
From outside of class: by using either object reference or classname
Instance Variable vs. Static Variable:

Note: In the case of instance variables for every object a separate copy will be created, but in the case of
static variables for total class only one copy will be created and shared by every object of that class.

How to Delete Static Variables of a Class:


We can delete static variables from anywhere by using the following syntax del classname.variablename
But inside classmethod we can also use cls variable del cls.variablename

Local Variables:
● Sometimes to meet temporary requirements of programmer, we can declare variables inside a method
directly, such type of variables are called local variable or temporary variables.
● Local variables will be created at the time of method execution and destroyed once method completes.
● Local variables of a method cannot be accessed from outside of method.

Types of Methods:
Inside Python class 3 types of methods are allowed
● Instance Methods
● Class Methods
● Static Methods

Instance Methods:
● Inside method implementation if we are using instance variables then such type of methods are called
instance methods.
● Inside instance method declaration, we have to pass self variable. def m1(self):
● By using self variable inside method we can able to access instance variables.
● Within the class we can call instance method by using self variable and from outside of the class we can
call by using object reference.

Class Methods:
● Inside method implementation if we are using only class variables (static variables), then such type of
methods we should declare as class method.
● We can declare class method explicitly by using @classmethod decorator.
● For class method we should provide cls variable at the time of declaration
● We can call classmethod by using classname or object reference variable.

Static Methods:
In general these methods are general utility methods.
● Inside these methods we won't use any instance or class variables.
● Here we won't provide self or cls arguments at the time of declaration.
● We can declare static method explicitly by using @staticmethod decorator
● We can access static methods by using classname or object reference
Note:
In general we can use only instance and static methods. Inside static method we can access class level
variables by using class name.
Class methods are most rarely used methods in python.

Inner classes:
Sometimes we can declare a class inside another class, such type of classes are called inner classes.
Without existing one type of object if there is no chance of existing another type of object, then we should go
for inner classes.

Example: Without existing university object there is no chance of existing Department object
class University:
.....
class Department:
......
Note: Without existing outer class object there is no chance of existing inner class object. Hence inner class
object is always associated with outer class object.
Demo Program-1:
class Outer:
def m1(self):
print("hello")
class Inner:
def m2(self):
print("hii")
t=Outer()
p=t.Inner()
t.m1()
p.m2()
Output:
hello
hii

Demo Program-2:
class Outer:
def m1(self):
print("hello")
class Inner:
def m2(self):
print("hii")
Outer().m1()
Outer().Inner().m2()
Output:
hello
hii

Demo Program-3:
class Outer:
class Inner:
def m2(self):
print("hii")
def m1(self):
t=self.Inner()
print("hello")
t.m2()
p=Outer()
p.m1()
Output:
hello
hii

Inner functions:
A function which is defined inside another function is known as inner function or nested function.

Example:
class Abc:
def m1(self):
def m2():
print("hello")
m2()
t=Abc()
t.m1()
output:
hello

Inheritance
To access one class properties into another class is called inheritance.
Types of Inheritance:
Single Inheritance
Multi-Level Inheritance
Hierarchical Inheritance
Multiple Inheritance
Hybrid Inheritance
Cyclic Inheritance

Method Resolution Order (MRO)


super() Method.

Single Inheritance:
The concept of inheriting the properties from one class to another class is known as single inheritance.

Example:
class A:
def m1(self):
print("hello")
class B(A):
def m2(self):
print("hi")
t=B()
t.m1()
t.m2()

output:
hello
hii

Multi-Level Inheritance:
The concept of inheriting the properties from multiple classes to single class with the concept of one after
another is known as multilevel inheritance.

Example:
class A:
def m1(self):
print("hello")
class B(A):
def m2(self):
print("hi")
class C(B):
def m3(self):
print("Welcome")
t=C()
t.m1()
t.m2()
t.m3()

output:
hello
hii
welcome

Hierarchical Inheritance:
The concept of inheriting properties from one class into multiple classes which are present at same level is
known as Hierarchical Inheritance.
Example:
class A:
def m1(self):
print("hello")
class B(A):
def m2(self):
print("hii")
class C(A):
def m3(self):
print("welcome")
t=B()
p=C()
t.m1()
t.m2()
p.m1()
p.m3()
output:
hello
hii
hello
welcome

Multiple Inheritance:
The concept of inheriting the properties from multiple classes into a single class at a time, is known as multiple
inheritance.

Example:

class A:
def m1(self):
print("hello")
class B:
def m2(self):
print("hii")
class C(A,b):
def m3(self):
print("welcome")
t=C()
t.m1()
t.m2()
t.m3()
output:
hello
hii
welcome

Hybrid Inheritance:
Combination of Single, Multi-level, multiple and Hierarchical inheritance is known as Hybrid Inheritance.
Cyclic Inheritance:
The concept of inheriting properties from one class to another class in cyclic way, is called Cyclic inheritance.
Python won't support for Cyclic Inheritance of course it is really not required.
Example:
class A(B):
def m1(self):
print("hii")
class B(A):
def m(self):
print("hii")

t=B()
t.m()
t.m1()

Output: NameError: name 'B' is not defined

Method Resolution Order (MRO):


In Hybrid Inheritance the method resolution order is decided based on MRO algorithm.
This algorithm is also known as C3 algorithm.
Samuele Pedroni proposed this algorithm.
It follows DLR (Depth First Left to Right) i.e Child will get more priority than Parent.
Left Parent will get more priority than Right Parent.
MRO(X) = X+Merge(MRO(P1),MRO(P2),...,ParentList)
Head Element vs Tail Terminology:
Assume C1,C2,C3,...are classes.
In the list: C1C2C3C4C5....
C1 is considered as Head Element and remaining is considered as Tail.

How to find Merge:


Take the head of first list
If the head is not in the tail part of any other list, then add this head to the result and remove it from the lists
in the merge.
If the head is present in the tail part of any other list, then consider the head element of the next list and
continue the same process.
Note: We can find MRO of any class by using mro() function. print(ClassName.mro())

Demo Program- for Method Resolution Order:

Object

A B C
X Y

mro(A)=A,object mro(B)=B,object mro(C)=C,object mro(X)=X,A,B,object mro(Y)=Y,B,C,object


mro(P)=P,X,A,Y,B,C,object
Finding mro(P) by using C3 Algorithm:
Formula: MRO(X) = X+Merge(MRO(P1),MRO(P2),...,ParentList) mro(p) = P+Merge(mro(X),mro(Y),mro(C),XYC)
= P+Merge(XABO,YBCO,CO,XYC)
= P+X+Merge(ABO,YBCO,CO,YC)
= P+X+A+Merge(BO,YBCO,CO,YC)
= P+X+A+Y+Merge(BO,BCO,CO,C)
= P+X+A+Y+B+Merge(O,CO,CO,C)
= P+X+A+Y+B+C+Merge(O,O,O)
= P+X+A+Y+B+C+O
Example:
class A:
def m1(self):
print("A")
class B:
def m1(self):
print("B")
class C:
def m1(self):
print("c")
class D(A,B):
def m1(self):
print("D")
class E(B,C):
def m1(self):
print("E")
class F(D,E,C):
def m1(self):
print("F")
t=F()
t.m1()

Output: F

In the above example P class m1() method will be considered. If P class does not contain m1() method then as
per MRO, X class method will be considered. If X class does not contain then A class method will be considered
and this process will be continued.
The method resolution in the following order: PXAYBCO

super() Method:
super() is a built-in method which is useful to call the super class constructors, variables and methods from the
child class.
Example:
class A:
def __init__(self):
self.a=10
self.b=30
def m1(self):
print(self.a+self.b)
def m2(self):
self.m1()
class B(A):
def m3(self):
super().m2()
t=B()
t.m3()
output:
40

POLYMORPHISM
poly means many. Morphs mean forms Polymorphism means 'Many Forms'.

Eg1: Yourself is best example of polymorphism. In front of Your parents You will have one type of behavior and
with friends another type of behavior. Same person but different behavior’s at different places, which is
nothing but polymorphism.

Eg2: + operator acts as concatenation and arithmetic addition.


Eg3: * operator acts as multiplication and repetition operator.
Eg4: The Same method with different implementations in Parent class and child classes.(overriding)

Related to Polymorphism the following 4 topics are important


● Duck Typing Philosophy of Python
● Overloading
● Operator Overloading
● Method Overloading
● Constructor Overloading
● Overriding
● Method Overriding
● Constructor Overriding

Overloading
We can use same operator or methods for different purposes.
Eg 1: + operator can be used for Arithmetic addition and String concatenation print(10+20)#30
print(‘siva’+'soft')#siva
There are 3 types of Overloading
● Operator Overloading
● Method Overloading
● Constructor Overloading

Operator Overloading:
We can use the same operator for multiple purposes, which is nothing but operator overloading.
Python supports operator overloading.
E.g. 1: + operator can be used for Arithmetic addition and String concatenation print (10+20)#30
print(‘siva’+'soft')#sivasoft

Demo program to use + operator for our class objects:


class Abc:
def __init__(self,a):
self.pages=a
b1=Abc(100)
b2=Abc(200)
print(b1+b2)
TypeError: unsupported operand type(s) for +: 'Abc' and 'Abc'

We can overload + operator to work with Book objects also. i.e Python supports Operator Overloading.
For every operator Magic Methods are available. To overload any operator we have to override that Method in
our class.
Internally + operator is implemented by using add () method.This method is called magic method for +
operator. We have to override this method in our class.

Demo Program to Overload + Operator for Our Book Class Objects:

class A:
def __init__(self,a):
self.page=a
def __add__(self,other):
return self.page+other.page
t=A(200)
t1=A(300)
t3=t+t1
print("No of pages:",t3)
output: No of pages: 500
Exmple:
class A:
def __init__(self,a):
self.page=a
def __gt__(self,other):
return self.page>other.page
t=A(200)
t1=A(300)
t3=t>t1
print(t3)
output: False

Method Overloading:
If 2 methods having same name but different type of arguments then those methods are said to be overloaded
methods.
Eg: m1(int a) m1(double d)
But in Python Method overloading is not possible.
If we are trying to declare multiple methods with same name and different number of arguments then Python
will always consider only last method.

Demo Program:
class A:
def m1(self):
print('hello')
def m1(self,a):
print("hii")
def m1(self,a,b):
print("welcome")
t=A()
t.m1()
t.m1(1)
t.m1(1,2)

output:
TypeError: A.m1() missing 2 required positional arguments: 'a' and 'b'
In the above program python will consider only last method.

How we can handle Overloaded Method Requirements in Python:


Most of the times, if method with variable number of arguments required then we can handle with default
arguments or with variable number of argument methods
Demo Program with Default Arguments:
class A:
def m1(self,a=None,b=None,c=None):
if(a!=None and b!=None and c!=None):
print("hello")
elif(a!=None and b!=None):
print("hii")
elif(a!=None):
print("Welcome")
else:
print("good")
t=A()
t.m1(1,2,3)
t.m1(5,6)
t.m1(1)
t.m1()
Output
hello
hii
Welcome
good
Demo Program with Variable Number of Arguments:
class A:
def sum(self,*a):
sum=0
for i in a:
sum=sum+i
print(sum)
t=A()
t.sum(1)
t.sum(3,4)
t.sum(3,4,5)
output:
1
7
12

Constructor Overloading:
Constructor overloading is not possible in Python.
If we define multiple constructors then the last constructor will be considered.

EXAMPLE:
class A:
def __init__(self):
print("hii")
def __init__(self,a):
print("hello")
def __init__(self,a,b):
print("Welcome")
t=A()
t=A(1)
t=A(1,2)
Output: TypeError: A.__init__() missing 2 required positional arguments: 'a' and 'b'.

In the above program only Two-Arg Constructor is available.


But based on our requirement we can declare constructor with default arguments and variable number of
arguments.

Example:
class Abc:
def __init__(self,*a):
sum=0
for i in a:
sum=sum+i
print(sum)
t=Abc(1)
t=Abc(1,2)
t=Abc(5,6,7)
output:
1
3
18

Overriding
Method Overriding
Whatever members available in the parent class are by default available to the child class through inheritance.
If the child class not satisfied with parent class implementation then child class is allowed to redefine that
method in the child class based on its requirement. This concept is called overriding.
Overriding concept applicable for both methods and constructors.

Example:
class A:
def m1(self):
print("Hello")
class B(A):
def m1(self):
print("hii")
t=B()
t.m1()
Output :hiii

Constructor overriding:
From Overriding method of child class, we can call parent class method also by using super() method.
In the above example, if child class does not contain constructor then parent class constructor will be executed
From child class constructor we can call parent class constructor by using super() method.

Example:
class A:
def __init__(self,a,b):
self.name=a
self.roll=b
class B(A):
def __init__(self,a,b,c):
self.age=c
super().__init__(a,b)
def m1(self):
print("name:",self.name)
print("Age:",self.age)
print("roll:",self.roll)
t=B("ravi",101,23)
t.m1()

output:
name: ravi
Age: 23
roll: 101
modules:
Consider a module to be the same as a code library.
A file containing a set of functions you want to include in your application.
To create a module just save the code you want in a file with the file extension .py:
Save this code in a file named mymodule.py

def greeting(name):
print("Hello, " + name)

Now we can use the module we just created, by using the import statement:

import mymodule
mymodule.greeting("Jonathan")

When using a function from a module, use the syntax: module_name.function_name.

Abstract Method:
Sometimes we don't know about implementation, still we can declare a method. Such types of methods are
called abstract methods.i.e abstract method has only declaration but not implementation.
In python we can declare abstract method by using @abstractmethod decorator as follows.
@abstractmethod
def m1(self): pass
@abstractmethod decorator present in abc module. Hence compulsory we should import abc
module,otherwise we will get error.
abc  abstract base class module
class A:
@abstractmethod
def m1(self):
pass
t=A()
t.m1()

NameError: name 'abstractmethod' is not defined

Example:
from abc import *
class A:
@abstractmethod
def m1(self):
pass
class B(A):
def m1(self):
print("hello")
t=B()
t.m1()
output:
hello

Child classes are responsible to provide implemention for parent class abstract methods.

Abstract class:
Sometimes implementation of a class is not complete, such type of partially implementation classes are called
abstract classes. Every abstract class in Python should be derived from ABC class which is present in abc
module.

Example:
From abc import *
Class A:
Pass
t=A()
In the above code we can create object for Abc class b'z it is concrete class and it does not contain any abstract
method.
Example:
From abc import *
Class A(ABC):
Pass
t=A()
In the above code we can create object, even it is derived from ABC class,b'z it does not contain any abstract
method.

Example:
From abc import *
Class A(ABC):
@abstarctmethod
def m1(self):
pass
t=A()
TypeError: Can't instantiate abstract class Abc with abstract methods m1

Example:
From abc import *
Class A:
@abstarctmethod
def m1(self):
print(“hello”)
t=A()
t.m1()
Output: Hello
Conclusion: If a class contains at least one abstract method and if we are extending ABC class then
instantiation is not possible.

"abstract class with abstract method instantiation is not possible"


Parent class abstract methods should be implemented in the child classes. Otherwise we cannot instantiate
child class. If we are not creating child class object then we won't get any error.
Interfaces In Python:
In general if an abstract class contains only abstract methods such type of abstract class is considered as
interface.
Example:
from abc import *
class A(ABC):
@abstractmethod
def m1(self):
pass
@abstractmethod
def m2(self):
pass
@abstractmethod
def m3(self):
pass

Note: The inbuilt function globals()[str] converts the string 'str' into a class name and returns the classname.

Concrete class vs. Abstract Class vs. Interface:


If we don’t know anything about implementation just we have requirement specification then we should go
for interface.
If we are talking about implementation but not completely then we should go for abstract class. (partially
implemented class).
If we are talking about implementation completely and ready to provide service then we should go for
concrete class.
Example:
from abc import *
class A(ABC):
@abstractmethod
def m1(self):
pass
@abstractmethod
def m2(self):
pass
@abstractmethod
def m3(self):
pass
class B(A):
def m1(self):
print("hello")
def m2(self):
print("hii")
def m3(self):
pass
class C(B):
def m3(self):
print("Welcome")
t=C()
t.m1()
t.m2()
t.m3()
output:
hello
hii
Welcome

Public, Protected and Private Attributes:


By default every attribute is public. We can access from anywhere either within the class or from outside of
the class.
Eg: name = ‘siva’
Protected attributes can be accessed within the class anywhere but from outside of the class only in child
classes. We can specify an attribute as protected by prefexing with _ symbol.
Syntax: _variablename = value
Eg: _name=‘siva’
But is is just convention and in reality does not exists protected attributes.
private attributes can be accessed only within the class.i.e from outside of the class we cannot access. We can
declare a variable as private explicitly by prefexing with 2 underscore symbols.

syntax: variablename=value

How to Access Private Variables from Outside of the Class:


We cannot access private variables directly from outside of the class.
But we can access indirectly as follows
objectreference._classname variablename

Example:
class A:
__a=20
__b=40
def __m(self):
print(A.__a+A.__b)
t=A()
t._A__m()
print(t._A__a)
output:
60
20

In any programming language there are 2 types of errors are possible.


Syntax Errors
Runtime Errors
Syntax Errors:
The errors which occur because of invalid syntax are called syntax errors.
Eg 1:
x = 10
if x == 10 print("Hello")
SyntaxError: invalid syntax

Eg 2:
print "Hello"
SyntaxError: Missing parentheses in call to 'print'

Note: Programmer is responsible to correct these syntax errors. Once all syntax errors are corrected then only
program execution will be started.
Runtime Errors:
Also known as exceptions.
While executing the program if something goes wrong because of end user input or programming logic or
memory problems etc then we will get Runtime Errors.
Eg:
print(10/0)  ZeroDivisionError: division by zero
print(10/"ten")  TypeError: unsupported operand
type(s) for /: 'int' and 'str'
x = int(input("Enter Number:")) print(x)

D:\Python_classes>py Abc.py Enter Number:ten


ValueError: invalid literal for int() with base 10: 'ten'

Note: Exception Handling concept applicable for


Runtime Errors but not for syntax errors
What is Exception?
An unwanted and unexpected event that disturbs normal flow of program is called exception.
Eg:
ZeroDivisionError
TypeError
ValueError
FileNotFoundError
EOFError
SleepingError
TyrePuncturedError
It is highly recommended to handle exceptions. The main objective of exception handling is Graceful
Termination of the program (i.e we should not block our resources and we should not miss anything)

Exception handling does not mean repairing exception. We have to define alternative way to continue rest of
the program normally.

Eg: For example our programming requirement is reading data from remote file locating at London. At
runtime if London file is not available then the program should not be terminated abnormally. We have to
provide local file to continue rest of the program normally. This way of defining alternative is nothing but
exception handling.
try:
Read Data from Remote File locating at London. except FileNotFoundError:
use local file and continue rest of the program normally

Q. What is an Exception?
Q. What is the purpose of Exception Handling?
Q. What is the meaning of Exception Handling?
Default Exception Handing in Python:
Every exception in Python is an object. For every exception type the corresponding classes are available.
Whevever an exception occurs PVM will create the corresponding exception object and will check for handling
code. If handling code is not available then Python interpreter terminates the program abnormally and prints
corresponding exception information to the console.
The rest of the program won't be executed.

Example:
print("hello")
print(10/0)
print("hii")
output:
hello
Traceback (most recent call last):
File "C:\Users\MSS40\AppData\Local\Programs\Python\Python312\gfu.py", line 2, in <module>
print(10/0)
ZeroDivisionError: division by zero

Every Exception in Python is a class.


All exception classes are child classes of BaseException.i.e every exception class extends BaseException either
directly or indirectly. Hence BaseException acts as root for Python Exception Hierarchy.
Most of the times being a programmer we have to concentrate Exception and its child classes

Customized Exception Handling by using try-except:


It is highly recommended to handle exceptions.
The code which may raise exception is called risky code and we have to take risky code inside try block. The
corresponding handling code we have to take inside except block.
try:
Risky Code except XXX:
Handling code/Alternative Code

Example:
print("hello")
try:
print(10/0)
except:
print(10/2)
print("hii")
output:
hello
5.0
Hii
Conclusions:
Within the try block if anywhere exception raised then rest of the try block won’t be executed eventhough we
handled that exception. Hence we have to take only risky code inside try block and length of the try block
should be as less as possible.
In addition to try block, there may be a chance of raising exceptions inside except and finally blocks also.
If any statement which is not part of try block raises an exception then it is always abnormal termination.
How to Print Exception Information:
try:
1) print(10/0)
3) print("exception raised and its description is:",msg)
2) except
Output exception ZeroDivisionError
raised as msg:
and its description is: division by zero
try with Multiple except Blocks:
The way of handling exception is varied from exception to exception.Hence for every exception type a
seperate except block we have to provide. i.e try with multiple except blocks is possible and recommended to
use.

Eg:
try:
-------
-------
-------
except ZeroDivisionError:
perform alternative arithmetic operations
except FileNotFoundError:
use local file instead of remote file

If try with multiple except blocks available then based on raised exception the corresponding except block will
be executed.

Example:
1) try:
2) x=int(input("Enter First Number: "))
3) y=int(input("Enter Second Number: "))
4) print(x/y)
5) except ZeroDivisionError :
6) print("Can't Divide with Zero")
7) except ValueError:
8) print("please provide int value only")

finally Block:
☕ It is not recommended to maintain clean up code(Resource Deallocating Code or Resource Releasing code)
inside try block because there is no guarentee for the execution of every statement inside try block always.
☕ It is not recommended to maintain clean up code inside except block, because if there is no exception then
except block won't be executed.
☕ Hence we required some place to maintain clean up code which should be executed always irrespective of
whether exception raised or not raised and whether exception handled or not handled. Such type of best place
is nothing but finally block.
☕ Hence the main purpose of finally block is to maintain clean up code.
try:
Risky Code
except:
Handling Code
finally:
Cleanup code

The speciality of finally block is it will be executed always whether exception raised or not raised and whether
exception handled or not handled.
Case-1: If there is no exception
1) try:
2) print("try")
3) except:
4) print("except")
5) finally:
6) print("finally")

Output:

Case-2: If there is an exception raised but handled


1) try:

3) 2)
print(10/0)print("try")

5) 4) except ZeroDivisionError:
print("except")
7) print("finally")
6) finally:
Output:
Note: There is only one situation where finally block won't be executed ie whenever we are using os._exit(0)
function.
Various possible Combinations of try-except-else-finally:
Whenever we are writing try block, compulsory we should write except or finally block.i.e without except or
finally block we cannot write try block.
Wheneever we are writing except block, compulsory we should write try block. i.e except without try is always
invalid.
Whenever we are writing finally block, compulsory we should write try block. i.e finally without try is always
invalid.
We can write multiple except blocks for the same try,but we cannot write multiple finally blocks for the same
try
Whenever we are writing else block compulsory except block should be there. i.e without except we cannot
write else block.
In try-except-else-finally order is important.
We can define try-except-else-finally inside try, except, else and finally blocks. i.e nesting of try-except-else-
finally is always possible.
1 try:
print("try")
2 except:
print("Hello")
3 else:
print("Hello")
4 finally:
print("Hello")
try:
5 print("try") except: √
print("except")

try:
6 print("try") √
finally:
print("finally")
try:
print("try") except:
7 print("except")
else:

print("else")

try:
8 print("try")
else:
print("else")
try:
print("try")
9 else:
print("else")
finally:
print("finally")
try:
print("try") except XXX:
10 print("except-1")
except YYY:

print("except-2")

try:
11 print("try")
except :
print("except-1")
else:
print("else")
else:
print("else")
try:
print("try") except :
print("except-1")
12 finally:
print("finally")
finally:
print("finally")

try:
print("try") print("Hello") except:
13 print("except")

try:
print("try") except:
print("except") print("Hello")
14 except:
print("except")

try:
print("try") except:
print("except") print("Hello")
15 finally:
print("finally")

try:
print("try") except:
print("except") print("Hello")
16 else:
print("else")

try:
print("try") except:
17 print("except")
try:

print("try")
except:
print("except")
try:
print("try") except:

18
print("except")
try:

print("try")
finally:
print("finally")

try:
print("try") except:

19
print("except") if 10>20:
print("if")

else:
print("else")

try:
print("try") try:
print("inner try") except:
print("inner except block") finally:
20 print("inner finally block")
except:

print("except")

try:
print("try")
except:
print("except") try:

21
print("inner try") except:
print("inner except block") finally:

print("inner finally block")

try:
print("try") except: √
22 print("except")
finally:
try:
print("inner try") except:
print("inner except block") finally:
print("inner finally block")

try:
print("try") except:
print("except")
23 try:
print("try")
else:
print("else")

try:
print("try") try:
24 print("inner try")
except:
print("except")

try:
print("try")
else:
25 print("else") except:
print("except")
finally:
print("finally")

Types of Exceptions:
In Python there are 2 types of exceptions are possible.
Predefined Exceptions
User Definded Exceptions
Predefined Exceptions:
Also known as inbuilt exceptions.
The exceptions which are raised automatically by Python virtual machine whenver a particular event occurs
are called pre defined exceptions.

Eg 1: Whenever we are trying to perform Division by zero, automatically Python will raise ZeroDivisionError.
print(10/0)

User Defined Exceptions:


Also known as Customized Exceptions or Programatic Exceptions
Some time we have to define and raise exceptions explicitly to indicate that something goes wrong, such type
of exceptions are called User Defined Exceptions or Customized Exceptions
Programmer is responsible to define these exceptions and Python not having any idea about these. Hence we
have to raise explicitly based on our requirement by using "raise" keyword.
Eg:
InSufficientFundsException
InvalidInputException
TooYoungException
TooOldException
How to Define and Raise Customized Exceptions:
Every exception in Python is a class that extends Exception class either directly or indirectly.

Program:===================================

Multi-Tasking:
Executing several tasks simultaneously is the concept of multitasking.

There are 2 types of Multi-Tasking


Process based Multi-Tasking
Thread based Multi-Tasking
Process based Multi Tasking:
Executing several tasks simultaneously where each task is a seperate independent process is called process
based multi-tasking.
Eg: while typing python program in the editor we can listen mp3 audio songs from the same system. At the
same time we can download a file from the internet. All these task are executing simultaneously and
independent of each other. Hence it is process based multi-tasking.

This type of multi-tasking is best suitable at operating system level.


Thread based Multitasking:
Executing several tasks simultaneously where each task is a separate independent part of the same program, is
called Thread based multi-tasking, and each independent part is called a Thread.
This type of multi-tasking is best suitable at programmatic level.

Note: Whether it is process based or thread based, the main advantage of multi-tasking is to improve
performance of the system by reducing response time.

The main important application areas of multi-threading are:


To implement Multimedia graphics
To develop animations
To develop video games
To develop web and application servers etc...
Note: Where ever a group of independent jobs are available, then it is highly recommended to execute
simultaneously instead of executing one by one. For such type of cases we should go for Multi-Threading.
Python provides one inbuilt module "threading" to provide support for developing threads. Hence developing
multi-threaded Programs is very easy in python.
Every Python Program by default contains one thread which is nothing but Main Thread.
Q) Program to print Name of Current executing Thread

1) import threading
2) print("Current Executing Thread:",threading.current_thread().getName())
Output: Current Executing Thread: MainThread
Note: threading module contains function current_thread() which returns the current executing Thread
object. On this object if we call getName() method then we will get current executing thread name.

The ways of Creating Thread in Python:


We can create a thread in Python by using 3 ways
● Creating a Thread without using any class
● Creating a Thread by extending Thread class
● Creating a Thread without extending Thread class
Creating a Thread without using any Class:
:Example:
from threading import *
def m():
for i in range(1,10):
print("hii")
t=Thread(target=m)
t.start()
for i in range(1,10):
print("hello")

If multiple threads present in our program, then we cannot expect execution order and hence we cannot
expect exact output for the multi-threaded programs. B'z of this we cannot provide exact output for the
above program. It is varied from machine to machine and run to run.

Note: Thread is a pre-defined class present in threading module which can be used to create our own
Threads.
Creating a Thread by extending Thread Class
We have to create child class for Thread class. In that child class we have to override run() method with our
required job. Whenever we call start() method then automatically run() method will be executed and
performs our job.
Example:
from threading import *
class A(Thread):
def run(self):
for i in range(1,10):
print("hii")
t=A()
t.start()
for i in range(1,10):
print("hello")
Creating a Thread without extending Thread Class:
Example:
from threading import *
class A:
def m(self):
for i in range(1,10):
print("hii")

t=A()
p=Thread(target=t.m)
p.start()
for i in range(1,10):
print("hello")

Setting and Getting Name of a Thread:


Every thread in python has name. It may be default name generated by Python or Customized Name
provided by programmer.

We can get and set name of thread by using the following Thread class methods. t.getName() Returns
Name of Thread
t.setName(newName)  To set our own name
Note: Every Thread has implicit variable "name" to represent name of Thread.

Example:
from threading import *
class A(Thread):
def run(self):
for i in range(1,10):
print("hii")
t=A()
t.start()
for i in range(1,10):
print("hello")
current_thread().setName("pawan kalyan")
t.setName("prabash")
print(current_thread().getName())
print(t.getName())

Thread Identification Number (ident):


For every thread internally a unique identification number is available. We can access this id by using
implicit variable "ident"

from threading import *


class A(Thread):
def run(self):
for i in range(1,10):
print("hii")
t=A()
t.start()
for i in range(1,10):
print("hello")

print(current_thread().ident)
print(t.ident)

join() Method:
If a thread wants to wait until completing some other thread then we should go for join() method.
from threading import *
import time
class A(Thread):
def run(self):
for i in range(1,10):
print("rama")
time.sleep(2)
t=A()
t.start()
t.join()
for i in range(1,10):
print("seeta")
Note: We can call join() method with time period also.
t.join(seconds)
In this case thread will wait only specified amount of time.
from threading import *
import time
class A(Thread):
def run(self):
for i in range(1,10):
print("rama")
time.sleep(2)
t=A()
t.start()
t.join(2)
for i in range(1,10):
print("seeta")
Daemon Threads:
The threads which are running in the background are called Daemon Threads.
The main objective of Daemon Threads is to provide support for Non Daemon Threads( like main thread)
Eg: Garbage Collector
Whenever Main Thread runs with low memory, immediately PVM runs Garbage Collector to destroy
useless objects and to provide free memory,so that Main Thread can continue its execution without having
any memory problems.
We can check whether thread is Daemon or not by using t.isDaemon() method of Thread class or by using
daemon property.
Synchronization:
If multiple threads are executing simultaneously then there may be a chance of data inconsistency
problems.
from threading import *
import time
def m(a):
for i in range(1,10):
print("good morning:",end="")
time.sleep(2)
print(a)

t=Thread(target=m,args=("ravi",))
p=Thread(target=m,args=("suresh",))
p.start()
t.start()

We are getting irregular output b'z both threads are executing simultaneously wish() function.
To overcome this problem we should go for synchronization.
In synchronization the threads will be executed one by one so that we can overcome data inconsistency
problems.
Synchronization means at a time only one Thread

The main application areas of synchronization are


Online Reservation system
Funds Transfer from joint accounts etc
In Python, we can implement synchronization by using the following
Lock
RLock
Semaphore
Synchronization By using Lock Concept:
Locks are the most fundamental synchronization mechanism provided by threading module.
We can create Lock object as follows l = Lock()
The Lock object can be hold by only one thread at a time.If any other thread required the same lock then it
will wait until thread releases lock. (Similar to common wash rooms, public telephone booth etc)
A Thread can acquire the lock by using acquire() Method l.acquire()
A Thread can release the lock by using release() Method l.release()
Note: To call release() method compulsory thread should be owner of that lock.i.e thread should has the
lock already, otherwise we will get Runtime Exception saying RuntimeError: release unlocked lock.

Example:
from threading import *
import time
r=Lock()
def m(a):
r.acquire()
for i in range(1,10):
print("good morning:",end="")
time.sleep(2)
print(a)
r.release()
t=Thread(target=m,args=("ravi",))
p=Thread(target=m,args=("suresh",))
t.start()
p.start()
Problem with Simple Lock:
The standard Lock object does not care which thread is currently holding that lock.If the lock is held and
any thread attempts to acquire lock, then it will be blocked,even the same thread is already holding that
lock.

from threading import *


import time
r=Lock()
def m(a):
r.acquire()
for i in range(1,10):
r.acquire()
print("good morning:",end="")
time.sleep(2)
print(a)
r.release()
r.release()
t=Thread(target=m,args=("ravi",))
p=Thread(target=m,args=("suresh",))
t.start()
p.start()
In the above Program main thread will be blocked b'z it is trying to acquire the lock second time.
Note: To kill the blocking thread from windows command prompt we have to use ctrl+break. Here ctrl+C
won't work.
If the Thread calls recursive functions or nested access to resources, then the thread may trying to acquire
the same lock again and again, which may block our thread.
Hence Traditional Locking mechanism won't work for executing recursive functions.
To overcome this problem, we should go for RLock(Reentrant Lock). Reentrant means the thread can
acquire the same lock again and again.If the lock is held by other threads then only the thread will be
blocked.
In this case Main Thread won't be Locked b'z thread can acquire the lock any number of times.
This RLock keeps track of recursion level and hence for every acquire() call compulsory release() call should
be available. i.e the number of acquire() calls and release() calls should be matched then only lock will be
released.

Eg:
l=RLock() l.acquire() l.acquire() l.release() l.release()
After 2 release() calls only the Lock will be released.

Note:
Only owner thread can acquire the lock multiple times
The number of acquire() calls and release() calls should be matched.
Demo Program for Synchronization by using RLock:
from threading import *
import time
r=RLock()
def m(a):
r.acquire()
for i in range(1,10):
r.acquire()
print("good morning:",end="")
time.sleep(2)
print(a)
r.release()
r.release()
t=Thread(target=m,args=("ravi",))
p=Thread(target=m,args=("suresh",))
t.start()
p.start()

Difference between Lock and RLock


Lock RLock
1) Lock object can be acquired by only one 1) RLock object can be acquired by only one
thread at a time. Even owner thread also thread at a time, but owner thread can
cannot acquire multiple times. acquire same lock object multiple times.
2) Not suitable to execute recursive 2) Best suitable to execute recursive
functions and nested access calls. functions and nested access calls.
3) In this case Lock object will takes care only 3) In this case RLock object will takes care
Locked or unlocked and it never takes care whether Locked or unlocked and owner
about owner thread and recursion level. thread information, recursiion level.

Synchronization by using Semaphore:


☕ In the case of Lock and RLock, at a time only one thread is allowed to execute.
☕ Sometimes our requirement is at a time a particular number of threads are allowed to access(like at a
time 10 memebers are allowed to access database server,4 members are allowed to access Network
connection etc).To handle this requirement we cannot use Lock and RLock concepts and we should go for
Semaphore concept.
☕ Semaphore can be used to limit the access to the shared resources with limited capacity.
☕ Semaphore is advanced Synchronization Mechanism.
☕ We can create Semaphore object as follows s = Semaphore(counter)
☕ Here counter represents the maximum number of threads are allowed to access simultaneously. The
default value of counter is 1.
☕ Whenever thread executes acquire() method,then the counter value will be decremented by 1 and if
thread executes release() method then the counter value will be incremented by 1.
☕ i.e for every acquire() call counter value will be decremented and for every release() call counter value
will be incremented.

from threading import *


import time
r=Semaphore(2)
def m(a):
r.acquire()
for i in range(1,10):
print("good morning:",end="")
time.sleep(2)
print(a)
r.release()
t=Thread(target=m,args=("ravi",))
p=Thread(target=m,args=("suresh",))
p.start()
t.start()

Bounded Semaphore:
Normal Semaphore is an unlimited semaphore which allows us to call release() method any number of
times to increment counter.The number of release() calls can exceed the number of acquire() calls also.
from threading import *
import time
r=Semaphore(2)
def m(a):
r.acquire()
for i in range(1,10):
print("good morning:",end="")
time.sleep(2)
print(a)
r.release()
r.release()
t=Thread(target=m,args=("ravi",))
p=Thread(target=m,args=("suresh",))
p.start()
t.start()

☕ It is valid because in normal semaphore we can call release() any number of times.
☕ BounedSemaphore is exactly same as Semaphore except that the number of release() calls should not
exceed the number of acquire() calls,otherwise we will get ValueError: Semaphore released too many
times

from threading import *


import time
r=BoundedSemaphore(2)
def m(a):
r.acquire()
for i in range(1,10):
print("good morning:",end="")
time.sleep(2)
print(a)
r.release()
r.release()
t=Thread(target=m,args=("ravi",))
p=Thread(target=m,args=("suresh",))
p.start()
t.start()

ValueError: Semaphore released too many times

Note: To prevent simple programming mistakes, it is recommended to use BoundedSemaphore over


normal Semaphore.

Difference between Lock and Semaphore:


At a time Lock object can be acquired by only one thread, but Semaphore object can be acquired by fixed
number of threads specified by counter value.
Conclusion:
The main advantage of synchronization is we can overcome data inconsistency problems.But the main
disadvantage of synchronization is it increases waiting time of threads and creates performance problems.
Hence if there is no specific requirement then it is not recommended to use synchronization.
Inter Thread Communication:
☕ Some times as the part of programming requirement, threads are required to communicate with each
other. This concept is nothing but interthread communication.
☕ Eg: After producing items Producer thread has to communicate with Consumer thread to notify about
new item.Then consumer thread can consume that new item.
☕ In Python, we can implement interthread communication by using the following ways
Event
Condition
Inter Thread Communication by using Event Objects:
☕ Event object is the simplest communication mechanism between the threads. One thread signals an
event and other thereds wait for it.
☕ We can create Event object as follows...
☕ event = threading.Event()
☕ Event manages an internal flag that can set() or clear()
☕ Threads can wait until event set.
Methods of Event Class:
set()  internal flag value will become True and it represents GREEN signal for all waiting threads.
clear()  inernal flag value will become False and it represents RED signal for all waiting threads.
isSet()  This method can be used whether the event is set or not
wait()|wait(seconds)  Thread can wait until event is set

Inter Thread Communication by using Condition Object:


☕ Condition is the more advanced version of Event object for interthread communication.A condition
represents some kind of state change in the application like producing item or consuming item. Threads
can wait for that condition and threads can be notified once condition happend.i.e Condition object allows
one or more threads to wait until notified by another thread.
☕ Condition is always associated with a lock (ReentrantLock).
☕ A condition has acquire() and release() methods that call the corresponding methods of the associated
lock.
☕ We can create Condition object as follows condition = threading.Condition()
Methods of Condition:
acquire()  To acquire Condition object before producing or consuming items.i.e thread acquiring internal
lock.
release()  To release Condition object after producing or consuming items. i.e thread releases internal lock

wait()|wait(time)  To wait until getting Notification or time expired

notify()  To give notification for one waiting thread

notifyAll()  To give notification for all waiting threads

Python MySQL
Python can be used in database applications. One of the most popular databases is MySQL.

Install MySQL Driver


Python needs a MySQL driver to access the MySQL database.
In this tutorial we will use the driver "MySQL Connector".
We recommend that you use PIP to install "MySQL Connector".
PIP is most likely already installed in your Python environment.
Navigate your command line to the location of PIP, and type the following:
Download and install "MySQL Connector":
C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>python -m pip install mysql-
connector-python
Now you have downloaded and installed a MySQL driver.

Create Connection:
import mysql.connector
mydb=mysql.connector.connect(host="localhost
",user="root",password="root")
print(mydb)

Creating a Database
To create a database in MySQL, use the "CREATE DATABASE" statement:
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",password="root")
cur=mydb.cursor()
cur.execute("create database college")

Check if Database Exists


import mysql.connector
mydb=mysql.connector.connect(host="localhost
",user="root",password="root")
cur=mydb.cursor()
cur.execute("show databases")
for i in cur:
print(i)

Creating a Table
To create a table in MySQL, use the "CREATE TABLE" statement.
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",password="root", database="college")
cur=mydb.cursor()
cur.execute("create table student (id int(3),name varchar(255),address varchar(50))")

Check if Table Exists


You can check if a table exist by listing all tables in your database with the "SHOW TABLES" statement:
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",password="root",
database="college")
cur=mydb.cursor()
cur.execute("show tables")
for i in cur:
print(i)

Insert Into Table


To fill a table in MySQL, use the "INSERT INTO" statement.
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",password="root",
database="college")
cur=mydb.cursor()
cur.execute("insert into student(id,name,address)values(1,'suresh','vizag')")
mydb.commit()
mportant!: Notice the statement: mydb.commit(). It is required to make the changes, otherwise no changes are
made to the table.

Insert Multiple Rows


To insert multiple rows into a table, use the executemany() method.
The second parameter of the executemany() method is a list of tuples, containing the data you want to insert:
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",password="root",
database="college")
cur=mydb.cursor()
sql="insert into student(id,name,address)values(%s,%s,%s)"
val=[(2,"ramesh","vzm"),(3,"hari","vizag")]
cur.executemany(sql,val)
mydb.commit()

Select From a Table


To select from a table in MySQL, use the "SELECT" statement:

import mysql.connector
mydb=mysql.connector.connect(host="localhost
",user="root",password="root",
database="college")
cur=mydb.cursor()
cur.execute("select * from student")
for i in cur:
print(i)
Select With a Filter
When selecting records from a table, you can filter the selection by using the "WHERE" statement:
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",password="root",
database="college")
cur=mydb.cursor()
cur.execute("select * from student where address='vizag'")
for i in cur:
print(i)

Sort the Result


Use the ORDER BY statement to sort the result in ascending or descending order.
The ORDER BY keyword sorts the result ascending by default. To sort the result in descending order, use the
DESC keyword.

import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",password="root",
database="college")
cur=mydb.cursor()
cur.execute("select * from student order by name")
for i in cur:
print(i)

Delete Record
You can delete records from an existing table by using the "DELETE FROM" statement:
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",password="root",
database="college")
cur=mydb.cursor()
cur.execute("delete from student where id=3")

Delete a Table
You can delete an existing table by using the "DROP TABLE" statement:
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",password=
"root", database="college")
cur=mydb.cursor()
cur.execute("drop table student")
Update Table
You can update existing records in a table by using the "UPDATE" statement:
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",password="root",
database="college")
cur=mydb.cursor()
cur.execute("update student set address='vizag' where address='vzm'")
mydb.commit()Limit the Result
You can limit the number of records returned from the query, by using the "LIMIT" statement:
Program===========================
NumPy
NumPy is a Python library. NumPy is used for working with arrays. NumPy is short for "Numerical Python".

What is NumPy?
NumPy is a Python library used for working with arrays.
It also has functions for working in domain of linear algebra, fourier transform, and matrices.
NumPy was created in 2005 by Travis Oliphant. It is an open source project and you can use it freely.
NumPy stands for Numerical Python.

Why Use NumPy?


In Python we have lists that serve the purpose of arrays, but they are slow to process.
NumPy aims to provide an array object that is up to 50x faster than traditional Python lists.
The array object in NumPy is called ndarray, it provides a lot of supporting functions that make working
with ndarray very easy.
Arrays are very frequently used in data science, where speed and resources are very important.

Why is NumPy Faster Than Lists?


NumPy arrays are stored at one continuous place in memory unlike lists, so processes can access and
manipulate them very efficiently.
This behavior is called locality of reference in computer science.
This is the main reason why NumPy is faster than lists. Also it is optimized to work with latest CPU architectures.

Pandas
Pandas is a Python library.Pandas is used to analyze data.

What is Pandas?
Pandas is a Python library used for working with data sets.
It has functions for analyzing, cleaning, exploring, and manipulating data.
The name "Pandas" has a reference to both "Panel Data", and "Python Data Analysis" and was created by Wes
McKinney in 2008.

Why Use Pandas?


Pandas allows us to analyze big data and make conclusions based on statistical theories.
Pandas can clean messy data sets, and make them readable and relevant.
Relevant data is very important in data science.

What Can Pandas Do?


Pandas gives you answers about the data. Like:
Is there a correlation between two or more columns?
What is average value?
Max value?
Min value?
Pandas are also able to delete rows that are not relevant, or contains wrong values, like empty or NULL values.
This is called cleaning the data.

Matplotlib
What is Matplotlib?
Matplotlib is a low level graph plotting library in python that serves as a visualization utility.
Matplotlib was created by John D. Hunter.
Matplotlib is open source and we can use it freely.
Matplotlib is mostly written in python, a few segments are written in C, Objective-C and Javascript for Platform
compatibility.

You might also like