0% found this document useful (0 votes)
197 views517 pages

Python Programming Features Overview

The document provides an overview of Python, highlighting its features such as simplicity, ease of learning, and dynamic typing. It compares Python with C, emphasizing differences in memory management, data types, and syntax. Additionally, it covers various data types in Python, including numeric, string, list, tuple, set, and dictionary, along with examples of their usage.

Uploaded by

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

Python Programming Features Overview

The document provides an overview of Python, highlighting its features such as simplicity, ease of learning, and dynamic typing. It compares Python with C, emphasizing differences in memory management, data types, and syntax. Additionally, it covers various data types in Python, including numeric, string, list, tuple, set, and dictionary, along with examples of their usage.

Uploaded by

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

Introduction

Python
Python

● Combines the features of C and JAVA


● It offers elegant style of developing programs like C
● It offers classes and objects like Java
Features of Python

● Simple
● More clarity
● Less stress on reading and understanding the syntax

● Easy to learn
● Uses very few keywords
● Very simple structure, resembles C

● Open source
● High level language
● Dynamically typed
● Type of the variable is not declared statically
Features of Python...

● Platform Independent
○ Python compiler generates byte code
○ PVM interprets the byte code

● Portable
● Procedure and Object oriented language
● Interpreted
● Extensible
● Embeddable
● Huge Library
● Scripting Language
● Database Connectivity
○ Provides interfaces to DB like Oracle, Sybase or MySql
Execution of a Python Program

● Example:
● [Link] → python_compiler → [Link] → PVM → Machine_Code
● python -m py_compile [Link]
● python [Link]
● python -m dis [Link]
Memory Management in Python

● In C or C++, allocation and deallocation of memory will be done manually


● malloc(), calloc(), realloc() or free()

● In python, it is done at run time automatically


● Memory Manager inside the PVM takes care of allocating memory for all objects in
Python.
● All objects are stored in Heap
Garbage Collection in Python

● Garbage collector is a module in Python that is useful to delete objects from memory
which are not used in the program.
● The module that represents the GC is gc.
● It will keep track of how many times the object is referenced.
● If it is referenced 0 times, then gc will remove object from memory.
C Vs Python
C Python

Procedure Oriented language Object Oriented language

Faster Slower

Compulsory to declare the data types of variables Data Types are not required

Type discipline is static and weak Dynamic and strong

Pointers concept present No pointers concept

No exception handling facility Exception handling facility is robust

Do-while is present Absent

Has switch statement No Switch


C Vs Python
C Python

Manually allocate the memory Automatic

Absence of GC GC is present

Supports Single and multi dimensional arrays Supports only single dimension

Array should be positive Can be Positive or negative

Array bounds checking is not present Present

Indentation is not necessary Strictly needed

Every statement is terminated by ; No semicolon


Chapter-2
Data Types
Data Types

Comments
Comments
Single Line Comments
● Starts with # symbol
● Comments are non-executable statements

1 #To find sum of two numbers


2 a = 10 #Store 10 into variable 'a'
Comments
Multi Line Comments
● Version-1
1 #To find sum of two numbers
2 #This is multi-line comments
3 #One more commented line

● Version-2
4 """
5 This is first line
6 This second line
7 Finally comes third
8 """

● Version-3
4 '''
5 This is first line
6 This second line
7 Finally comes third
8 '''
Docstrings
Multi Line Comments
● Python supports only single line commenting
● Strings enclosed within ''' … ''' or """ … """, if not assigned to any variable, they are removed from
memory by the GC
● Also called as Documentation Strings OR docstrings
● Useful to create API file

Command to Create the html file


-------------------------------
py -m pydoc -w 1_Docstrings

-m: Module
-w: To create the html file
How python sees variables
Data-Types
None Type
● None data-type represents an object that does not contain any value
● In Java, it is called as NULL Object
● In Python, it is called as NONE Object
● In boolean expression, NONE data-type represents ‘False’
● Example:
○ a = “”
Data-Types
Numeric Type
● int
○ No limit for the size of an int datatype
○ Can store very large numbers conveniently
○ Only limited by the memory of the system
○ Example:
■ a = 20
Data-Types
Numeric Type
● float
○ Example-1:
■ A = 56.78

○ Example-2:
■ B = 22.55e3 ⇔ B = 22.55 x 10^3
Data-Types
Numeric Type
● Complex
○ Written in the form a + bj OR a + bJ
○ a and b may be ints or floats
○ Example:
■ c = 1 + 5j
■ c = -1 - 4.4j
Representation
Binary, Octal, Hexadecimal
● Binary
○ Prefixed with 0b OR 0B
■ 0b11001100
■ 0B10101100
● Octal
○ Prefixed with 0o OR 0O
■ 0o134
■ 0O345
● Hexadecimal
○ Prefixed with 0x OR 0X
■ 0xAB
■ 0Xab
Conversion
Explicit
● Coercion / type conversions
○ Example-1:

x = 15.56
int(x) #Will convert into int and display 15

○ Example-2:

x = 15
float(x) #Will convert into float and display 15.0
Conversion
Explicit
● Coercion / type conversions
○ Example-3:

a = 15.56
complex(a) #Will convert into complex and display (15.56 + 0j)

○ Example-4:
a = 15
b = 3
complex(a, b) #Will convert into complex and display (15 + 3j)
Conversion
Explicit
● Coercion / type conversions
○ Example-5: To convert string into integer
○ Syntax: int(string, base)

str = “1c2”
n = int(str, 16)
print(n)

○ Other functions are


■ bin(): To convert int to binary
■ oct(): To convert oct to binary
■ hex(): To convert hex to binary
bool Data-Type
● Two bool values
○ True: Internally represented as 1
○ False: Internally represented as 0

● Blank string “” also represented as False

● Example-1:

a = 10
b = 20
if ( a < b):
print(“Hello”)
bool Data-Type

● Example-2:
a = 10 > 5
print(a) #Prints True

a = 5 > 10
print(a) #Prints False

● Example-3:

print(True + True) #Prints 2

print(True + False) #Prints 1


Data Types

Sequences
Sequences
str
● str represents the string data-type
● Example-1:
3 str = "Welcome to Python"
4 print(str)
5
6 str = 'Welcome to Python'
7 print(str)

● Example-2:
3 str = """
4 Welcome to Python
5 I am very big
6 """
7 print(str)
8
9 str = '''
10 Welcome to Python
11 I am very big
12 '''
13 print(str)
Sequences
str
● Example-3:
3 str = "This is 'core' Python"
4 print(str)
5
6 str = 'This is "core" Python'
7 print(str)

● Example-4:

3 s = "Welcome to Python"
4
5 #Print the whole string
6 print(s)
7
8 #Print the character indexed @ 2
9 print(s[2])
10
11 #Print range of characters
12 print(s[2:5]) #Prints 2nd to 4th character
13
14 #Print from given index to end
15 print(s[5: ])
16
17 #Prints first character from end(Negative indexing)
18 print(s[-1])
Sequences
str
● Example-5:

3 s = "Emertxe"
4
5 print(s * 3)
Data Types

bytes Data-types
Sequences
bytes
● bytes represents a group of byte numbers
● A byte is any positive number between 0 and 255(Inclusive)
● Example-1:

3 #Create the list of byte type array


4 items = [10, 20, 30, 40, 50]
5
6 #Convert the list into bytes type array
7 x = bytes(items)
8
9 #Print the array
10 for i in x:
11 print(i)
Sequences
bytes
● Modifying any item in the byte type is not possible
● Example-2:

3 #Create the list of byte type array


4 items = [10, 20, 30, 40, 50]
5
6 #Convert the list into bytes type array
7 x = bytes(items)
8
9 #Modifying x[0]
10 x[0] = 11 #Gives an error
Data Types

bytearray Data-type
Sequences
bytearray
● bytearray is similar to bytes
● Difference is items in bytearray is modifiable
● Example-1:

3 #Create the list of byte type array


4 items = [10, 20, 30, 40, 50]
5
6 #Convert the list into bytes type array
7 x = bytearray(items)
8
9 x[0] = 55 #Allowed
10
11 #Print the array
12 for i in x:
13 print(i)
Data Types

list Data-type
Sequences
list
● list is similar to array, but contains items of different data-types
● list can grow dynamically at run-time, but arrays cannot
● Example-1:
3 #Create the list
4 list = [10, -20, 15.5, 'Emertxe', "Python"]
5
6 print(list)
7
8 print(list[0])
9
10 print(list[1:3])
11
12 print(list[-2])
13
14 print(list * 2)
Data Types

tuple Data-type
Sequences
tuple
● tuple is similar to list, but items cannot be modified
● tuple is read-only list
● tuple are enclosed within ()
● Example-1:

3 #Create the tuple


4 tpl = (10, -20, 12.34, "Good", 'Elegant')
5
6 #print the list
7 for i in tpl:
8 print(i)
Data Types

range Data-type
Sequences
range
● range represents sequence of numbers
● Numbers in range are not modifiable
● Example-1:

3 #Create the range of numbers


4 r = range(10)
5
6 #Print the range
7 for i in r:
8 print(i)
Sequences
range
● Example-2:
10 #Print the range with step size 2
11 r = range(20, 30, 2)
12
13 #Print the range
14 for i in r:
15 print(i)

● Example-3:
17 #Create the list with range of numbers
18 lst = list(range(10))
19 print(lst)
Data Types

Sets
Sets

● Set is an unordered collection of elements


● Elements may not appear in the same order as they are entered into the set
● Set does not accept duplicate items
● Types
○ set datatype
○ frozenset datatype
Sets
set
● Example-1:

3 #Create the set


4 s = {10, 20, 30, 40, 50}
5 print(s) #Order will not be maintained

● Example-2:
8 ch = set("Hello")
9 print(ch) #Duplicates are removed

● Example-3:
11 #Convert list into set
12 lst = [1, 2, 3, 3, 4]
13 s = set(lst)
14 print(s)
Sets
set
● Example-5:

11 #Convert list into set


12 lst = [1, 2, 3, 3, 4]
13 s = set(lst)
14 print(s)

● Example-6:

16 #Addition of items into the array


17 [Link]([50, 60])
18 print(s)
19
20 #Remove the item 50
21 [Link](50)
22 print(s)
Sets
frozenset
● Similar to that of set, but cannot modify any item
● Example-1:
2 s = {1, 2, 3, 4}
3 print(s)
4
5 #Creating the frozen set
6 fs = frozenset(s)
7 print(fs)

● Example-2:
9 #One more methos to create the frozen set
10 fs = frozenset("abcdef")
11 print(fs)
Data Types

Mapping Types
Mapping

● Map represents group of items in the form of key: value pair


● dict data-type is an example for map
● Example-1:
3 #Create the dictionary
4 d = {10: 'Amar', 11: 'Anthony', 12: 'Akbar'}
5 print(d)
6
7 #Print using the key
8 print(d[11])

● Example-2:
10 #Print all the keys
11 print([Link]())
12
13 #Print all the values
14 print([Link]())
Mapping

● Example-3:

16 #Change the value


17 d[10] = 'Akul'
18 print(d)
19
20 #Delete the item
21 del d[10]
22 print(d)

● Example-4:
24 #create the dictionary and populate dynamically
25 d = {}
26 d[10] = "Ram"
27
28 print(d)
Data Types

Determining the Datatype


Determining Datatype of a Variable

● type()
● Example-1:
3 a = 10
4 print(type(a))
5
6 b = 12.34
7 print(type(b))
8
9 l = [1, 2, 3]
10 print(type(l))
Operators
Team Emertxe
Arithmetic
OPERATORS
Arithmetic
Operator Example Result

+ a+b 18

- a-b 8

* a*b 65

/ a/b 2.6

% a%b 3

** a ** b 371293

// a // b 2

The results are obtained for the values of:


a = 13
b = 5
OPERATORS
Assignment
Operators Example-1:

= a = b = 1

+=

-+ Example-2:

*+ a = 1; b = 1

/=

%= Example-3:

**=
a, b = 1, 2

//=

Python does not have ++ AND -- operators


OPERATORS
Unary Minus
Example-1:

n = 10
print(-n)

Example-2:
num = -10
num = -num
print(num)
OPERATORS
Relational
Operator Example Result

> a > b False

>= a >= b False

< a < b True

<= a <= b True

== a == b False

!= a != b True

The results are obtained for the values of:


a = 1
b = 2
OPERATORS
Relational: Chaining
Example-1:
x = 15
print(10< x < 20)

Example-2:

print(1 < 2 < 3 < 4)


OPERATORS
Logical
If a = 100, b = 200
Operator Example Result

and a and b 2

or a or b 1

not not a False

Example-1: Example-2:
if (a < b and b < c): if (a > b or b < c):
print("Yes") print("Yes")
else: else:
print("No") print("No")

Short Circuit evaluation implies to Logical Operators


OPERATORS
Boolean
If a = True, b = False
Operator Example Result

and a and b False

or a or b True

not not a False

Example-1:
print(a and b)
print(a or b)
print(not a)
OPERATORS
Bitwise
If a = 10(0000 1010), b = 11(0000 1011)
Operator Example Result

~ ~a 1111 0101(-11)

& a & b 0000 1010(10)

| a | b 0000 1011(11)

^ a ^ b 0000 0001(1)

<< a << 2 0010 1000(40)

>> a >> 2 0000 0010(2)

In case of >> shifting, it preserves the sign of the number.


OPERATORS
Membership
Operator Description

in Returns True, if an item is found in the specified sequence

not in Returns True, if an item is not found in the specified sequence

Example-1:
names = ["Ram", "Hari", "Thomas"]

for i in names:
print(i)

Example-2:
postal = {"Delhi": 110001, "Chennai": 600001, "Bangalore": 560001}

for city in postal:


print(city, postal[city])
OPERATORS
Identity

Use to comapre the memory locations of two objects

id(): Is used to get the memory location ID
Example-1:
a = 25
b = 25
if (a is b): #This compares only the locations
print("a and b are same")

Operator Description

is Returns True, if ID of two objects are same

is not Returns True, if ID of two objects are not same


OPERATORS
Identity

To compare two objects, use ‘==’ operator

Example-1:
a = [1, 2, 3, 4]
b = [1, 2, 3, 4]

if (a == b):
print("Objects are same")
else:
print("Objects are not same")
OPERATORS
Precedence & Associativity
Operator Name
(expressions...), [expressions...], {key: Binding or tuple display, list display, dictionary
value...}, {expressions...} display, set display
x[index], x[index:index], x(arguments...), Subscription, slicing, call, attribute reference
[Link]
** Exponentiation

+, -, ~ Positive, negative, bitwise NOT

*, @, /, //, % Multiplication, matrix multiplication, division,


floor division, remainder
+, - Addition, Subraction

<<, >> Bitwise Left, Right shift

& Bitwise AND

^ Bitwise XOR

| Bitwise OR

in, not in, is, is not, <, <=, >, >=, !=, == Comparisons, including membership tests and identity
tests
not Boolean not

and Boolean and

or Boolean or

if-else Conditional Expression

lambda Lambda Expression

All operators follow, Left – Right associativity, except ** which


follows Right - Left
Mathematical Functions
Example-1:
import math
x = [Link](16)

Example-2:
import math as m
x = [Link](16)

Example-3:
from math import sqrt
x = sqrt(16)

Example-4:
from math import sqrt, factorial
x = sqrt(16)
y = factorial(5)
THANK YOU
Standard Input & Output
Team Emertxe
Output Statements
Output Statements
Print()

 print(), when called simply throws the cursor to the next line
 Means, a blank line will be displayed
Output Statements
Print(“string”)
Example Output

print()
Prints the '\n' character

print("Hello") Hello

print('Hello') Hello

print("Hello \nWorld") Hello


World
print("Hello \tWorld") Hello World

print("Hello \\nWorld") Hello \nWorld

print(3 * 'Hello') HelloHelloHello

print("Hello"+"World") HelloWorld

print("Hello","World") Hello World


Output Statements
Print(variable list)
Example Output

a, b = 1, 2
print(a, b) 1 2

print(a, b, sep=",") 1,2

print(a, b, sep=':') 1:2

print(a, b, sep='---') 1---2

print("Hello", end="") HelloWorld


print("World")
print("Hello", end="\t") Hello World
print("World")
Output Statements
Print(object)

Objects like list, tuples or dictionaries can be displayed
Example Output

lst = [10, 'A', "Hai"]


print(lst) [10, 'A', 'Hai']

d = {10: "Ram", 20: "Amar"} {10: 'Ram', 20: 'Amar'}


print(d)
Output Statements
Print(“string”, variable list)

Example Output

a = 2
print(a, ": Even Number") 2 : Even Number
You typed 2 as Input
print("You typed", a, "as Input")
Output Statements
Print(formatted string)
Syntax: print("formatted string" % (varaible list))
Example Output
a = 10
print("The value of a: %i" % a) The value of a: 10

a, b = 10, 20 a: 10 b: 20
print("a: %d\tb: %d" % (a, b))
name = "Ram" Hai Ram
print("Hai %s" % name) Hai ( Ram)
print("Hai (%20s)" % name) Hai (Ram )
print("Hai (%-20s)" % name)
print("%c" % name[2]) m
print("%s" % name[0:2]) Ra
num = 123.345727 Num: 123.345727
print("Num: %f" % num) Num: 123.35
print("Num: %8.2f" % num)
Output Statements
Print(formatted string)
Syntax: print("formatted string" % (varaible list))
Example Output
a, b, c = 1, 2, 3
print("First= {0}". format(a))
print("First= {0}, Second= {1}". format(a, b)) First= 1
print("First= {one}, Second= {two}". format(one=a, two=b)) First= 1, Second= 2
print("First= {}, Second= {}". format(a, b)) First= 1, Second= 2
First= 1, Second= 2

name, salary = "Ram", 123.45 Hello Ram, your salary: 123.45


print("Hello {0}, your salary: {1}". format(name, salary)) Hello Ram, your salary: 123.45
print("Hello {n}, your salary: {s}". format(n=name, s=salary)) Hello Ram, your salary: 123.45
print("Hello {:s}, your salary: {:.2f}". format(name, salary)) Hello Ram, your salary: 123.45
print("Hello %s, your salary: %.2f" % (name, salary))
Input Statements
Input Statements
Input()
Example
str = input()
print(str)

str = input("Enter the name: ")


print(str)

a = int(input("Enter the number: "))


print(a)

b = float(input("Enter the float number: "))


print(b)
Command Line Arguments
CLA
Example

1 #To display CLA


2
3 import sys
4
5 #Get the no. of CLA
6 n = len([Link])
7
8 #Get the arguments
9 args = [Link]
10
11 #Print the 'n'
12 print("No. Of CLA: ", n)
13
14 #print the arguments in one shot
15 print(args)
16
17 #Print the arguments one by one
18 for i in args:
19 print(i)
CLA
Parsing CLA

argparse module is useful to develop user-friendly programs

This module automatically generates help and usage messages

May also display appropriate error messages
CLA
Parsing CLA: Steps
● Step-1: Import argparse module
import argparse

● Step-2: Create an Object of ArgumentParser


parser = [Link](description="This program displays square of two numbers")

● Step-2a: If programmer does not want to display description, then above step can
be skipped
parser = [Link]()

● Step-3: Add the arguments to the parser


parser.add_argument("num", type=int, help="Enter only int number.")

● Step-4: Retrieve the arguments


args = parser.parse_args()

● Step-5: Access the arguments


[Link]
THANK YOU
Control Statements
Team Emertxe
Single Control Statements
If Statements
If-Else

 Syntax

if condition:
statements
else:
statements


Example

if num % 2:
print("ODD")
else:
print("EVEN")
If Statements
If-Elif-Else

 Syntax

if condition1:
statements
elif condition2:
statements
else
statements

Example

if num == 1:
print("You entered 1")
elif num == 2:
print("You entered 2")
else:
print("You entered 3")
Multiple Control Statements
Multiple Statements
While

 Syntax

while condition:
statements


Example
i = 1
while i <= 10:
print(i)
i = i + 1
Multiple Statements
For

 Syntax

for var in sequence:


statements


Example-v1.1 
Example-v1.2
str = "Hello" n = len(str)
for ch in str: for i in range(n):
print(ch, end='') print(str[i])
Else Suite
Multiple Statements
For with Else suite

 Syntax

for var in sequence:


statement / statements
else:
statement / statements


Example
for i in range(5):
print(i)
else:
print("Over")
Multiple Statements
While with Else suite

 Syntax

while condition:
statement / statements
else:
statement / statements


Example
i = 0
while i < 5
print(i)
i += 1
else:
print("Over")

While searching an elemnt in the sequence is not found,


else will be the best option to display the item not found
Misc Statements
Misc Statements
Break

 Example

x = 10
while x >= 1:
print("x = ", x)
x -= 1
if x == 5:
break
Misc Statements
Continue

 Example

x = 10
while x >= 1:
if x == 5:
x -= 1
continue
print("x = ", x)
x -= 1
Misc Statements
Pass

 Example-1

x = 0
while x < 10:
x += 1
if x == 5:
pass
print(x)
Misc Statements
Pass

 Example-2: Program to retrieve only the negative numbers from the list

num = [1, 2, 3, -4, -5, -6, 7, 8]


for i in num:
if (i > 0):
pass
else:
print(i)

Pass does nothing


Misc Statements
Assert

 Syntax:

assert expression, message

 Example-1

num = int(input("Enter the number greater than zero: "))


assert num > 0, "Wrong input"
print("Num: ", num)
Misc Statements
Assert: Try Except
 Example-1

num = int(input("Enter the number greater than zero: "))


try:
assert num > 0, "Wrong input"
print("Num: ", num)
except AssertionError:
print("You entered wrong input")
print("Enter positive number")
Misc Statements
Return

 Example-1: To add two numbers & return the result

def sum(a, b):


return a + b

res = sum(5, 10)


print(res)
THANK YOU
Array
Team Emertxe
Single Dimensional Arrays
Single Dimensional Arrays
Creating an Array

Syntax array_name = array(type_code, [elements])

Example-1 a = array(‘i’, [4, 6, 2, 9])

Example-2 a = array(‘d’, [1.5, -2.2, 3, 5.75])


Single Dimensional Arrays
Creating an Array
Typecode C Type Sizes
‘b’ signed integer 1

‘B’ unsigned integer 1

‘i’ signed integer 2

‘I’ unsigned integer 2

‘l’ signed integer 4

‘L’ unsigned integer 4

‘f’ floating point 4

‘d’ double precision floating point


8

‘u’ unicode character 2


Single Dimensional Arrays
Importing an Array Module

import array a = [Link](‘i’, [4, 6, 2, 9])

import array as ar a = [Link](‘i’, [4, 6, 2, 9])

from array import * a = array(‘i’, [4, 6, 2, 9])


Importing an Array Module
Example-1

import array

#Create an array
a = [Link]("i", [1, 2, 3, 4])

#print the items of an array


print("Items are: ")
for i in a:
print(i)
Importing an Array Module
Example-2

from array import *

#Create an array
a = array("i", [1, 2, 3, 4])

#print the items of an array


print("Items are: ")
for i in a:
print(i)
Importing an Array Module
Example-3

from array import *

#Create an array
a = array('u', ['a', 'b', 'c', 'd'])
#Here, 'u' stands for unicode character

#print the items of an array


print("Items are: ")
for ch in a:
print(ch)
Importing an Array Module
Example-4

from array import *

#Create first array


a = array('i', [1, 2, 3, 4])

#From first array create second


b = array([Link], (i for i in a))

#print the second array items


print("Items are: ")
for i in b:
print(i)

#From first array create third


c = array([Link], (i * 3 for i in a))

#print the second array items


print("Items are: ")
for i in c:
print(i)
Indexing & Slicing on Array
Example-1: Indexing

#To retrieve the items of an array using array index

from array import *

#Create an array
a = array('i', [1, 2, 3, 4])

#Get the length of the array


n = len(a)

#print the Items


for i in range(n):
print(a[i], end=' ')
Indexing & Slicing on Array
Example-2: Indexing

#To retrieve the items of an array using array index using while loop

from array import *

#Create an array
a = array('i', [1, 2, 3, 4])

#Get the length of the array


n = len(a)

#print the Items


i = 0
while i < n:
print(a[i], end=' ')
i += 1
Indexing & Slicing on Array
Slicing

Syntax arrayname[start: stop: stride]

Example arr[1: 4: 1]

Prints items from index 1 to 3 with the step size of 1


Indexing & Slicing on Array
Example-3: Slicing

#Create an array
x = array('i', [10, 20, 30, 40, 50, 60])

#Create array y with Items from 1st to 3rd from x


y = x[1: 4]
print(y)

#Create array y with Items from 0th till the last Item in x
y = x[0: ]
print(y)

#Create array y with Items from 0th till the 3rd Item in x
y = x[: 4]
print(y)

#Create array y with last 4 Items in x


y = x[-4: ]
print(y)

#Stride 2 means, after 0th Item, retrieve every 2nd Item from x
y = x[0: 7: 2]
print(y)

#To display range of items without storing in an array


for i in x[2: 5]:
print(i)
Indexing & Slicing on Array
Example-4: Slicing

#To retrieve the items of an array using array index using for loop

from array import *

#Create an array
a = array('i', [1, 2, 3, 4])

#Display elements from 2nd to 4th only


for i in a[2: 5]:
print(i)
Processing the Array

Method Description

[Link](x) Adds an element x at the end of the existing array a

[Link](x) Returns the numbers of occurrences of x in the array a

[Link](x) Appends x at the end of the array a. ‘x’ can be another array or an
iterable object

[Link](x) Returns the position number of the first occurrence of x in the


array. Raises ‘ValueError’ if not found

[Link](i, x) Inserts x in the position i in the array


Processing the Array

Method Description

[Link](x) Removes the item x from the arry a and returns it

[Link]() Removes last item from the array a

[Link](x) Removes the first occurrence of x in the array a. Raises


‘ValueError’ if not found

[Link]() Reverse the order of elements in the array a

[Link]() Converts the array ‘a’ into a list


Processing the Array
Examples
from array import *
#Create an array
a = array('i', [1, 2, 3, 4, 5])
print(a)

#Append 6 to an array
[Link](6)
print(a)

#Insert 11 at position 1
[Link](1, 11)
print(a)

#Remove 11 from the array


[Link](11)
print(a)

#Remove last item using pop()


item = [Link]()
print(a)
print("Item pop: ", item)
Processing the Array
Exercises
1. To store student’s marks into an array and find total marks and percentage of marks

2. Implement Bubble sort

3. To search for the position of an item in an array using sequential search

4. To search for the position of an element in an array using index() method


Single Dimensional Arrays
Numpy
Single Dimensional Arrays
Importing an numpy

import numpy a = [Link]([4, 6, 2, 9])

import numpy as np a = [Link]([4, 6, 2, 9])

from numpy import * a = array([4, 6, 2, 9])


Single Dimensional Arrays
Creating an Array: numpy-array()

Example-1: To create an array of int datatype

a = array([10, 20, 30, 40, 50], int)

Example-2: To
Example-2: Tocreate
createanan array
array of of float
float datatype
datatype

= array([10.1,
a = array([10.1,20.2,
20.2,30.3,
30.3, 40.4,
40.4, 50.5],
50.5], float)
float)

Example-3: To create an array of float datatype without specifying the float datatype

a = array([10, 20, 30.3, 40, 50])

Note: If one item in the array is of float type, then Python interpreter converts
remaining items into the float datatype

Example-4: To create an array of char datatype

a = array([‘a’, ‘b’, ‘c’, ‘d’])

Note: No need to specify explicitly the char datatype


Single Dimensional Arrays
Creating an Array: numpy-array()

Program-1: To create an array of char datatype


from numpy import *

a = array(['a', 'b', 'c', 'd'])


print(a)

Program-2: To create an array of str datatype

from numpy import *

a = array(['abc', 'bcd', 'cde', 'def'], dtype=str)


print(a)
Single Dimensional Arrays
Creating an Array: numpy-array()

Program-3: To create an array from another array using numpy


from numpy import *

a = array([1, 2, 3, 4, 5])
print(a)

#Create another array using array() method


b = array(a)
print(a)

#Create another array by just copy


c = a
print(a)
Single Dimensional Arrays
Creating an Array: numpy-linspace()

Syntax linspace(start, stop, n)


Example a = linspace(0, 10, 5)
Description Create an array ‘a’ with starting element 0 and ending 10.
This range is divide into 5 equal parts
Hence, items are 0, 2.5, 5, 7.5, 10

Program-1: To create an array with 5 equal points using linspace

from numpy import *

#Divide 0 to 10 into 5 parts and take those points in the array


a = linspace(0, 10, 5)
print(a)
Single Dimensional Arrays
Creating an Array: numpy-logspace()

Syntax logspace(start, stop, n)


Example a = logspace(1, 4, 5)
Description Create an array ‘a’ with starting element 10^1 and ending 10^4.
This range is divide into 5 equal parts
Hence, items are 10. 56.23413252 316.22776602 1778.27941004 10000.

Program-1: To create an array with 5 equal points using logspace

from numpy import *

#Divide the range 10^1 to 10^4 into 5 equal parts


a = logspace(1, 4, 5)
print(a)
Single Dimensional Arrays
Creating an Array: numpy-arange()
Syntax arange(start, stop, stepsize)
Example-1 arange(10) Produces items from 0 - 9

Example-2 arange(5, 10) Produces items from 5 - 9

Example-3 arange(1, 10, 3) Produces items from 1, 4, 7

Example-4 arange(10, 1, -1) Produces items from [10 9 8 7 6 5 4 3 2]

Example-5 arange(0, 10, 1.5) Produces [0. 1.5 3. 4.5 6. 7.5 9.]

Program-1: To create an array with even number upto 10


from numpy import *

a = arange(2, 11, 2)
print(a)
Single Dimensional Arrays
Creating Array: numpy-zeros() & ones()
Syntax zeros(n, datatype)

ones(n, datatype)
Example-1 zeros(5) Produces items [0. 0. 0. 0. 0.]
Default datatype is float
Example-2 zeros(5, int) Produces items [0 0 0 0 0]
Example-3 ones(5, float) Produces items [1. 1. 1. 1. 1.]

Program-1: To create an array using zeros() and ones()


from numpy import *

a = zeros(5, int)
print(a)

b = ones(5) #Default datatype is float


print(b)
Single Dimensional Arrays
Vectorized Operations
Example-1 a = array([10, 20 30.5, -40])
a = a + 5 #Adds 5 to each item of an array
Example-2 a1 = array([10, 20 30.5, -40])

a2 = array([1, 2, 3, 4])

a3 = a1 + a2 #Adds each item of a1 and a2

Importance of vectorized operations


1. Operations are faster
- Adding two arrays in the form a + b is faster than taking corresponding items of both
arrays and then adding them.

2. Syntactically clearer
- Writing a + b is clearer than using the loops

3. Provides compact code


Single Dimensional Arrays
Mathematical Operations
sin(a) Calculates sine value of each item in the array a

arcsin(a) Calculates sine inverse value of each item in the array a

log(a) Calculates natural log value of each item in the array a

abs(a) Calculates absolute value of each item in the array a

sqrt(a) Calculates square root value of each item in the array a

power(a, n) Calculates a ^ n

exp(a) Calculates exponential value of each item in the array a

sum(a) Calculates sum of each item in the array a

prod(a) Calculates product of each item in the array a

min(a) Returns min value in the array a

max(a) Returns max value in the array a


Single Dimensional Arrays
Comparing Arrays


Relational operators are used to compare arrays of same size

These operators compares corresponding items of the arrays and return another array with
Boolean values

Program-1: To compare two arrays and display the resultant Boolean type array
from numpy import *

a = array([1, 2, 3])
b = array([3, 2, 3])

c = a == b
print(c)

c = a > b
print(c)

c = a <= b
print(c)
Single Dimensional Arrays
Comparing Arrays


any(): Used to determine if any one item of the array is True

all(): Used to determine if all items of the array are True

Program-2: To know the effects of any() and all()


from numpy import *

a = array([1, 2, 3])
b = array([3, 2, 3])

c = a > b
print(c)

print("any(): ", any(c))


print("all(): ", all(c))

if (any(a > b)):


print("a contains one item greater than those of b")
Single Dimensional Arrays
Comparing Arrays


logical_and(), logical_or() and logical_not() are useful to get the Boolean array as a

result of comparing the compound condition

Program-3: To understand the usage of logical functions


from numpy import *

a = array([1, 2, 3])
b = array([3, 2, 3])

c = logical_and(a > 0, a < 4)


print(c)
Single Dimensional Arrays
Comparing Arrays


where(): used to create a new array based on whether a given condition is True or False

Syntax: a = where(condition, exp1, exp2)

If condition is True, the exp1 is evaluated, the result is stored in array

a, else exp2 will be evaluated

Program-4: To understand the usage of where function


from numpy import *

a = array([1, 2, 3], int)

c = where(a % 2 == 0, a, 0)
print(c)
Single Dimensional Arrays
Comparing Arrays


where(): used to create a new array based on whether a given condition is True or False

Syntax: a = where(condition, exp1, exp2)

If condition is True, the exp1 is evaluated, the result is stored in array

a, else exp2 will be evaluated

Exercise-1: To retrieve the biggest item after comparing two arrays using where()
Single Dimensional Arrays
Comparing Arrays


nonzero(): used to know the positions of items which are non-zero

Returns an array that contains the indices of the items of the array which
are non-zero

Syntax: a = nonzero(array)

Program-5: To retrieve non zero items from an array

from numpy import *

a = array([1, 2, 0, -1, 0, 6], int)

c = nonzero(a)

#Display the indices


for i in c:
print(i)

#Display the items


print(a[c])
Single Dimensional Arrays
Aliasing Arrays


‘Aliasing means not copying’. Means another name to the existing object

Program-1: To understand the effect of aliasing

from numpy import *

a = arange(1, 6)
b = a
print(a)
print(b)

#Modify 0th Item


b[0] = 99
print(a)
print(b)
Single Dimensional Arrays
Viewing & Copying


view(): To create the duplicate array

Also called as ‘shallow copying’

Program-1: To understand the view()

from numpy import *

a = arange(1, 6)
b = [Link]() #Creates new array
print(a)
print(b)

#Modify 0th Item


b[0] = 99
print(a)
print(b)
Single Dimensional Arrays
Viewing & Copying


copy(): To create the copy the original array

Also called as ‘deep copying’

Program-1: To understand the view()

from numpy import *

a = arange(1, 6)
b = [Link]() #Creates new array
print(a)
print(b)

#Modify 0th Item


b[0] = 99
print(a)
print(b)
Multi Dimensional Arrays
Numpy
Multi Dimensional Arrays
Creating an Array

Example-1: To create an 2D array with 2 rows and 3 cols

a = array([[1, 2, 3],
[4, 5, 6]]

Example-2: To
Example-2: Tocreate
createanan
3Darray
array of float
with 2-2D datatype
arrays with each 2 rows and 3 cols

= array([[[1,
a = array([10.1,2, 20.2,
3],[4,30.3,
5, 6]]40.4, 50.5], float)
[[1, 1, 1], [1, 0, 1]]]
Multi Dimensional Arrays
Attributes of an Array: The ndim
● The ‘ndim’ attribute represents the number of dimensions or axes of an array
● The number of dimensions are also called as ‘rank’

Example-1: To understand the usage of the ndim attribute

a = array([1, 2, 3])

print([Link])

Example-2: To understand the usage of the ndim attribute

a = array([[[1, 2, 3],[4, 5, 6]]


[[1, 1, 1], [1, 0, 1]]]

print([Link])
Multi Dimensional Arrays
Attributes of an Array: The shape
● The ‘shape’ attribute gives the shape of an array
● The shape is a tuple listing the number of elements along each dimensions

Example-1: To understand the usage of the ‘shape’ attribute

a = array([1, 2, 3]) Outputs: (5, )

print([Link])

Example-2: To understand the usage of the ‘shape’ attribute

a = array([[1, 2, 3],[4, 5, 6]]) Outputs: (2, 3)

print([Link])

Example-3: To ‘shape’ attribute also changes the rows and cols

a = array([[1, 2, 3],[4, 5, 6]]) Outputs:

[Link] = (3, 2) [[1 2]


[3 4]
print(a) [5 6]]
Multi Dimensional Arrays
Attributes of an Array: The size
● The ‘size’ attribute gives the total number of items in an array

Example-1: To understand the usage of the ‘size’ attribute

a = array([1, 2, 3]) Outputs: 5

print([Link])

Example-2: To understand the usage of the ‘size’ attribute

a = array([[1, 2, 3],[4, 5, 6]]) Outputs: 6

print([Link])
Multi Dimensional Arrays
Attributes of an Array: The itemsize
● The ‘itemsize’ attribute gives the memory size of an array element in bytes

Example-1: To understand the usage of the ‘itemsize’ attribute

a = array([1, 2, 3, 4, 5]) Outputs: 4

print([Link])

Example-2: To understand the usage of the ‘size’ attribute

a = array([1.1, 2.3]) Outputs: 8

print([Link])
Multi Dimensional Arrays
Attributes of an Array: The dtype
● The ‘dtype’ attribute gives the datatype of the elements in the array

Example-1: To understand the usage of the ‘dtype’ attribute

a = array([1, 2, 3, 4, 5]) Outputs: int32

print([Link])

Example-2: To understand the usage of the ‘dtype’ attribute

a = array([1.1, 2.3]) Outputs: float64

print([Link])
Multi Dimensional Arrays
Attributes of an Array: The nbytes
● The ‘nbytes’ attribute gives the total number of bytes occupied by an array

Example-1: To understand the usage of the ‘nbytes’ attribute

a = array([1, 2, 3, 4, 5]) Outputs: 20

print([Link])

Example-2: To understand the usage of the ‘nbytes’ attribute

a = array([1.1, 2.3]) Outputs: 16

print([Link])
Multi Dimensional Arrays
Methods of an Array: The reshape()
● The ‘reshape’ method is useful to change the shape of an array

Example-1: To understand the usage of the ‘reshape’ method

a = arange(10) Outputs:

#Change the shape as 2 Rows, 5 Cols [[0 1 2 3 4]


a = [Link](2, 5) [5 6 7 8 9]]

print(a)

Example-2: To understand the usage of the ‘reshape’ method

#Change the shape to 5 rows, 2 cols Outputs:


a = [Link](5, 2)
[[0 1]
print(a) [2 3]
[4 5]
[6 7]
[8 9]]
Multi Dimensional Arrays
Methods of an Array: The flatten()
● The ‘flatten’ method is useful to return copy of an array collapsed into ine
dimension

Example-1: To understand the usage of the ‘flatten’ method

#flatten() method Outputs:


a = array([[1, 2], [3, 4]])
print(a) [1 2 3 4]

#Change to 1D array
a = [Link]()
print(a)
Multi Dimensional Arrays
Methods of creating an 2D-Array

● Using array() function


● Using ones() and zeroes() functions
● Uisng eye() function
● Using reshape() function
Multi Dimensional Arrays
Creation of an 2D-Array: array()

Example-1:

a = array([[1, 2], [3, 4]]) Outputs:


print(a)
[[1, 2],
[3, 4]]
Multi Dimensional Arrays
Creation of an 2D-Array: ones() & zeros()

Syntax zeros((r, c), dtype)

ones((r, c), dtype)


Example-1 a = ones((3, 4), float) Produces items

[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]

Example-2 b = zeros((3, 4), int) Produces items

[[0 0 0 0]
[0 0 0 0]
[0 0 0 0]]
Multi Dimensional Arrays
Creation of an 2D-Array: The eye()
● The eye() function creates 2D array and fills the items in the diagonal with 1’s

Syntax eye(n, dtype=datatype)

Description - Creates ‘n’ rows & ‘n’ cols


- Default datatype is float
Example-1 a = eye(3) - Creates 3 rows and 3 cols

[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
Multi Dimensional Arrays
Creation of an 2D-Array: The reshape()
● Used to convert 1D into 2D or nD arrays

Syntax reshape(arrayname, (n, r, c))

Description arrayname – Represents the name of the array whose elements to be


converted
n – Numbers of arrays in the resultant array
r, c – Number of rows & cols respectively

Example-1 a = array([1, 2, 3, 4, 5, 6]) Outputs:

b = reshape(a, (2, 3)) [[1 2 3]


[4 5 6]]
print(b)
Multi Dimensional Arrays
Creation of an 2D-Array: The reshape()
● Used to convert 1D into 2D or nD arrays

Syntax reshape(arrayname, (n, r, c))

Description arrayname – Represents the name of the array whose elements to be


converted
n – Numbers of arrays in the resultant array
r, c – Number of rows & cols respectively

Example-2 a = arange(12) Outputs:

b = reshape(a, (2, 3, 2)) [[0 1]


[2 3]
print(b) [4 5]]

[[6 7]
[8 9]
[10 11]]
Multi Dimensional Arrays
Indexing of an 2D-Array

Program-1: To understand indexing of 2D arrays


from numpy import *

#Create an 2D array with 3 rows, 3 cols


a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

#Display only rows


for i in range(len(a)):
print(a[i])

#display item by item


for i in range(len(a)):
for j in range(len(a[i])):
print(a[i][j], end=' ')
Multi Dimensional Arrays
Slicing of an 2D-Array

#Create an array Produces:


a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
a = reshape(a, (3, 3)) [[1 2 3]
print(a) [4 5 6]
[7 8 9]]

a[:, :] Produces:
a[:]
a[: :] [[1 2 3]
[4 5 6]
[7 8 9]]
#Display 0th row
a[0, :]

#Display 0th col


a[:, 0]

#To get 0th row, 0th col item


a[0:1, 0:1]
Matrices in Numpy
Matrices in Numpy

Syntax matrix-name = matrix(2D Array or String)

Example-1 a = [[1, 2, 3], [4, 5, 6]] Outputs:

a = matrix(a) [[1 2 3]
[4 5 6]]
print(a)

Example-2 a = matrix([[1, 2, 3], [4, 5, 6]]) Outputs:

[[1 2 3]
[4 5 6]]

Example-3 a = ‘1 2; 3 4; 5 6’ [[1 2]
[3 4]
b = matrix(a) [5 6]]
Matrices in Numpy
Getting Diagonal Items

Function diagonal(matrix)

Example-1 #Create 3 x 3 matrix Outputs:


a = matrix("1 2 3; 4 5 6; 7 8 9")
[1 5 9]

#Find the diagonal items


d = diagonal(a)
print(d)
Matrices in Numpy
Finding Max and Min Items

Function max()
min()

Example-1 #Create 3 x 3 matrix Outputs:


a = matrix("1 2 3; 4 5 6; 7 8 9")
9 1

#Print Max + Min Items


big = [Link]()
small = [Link]()
print(big, small)
Matrices in Numpy
Exercise

1. To find sum, average of elements in 2D array

2. To sort the Matrix row wise and column wise

3. To find the transpose of the matrix

4. To accept two matrices and find thier sum

5. To accept two matrices and find their product

Note: Read the matrices from the user and make the program user friendly
THANK YOU
Strings
Team Emertxe
Strings And Characters
Strings And Characters
Creating Strings
Example-1 s = 'Welcome to Python'

Example-2 s = "Welcome to Python"

Example-3 s = """
Welcome to Python
"""

Example-4 s = '''
Welcome to Python
'''

Example-5 s = "Welcome to 'Core' Python"

Example-6 s = 'Welcome to "Core" Python'

Example-7 s = "Welcome to\tCore\nPython"

Example-8 s = r"Welcome to\tCore\nPython"


Strings And Characters
Length of a String
len() Is used to find the length of the string

Example str = "Core Python"

n = len(str)

print("Len: ", n)
Strings And Characters
Indexing the Strings

Both positive and Negative indexing is possible in Python

str = "Core Python"

#Method-1: Access each character using #Method-2: Using for loop


while loop
n = len(str) for i in str:
print(i, end=' ')
i = 0
while i < n:
print(str[i], end=' ')
i += 1

#Method-3: Using slicing operator #Method-4: Using slicing operator

for i in str[::]: #Take sthe step size as -1


print(i, end='') for i in str[: : -1]:
print() print(i, end='')
Strings And Characters
Slicing the Strings
str = "Core Python"

1 str[: :]
Prints all

2 str[0: 9: 1]
Access the string from 0th to 8th element
3 str[0: 9: 2]
Access the string in the step size of 2
4 str[2: 3: 1]
Access the string from 2nd to 3rd Character
5 str[: : 2] Access the entire string in the step size of 2

6 str[: 4: ] Access the string from 0th to 3rd location in steps of 1

7 str[-4: -1: ] Access from str[-4] to str[-2] from left to right

8 str[-6: :] Access from -6 till the end of the string

9 str[-1: -4: -1] When stepsize is negative, then the items are counted from right to
left
10 str[-1: : -1] Retrieve items from str[-1] till the first element from right to left
Strings And Characters
Repeating the Strings

The repetition operator * is used for repeating the strings

Example-1 str = "Core Python"

print(str * 2)

Example-2
print(str[5: 7] * 2)
Strings And Characters
Concatenation of Strings

+ is used as a concatenation operator

Example-1 s1 = "Core"
s2 = "Python"
s3 = s1 + s2
Strings And Characters
Membership Operator

We can check, if a string or a character is a member of another string or not using
'in' or 'not in' operator


'in' or 'not in' makes case sensitive comaprisons

Example-1 str = input("Enter the first string: ")


sub = input("Enter the second string: ")

if sub in str:
print(sub+" is found in main string")
else:
print(sub+" is not found in main string")
Strings And Characters
Removing Spaces

str = " Ram Ravi "

lstrip() #Removes spaces from the left side


print([Link]())
rstrip() #Removes spaces from the right side
print([Link]())

strip() #Removes spaces from the both sides


print([Link]())
Strings And Characters
Finding the Sub-Strings


Methods useful for finding the strings in the main string

- find()

- rfind()

- index()

- rindex()

find(), index() will search for the sub-string from the begining

rfind(), rindex() will search for the sub-string from the end

find(): Returns -1, if sub-string is not found

index(): Returns 'ValueError' if the sub-string is not found
Strings And Characters
Finding the Sub-Strings
Syntax [Link](substring, beg, end)

Example str = input("Enter the main string:")


sub = input("Enter the sub string:")

#Search for the sub-string


n = [Link](sub, 0, len(str))

if n == -1:
print("Sub string not found")
else:
print("Sub string found @: ", n + 1)
Strings And Characters
Finding the Sub-Strings
Syntax [Link](substring, beg, end)

Example str = input("Enter the main string:")


sub = input("Enter the sub string:")

#Search for the sub-string


try:
#Search for the sub-string
n = [Link](sub, 0, len(str))
except ValueError:
print("Sub string not found")
else:
print("Sub string found @: ", n + 1)
Strings And Characters
Finding the Sub-Strings: Exercise

1 To display all positions of a sub-string in a given main string


Strings And Characters
Counting Sub-Strings in a String

count() To count the number of occurrences of a sub-string in a main string

Syntax [Link](substring, beg, end)

Example-1 str = “New Delhi”

n = [Link](‘Delhi’)

Example-2 str = “New Delhi”

n = [Link](‘e’, 0, 3)

Example-3 str = “New Delhi”

n = [Link](‘e’, 0, len(str))
Strings And Characters
Strings are Immutable

Immutable object is an object whose content cannot be changed

Immutable Numbers, Strings, Tuples

Mutable Lists, Sets, Dictionaries

Reasons: Why strings are made immutable in Python

Performance Takes less time to allocate the memory for the Immutable objects, since
their memory size is fixed

Security Any attempt to modify the string will lead to the creation of new object in
memory and hence ID changes which can be tracked easily
Strings And Characters
Strings are Immutable

Immutable object is an object whose content cannot be changed


Example:
one two

s1 = “one”

s2 = “two”
S1 S2

one two

S2 = s1

S1 S2
Strings And Characters
Replacing String with another String

replace() To replace the sub-string with another sub-string

Syntax [Link](old, new)

Example str = "Ram is good boy"

str1 = [Link]("good", "handsome")

print(str1)
Strings And Characters
Splitting And Joining Strings

split() - Used to brake the strings

- Pieces are returned as a list

Syntax [Link](‘character’)

Example str = "one,two,three"

lst = [Link](',')

join() - Groups into one sring

Syntax [Link](str)

- separator: Represents the character to be used between two strings

- str: Represents tuple or list of strings


Example str = ("one", "two", "three")

str1 = "-".join(str)
Strings And Characters
Changing the Case of the Strings

Methods upper()
lower()
swapcase()
title()
str = "Python is the future"

upper() print([Link]()) PYTHON IS THE FUTURE

lower() print([Link]()) python is the future

swapcase() print([Link]()) pYTHON IS THE FUTURE

title() print([Link]()) Python Is The Future


Strings And Characters
Check: Starting & Ending of Strings

Methods startswith()

endswith()

str = "This is a Python"

startswith() print([Link]("This")) True

endswith() print([Link]("This")) False


Strings And Characters
String Testing Methods
isalnum() Returns True, if all characters in the string are alphanumeric(A – Z, a – z, 0
– 9) and there is atleast one character

isalpha() Returns True, if the string has atleast one character and all characters are
alphabets(A - Z, a – z)

isdigit() Returns True if the string contains only numeric digits(0-9) and False
otherwise

islower() Returns True if the string contains at least one letter and all characters are
in lower case; otherwise it returns False

isupper() Returns True if the string contains at least one letter and all characters are
in upper case; otherwise it returns False

istitle() Returns True if each word of the string starts with a capital letter and there
at least one character in the string; otherwise it returns False

isspace() Returns True if the string contains only spaces; otherwise, it returns False
Strings And Characters
Formatting the strings

format() Presenting the string in the clearly understandable manner

Syntax
"format string with replacement fields". format(values)

id = 10
name = "Ram"
sal = 19000.45
print("{}, {}, {}". format(id, name, sal))

print("{}-{}-{}". format(id, name, sal))

print("ID: {0}\tName: {1}\tSal: {2}\n". format(id, name, sal))

print("ID: {2}\tName: {0}\tSal: {1}\n". format(id, name, sal))

print("ID: {two}\tName: {zero}\tSal: {one}\n". format(zero=id, one=name, two=sal))

print("ID: {:d}\tName: {:s}\tSal: {:10.2f}\n". format(id, name, sal))


Strings And Characters
Formatting the strings

format() Presenting the string in the clearly understandable manner

Syntax
"format string with replacement fields". format(values)

n = 5000

print("{:*>15d}". format(num))

print("{:*^15d}". format(num))
Strings And Characters
Exercise
1. To know the type of character entered by the user

2. To sort the strings in alphabetical order

3. To search for the position for a string in agiven group of strings

4. To find the number of words in a given strings

5. To insert the sub-string into a main string in a particular position


THANK YOU
Functions
Team Emertxe
Function vs Method
Function vs Method


A function can be written individually in a Python

Function is called using its name

A function within the class is called “Method”

Method is called in two ways,

[Link]()

[Link]()

Function & Method are same except thier placement and the way they are
called
Defining & Calling a Function
Defining & Calling

Syntax

def function_name(para1, para2, para3,...)


""" docstring """
statements

Example
def sum(a, b):
""" This function finds sum of two numbers """
c = a + b
print('Sum= ', c)

#call the function


sum(10, 15)
Returning Value/s From a Function
Returning a Value

Example Description

return c Returns c from the function

return 100 Returns constant from a


function

return lst Return thelist that contains values

return z, y, z Returns more than one value


Returning a Value

Example
# A function to add two numbers
def sum(a, b):
""" This function finds sum of two numbers """
c = a + b
return c # return result

#call the function


x = sum(10, 15)
print('The Sum is: ', x)

y = sum(1.5, 10.75)
print('The Sum is: ', y)
Returning ‘M’ Values

Example
# A function that returns two results
def sum_sub(a, b):
""" this function returns results of
addition and subtraction of a, b """
c = a + b
d = a - b
return c, d

# get the results from sum_sub() function


x, y = sum_sub(10, 5)

# display the results


print("Result of addition: ", x)
print("Result of subtraction: ", y)
Functions are First Class Objects
Functions
First Class Objects

Functions are considered as first class objects

When function is defined, python interpreter internally creates an Object

Noteworthy:

It is possible to assign a function to a variable

It is possible to define one function inside another function

It is possible to pass a function as parameter to a another function

It is possible that a function can return another function
Pass by Object References
Functions
Pass by Object References

The values are sent to the function by means of Object References

Objects are created on heap memory at run time

Location of the object can be obtained by using id( ) function
Functions
Pass by Object References

Example-1: To pass an integer to a function and modify it
Inside modify()
# passing an integer to a function
function
def modify(x):
""" reassign a value to the variable """
x = 15 x 15
print(x, id(x))

# call mofify() and pass x


x = 10
modify(x)
print(x, id(x))

x 10
Outside the
function

Heap
Functions
Pass by Object References

Example-1: To pass a list to a function and modify it
Inside modify()
# passing an list to a function
function
def modify(lst):
""" to create a new list """
lst 10, 11, 12
lst = [10, 11, 12]
print(lst, id(lst))

# call mofify() and pass lst


lst = [1, 2, 3, 4]
modify(lst)
print(lst, id(lst))

lst 1, 2, 3, 4

Outside the
function

Heap

If altogether a new object inside a function is created, then it will


not be available outside the function
Formal and Actual Arguments
Functions
Formal and Actual Arguments

# A function to add two numbers Formal


def sum(a, b):
""" This function finds sum of two numbers """
c = a + b
return c # return result

#call the function


x = sum(10, 15)
print('The Sum is: ', x)
Actual
y = sum(1.5, 10.75)
print('The Sum is: ', y)
Functions
Formal and Actual Arguments

Types: Actual Arguments

Positional

Keyword

Default

Variable length
Actual Arguments
Positional Arguments

Arguments are passed to a function in correct positional order

# positional arguments demo


def attach(s1, s2):
""" to joins1 and s2 and display total string """
s3 = s1 + s2
print('Total string: ' + s3)

# call attach() and pass 2 strings


attach('New','York') # positional arguments
Actual Arguments
Keyword Arguments

Keyword Arguments are arguments that identify the parameters by their names

# key word arguments demo


def grocery(item, price):
""" to display the given arguments """
print('Item = %s' % item)
print('Price = %.2f' % price)

# call grocerry() and pass two arguments


grocery(item='sugar', price = 50.75) #keyword arguments
grocery(price = 88.00, item = 'oil') #keyword arguments
Actual Arguments
Variable Length Arguments-1


An argument that can accept any number of arguments

Syntax: def function_name(farg, *args)

- farg: Formal argument

- *args: Can take 1 or more arguments

*args will be stored as tuple

# variable length arguments demo


def add(farg, *args): # *args can take 1 or more values
""" to add given numbers """
print('Formal arguments= ', farg)

sum = 0
for i in args:
sum += i
print('Sum of all numbers= ', (farg + sum))

# call add() and pass arguments


add(5, 10)
add(5, 10, 20, 30)
Actual Arguments
Variable Length Arguments-2


An argument that can accept any number of values provided in the format of keys and values

Syntax: def function_name(farg, **kwargs)

- farg: Formal argument

- **kwargs:

- Called as keyword variable

- Internally represents dictionary object

**kwargs will be stored as dictionary

# keyword variable argument demo


def display(farg, **kwargs): # **kwargs can take 0 or more values
""" to add given values """
print('Formal arguments= ', farg)

for x, y in [Link](): # items() will give pair of items


print('key = {}, value = {}'.format(x, y))

# pass 1 formal argument and 2 keyword arguments


display(5, rno = 10)
print()
#pass 1 formal argument and 4 keyword arguments
display(5, rno = 10, name = 'Prakesh')
Local and Global Variables
Local & Global Vars
The Global Keyword


The global variable can be accessed inside the function using the global keyword

- global var

# accesing the global variable from inside a function


a = 1 # this is global variable

def myfunction():

global a # this is global variable

print('global a =', a) # display global variable

a = 2 # modify global variable value

print('modified a =', a) # display new value

myfunction()

print('global a =', a) # display modified value


Local & Global Vars
The Global Keyword


Syntax to get a copy of the global variable inside the function and work on it

- globals()[“global_var_name”]

#same name for global and local variable

a = 1 # this is global variable:

def myfunction():

a = 2 # a is local var

x = globals()['a'] # get global var into x

print('global var a =', x) # display global variable

print('local a =', a) # display new value

myfunction()

print('global a =', a)
Passing Group of Items to a
Function
Passing
The Group Of Items


To pass the group of items to a function, accept them as a list and then pass it.

Example-1
# a function to find total and average
def calculate(lst):
""" to find total and average """
n = len(lst)
sum = 0
for i in lst:
sum += i
avg = sum / n
return sum, avg

# take a group of integers from keyboard


print('Enter numbers seperated by space: ')
lst = [int(x) for x in input().split()]

#call calculate() and pass the list


x, y = calculate(lst)
print('Total: ', x)
print('Average: ', y)
Recursive Function
Recursions


A function calling itself is called as Recursions

Example-1

# resursive function to calculate factorial


def factorial(n):
""" to find factorial of n """
if n == 0:
result = 1
else:
result = n * factorial(n - 1)
return result

# find factorial values for first 10 numbers


for i in range(1, 11):
print('Factorial of {} is {}'.format(i, factorial(i)))
Anonymous Functions Or
Lambdas
Lambdas


A function without name is called ‘Anonymous functions’

Anonymous functions are not defined using the ‘def’ keyword

Defined using the keyword ‘lambda’, hence called as lambda function

Example

Normal Function Anonymous Function


def square(x): f = lambda x: x * x
return x * x
#f = function name
#Calling the function #Calling the function

square(x) value = f(5)


Syntax

lambda argument_list: expression


Lambdas
Example


Example

# lambda function to calculate square value

f = lambda x: x*x # write lambda function

value = f(5) # call lambda func

print('Square of 5 = ', value) # display result


Lambdas
using lambdas with filter()


A filter() is useful to filter out the elements of a sequence depending on the
result of a function

Syntax: filter(function, sequence)

Example
def is_even(x):
if x % 2 == 0:
return True
else:
return False

filter (is_even, lst)

- is_even function acts on every element on the lst


Lambdas
using lambdas with filter()


Example

# a normal function that returns # lambda function that returns even numbers from
# even numbers from a list list
def is_even(x): lst = [10, 23, 45, 46, 70, 99]
if x % 2 == 0: lstl = list(filter(lambda x: (x % 2 == 0), lst))
return True
print(lstl)
else:
return False

# let us take a list of numbers


lst = [10, 23, 45, 46, 70, 99]

# call filter() eith is_even() and list


lstl = list(filter(is_even, lst))
print(lstl)
Lambdas
using lambdas with map()

A map() is similar to filter(), but it acts on each element of the sequence and changes the items

Syntax: map(function, sequence)

Example
Normal Function Lambdas

#map() function that gives squares # lambda that returns squares


def squares(x): lst = [1, 2, 3, 4, 5]
return x * x lstl = list(map(lambda x: x * x, lst))
print(lstl)
#let us take a lis of numbers
lst = [1, 2, 3, 4, 5]

# call map() with square()s and lst


lstl = list(map(squares, lst))
print(lstl)

Writing using the lambdas will be more elegant


Lambdas
using lambdas with reduce()

A reduce() reduces a sequence of elements to a single value by processing the elements according to the
function supplied

Syntax: reduce(function, sequence)

Example
Lambdas
# lambda that returns products of elements of a list
from functools import *
lst = [1, 2, 3, 4, 5]
result = reduce(lambda x, y: x * y, lst)
print(result)

import functools, since reduce() belongs to functools


Lambdas
using lambdas with reduce(): Exercise

Problem
To calculate sum of numbers from 1 to 50 using reduce() & lambda functions

import functools, since reduce() belongs to functools


Function Decorators
Function Decorators


A decorator is a function that accepts a function as parameter and returns a
function

A decorator takes the result of a function, modifies and returns it
Function Decorators
Steps to Create Decorators

STEP-1: Define the decorator
def decor(fun):


STEP-2: Define the function inside the decorator
def decor(fun):
def inner():
value = fun()
return value + 2
return inner

• STEP-3: Define one function


def num():
return 10

• STEP-4: Call the decorator

res = decor(num)
Function Decorators
Complete Program

# a decorator that increments the value of a function by 2


def decor(fun): #this is decorator func
def inner(): #this is inner func that modifies
value = fun()
return value + 2
return inner # return inner function

# take a function to which decorator should be applied


def num():
return 10

#call decorator func and pass me


result_fun = decor(num) # result_fun represents ''inner function
print(result_fun()) # call result_fun and display
Function Decorators
@ decor

To apply the decorator to a function
@decor
def num():
return 10


It means decor() is applied to process or decorate the result of the num() function

No need to call decorator explicitly and pass the function name

@ is useful to call the decorator function internally
Function Decorators
@ decor: Example

# a decorator that increments the value of a function by 2


def decor(fun): #this is decorator func
def inner(): #this is inner func that modifies
value = fun()
return value + 2
return inner # return inner function

# take a function to which decorator should be applied


@decor #apply decor to the below function
def num():
return 10

#call num() function and display its result


print(num())
Function Decorators
@ decor: More than one decorator
# a decorator that increments the value of a # a decorator that doubles the value of a function
function by 2
def decor1(fun): #this is decorator func
def decor(fun): #this is decorator func
def inner(): #Inner func that modifies
def inner(): #inner func that modifies
value = fun()
value = fun()
return value * 2
return value + 2
return inner # return inner function
return inner # return inner function

# take a function to which decorator should be #call num() function and apply decor1 and then
applied decor
print(num())
@decor
@decor1
def num():
return 10

Without using @, decorators can be called


Function Generators
Function Generators


Generator: Function that returns sequence of values

It is written like ordinary function but it uses ‘yield’ statement

# generator that returns sequence from x and y


def mygen(x, y):
while x <= y:
yield x
x += 1

# fill generator object with 5 and 10


g = mygen(5, 10)

# display all numbers in the generator


for i in g:
print(i, end=' ')

To retrieve element by element from a generator object,


use next() function
Creating Our Own Modules in
Python
Creating
Own Modules in Python


A module represents a group of
1. Classes
2. Methods
3. Functions
4. Variables

Modules can be reused

Types:

Built-in: sys, io, time ...

User-defined
Creating
Own Modules in Python: Example
[Link] [Link]
# to calculate dearness allowance from employee import *
def da(basic):
""" da is 80% of basic salary """
da = basic * 80 / 100 # calculate gross salary of employee by taking
return da basic
basic= float(input('Enter basic salary: '))

# to calculate house rent allowance


def hra(basic): # calculate gross salary
""" hra is 15% of basic salary """ gross = basic + da(basic) + hra(basic)
hra = basic * 15 / 100
return hra print('Your gross salary: {:10.2f}'.
format(gross))

# to calculate provident fund amount


def pf(basic): # calculate net salary
""" pf is 12% of basic salary """ net = gross - pf(basic) - itax(gross)
pf = basic * 12 / 100
return pf print('Your net salary: {:10.2f}'. format(net))

# to calculate income tax


def itax(gross):
""" tax is calculated
at 10% on gross """
tax = gross * 0.1
return tax
The Special Variable __name__
The Special Variable
__name__


It is internally created, when program is executed

Stores information regarding whether the program is executed as an individual program or as a
module

When a program is executed directly, it stores __main__

When a program is executed as a module, the python interpreter stores module name
The Special Variable
__name__ : Example-1

#python program to display message. save this as [Link]

def display():

print('Hello Python')

if __name__ == '__main__':

display() # call display func

print('This code is run as a program')

else:

print('This code is run as a module')


The Special Variable
__name__ : Example-2

# in this program [Link] is imported as a module. save this as [Link]

import one

[Link]() # call module one's display function.


THANK YOU
List And Tuples
Team Emertxe
List
List
Introduction

Used for storing different types of data unlike arrays
Example-1 student = [10, "Amar", 'M', 50, 55, 57, 67, 47]

Example-2 e_list = [] #Empty List


Indexing + Slicing can be applied on list

Example-1 print(student[1]) Gives "Amar"

Example-2 print(student[0: 3: 1])


Prints [10, "Amar", 'M']

Example-3 student[::] Print all elements


List
Examples
Example-1 #Create list with integer numbers
num = [10, 20, 30, 40, 50]
print(num)
print("num[0]: %d\tnum[2]: %d\n" % (num[0], num[2]))

Example-2 #Create list with strings


names = ["Ram", "Amar", "Thomas"]
print(names)
print("names[0]: %s\tnames[2]: %s\n" % (names[0], names[2]))

Example-3 #Create list with different dtypes


x = [10, 20, 1.5, 6.7, "Ram", 'M']
print(x)
print("x[0]: %d\tx[2]: %f\tx[4]: %s\tx[5]: %c\n" %(x[0], x[2], x[4], x[5]))
List
Creating list using range()
Example #Create list
num = list(range(4, 9, 2))
print(num)
List
Updating list
1 Creation lst = list(range(1, 5)) [1, 2, 3, 4]
print(lst)

2 append [Link](9) [1, 2, 3, 4, 9]


print(lst)

3 Update-1 lst[1] = 8 [1, 8, 3, 4, 9]


print(lst)

4 Update-2 lst[1: 3] = 10, 11 [1, 10, 11, 4, 9]


print(lst)

5 delete del lst[1] [1, 11, 4, 9]


print(lst)

6 remove [Link](11) [1, 4, 9]


print(lst)

7 reverse [Link]() [9, 4, 1]


print(lst)
List
Concatenation of Two List

'+' operator is used to join two list

Example x = [10, 20, 30]


y = [5, 6, 7]
print(x + y)
List
Repetition of List

'*' is used to repeat the list 'n' times

Example x = [10, 20, 30]

print(x * 2)
List
Membership of List

'in' and 'not in' operators are used to check, whether an element belongs to the list
or not

Example x = [1, 2, 3, 4, 5] Returns True, if the item is found


a = 3 in the list
print(a in x)

Example x = [1, 2, 3, 4, 5] Returns True, if the item is not


a = 7 found in the list
print(a not in x)
List
Aliasing And Cloning Lists

Aliasing: Giving new name for the existing list

Example x = [10, 20, 30, 40]


y = x
Note: No separate memory will be allocated for y

Cloning / Copy: Making a copy

Example x = [10, 20, 30, 40]


y = x[:] <=> y = [Link]()
x[1] = 99
print(x)
print(y)
Note: Changes made in one list will not reflect other
List
Exercise
1. To find the maximum & minimum item in a list of items

2. Implement Bubble sort

3. To know how many times an element occurred in the list

4. To create employee list and search for the particular employee


List
To find the common items
#To find the common item in two lists

l1 = ["Thomas", "Richard", "Purdie", "Chris"]


l2 = ["Ram", "Amar", "Anthony", "Richard"]

#Covert them into sets


s1 = set(l1)
s2 = set(l2)

#Filter intersection of two sets


s3 = [Link](s2)

#Convert back into the list


common = list(s3)

print(common)
List
Nested List
#To create a list with another list as element
list = [10, 20, 30, [80, 90]]
print(list)
List
List Comprehensions

List comprehensions represent creation of new lists from an iterable object(list, set,


tuple, dictionary or range) that satisfies a given condition
Example-1: Create a list with squares of integers from 1 to 10

#Version-1
squares = []
for x in range(1, 11):
[Link](x ** 2)

print(squares)

#Version-2
squares = []
squares = [x ** 2 for x in range(1, 11)]
print(squares)
List
List Comprehensions

List comprehensions represent creation of new lists from an iterable object(list, set,


tuple, dictionary or range) that satisfies a given condition
Example-2: Get squares of integers from 1 to 10 and take only the even numbers from the
result
even_squares = [x ** 2 for x in range(1, 11) if x % 2 == 0]
print(even_squares)
List
List Comprehensions

List comprehensions represent creation of new lists from an iterable object(list, set,


tuple, dictionary or range) that satisfies a given condition
Example-3: #Adding the elements of two list one by one

#Example-1 #Example-2
x = [10, 20, 30] lst = [i + j for i in "ABC" for j in "DE"]
y = [1, 2, 3, 4] print(lst)

lst = []

#Version-1
for i in x:
for j in y:
[Link](i + j)

#Version-2
lst = [i + j for i in x for j in y]
Tuple
Tuple
Introduction

A tuple is similar to list but it is immutable
Tuple
Creating Tuples

To create empty tuple


tup1 = ()

Tuple with one item


tup1 = (10, )

Tuple with different dtypes


tup3 = (10, 20, 1.1, 2.3, "Ram", 'M')

Tuple with no braces


t4 = 10, 20, 30, 40

Create tuple from the list


list = [10, 1.2, "Ram", 'M']
t5 = tuple(list)
Create tuple from range
t6 = tuple(range(4, 10, 2))
Tuple
Accessing Tuples

Accessing items in the tuple can be done by indexing or slicing method, similar to
that of list
Tuple
Basic Operations On Tuples

s = (10, "Ram", 10, 20, 30, 40, 50)


To find the length of the tuple
print(len(s))
Repetition operator
fee = (25.000, ) * 4
print(fee)
Concatenate the tuples using *
ns = s + fee
print(ns)

Membership
name = "Ram"
print(name in s)

Repetition
t1 = (1, 2, 3)
t2 = t1 * 3
print(t2)
Tuple
Functions To Process Tuples

len() len(tpl) Returns the number of elements in the tuple

min() min(tpl) Returns the smallest element in the tuple

max() max() Returns the biggest element in the tuple

count() [Link](x) Returns how many times the element ‘x’ is found in the tuple

index() [Link](x) Returns the first occurrence of the element ‘x’ in tpl.
Raises ValueError if ‘x’ is not found in the tuple

sorted() sorted(tpl) Sorts the elements of the tuple into ascending order.
sorted(tpl, reverse=True) will sort in reverse order
Tuple
Exercise
1. To accept elements in the form of a a tuple and display thier sum and average

2. To find the first occurrence of an element in a tuple

3. To sort a tuple with nested tuples

4. To insert a new item into a tuple at a specified location

5. To modify or replace an existing item of a tuple with new item

6. To delete an element from a particular position in the tuple


THANK YOU
Dictionaries
Team Emertxe
Dictionaries
Introduction
Group of items arranged in the form of key-value pair

Example

d = {"Name": "Ram", "ID": 102, "Salary": 10000}


Program

#Print the entire dictionary


print(d)

#Print only the keys


print("Keys in dic: ", [Link]())

#Print only values


print("Values: ", [Link]())

#Print both keys and value pairs as tuples


print([Link]())
Dictionaries
Operations
d = {"Name": "Ram", "ID": 102, "Salary": 10000}

1. To get the no. of pairs in the Dictionary n = len(d)

2. To modify the existing value d[salary] = 15000

3. To insert new key:value pair d["Dept"] = "Finance"

4. To delete the key:value pair del d["ID"]

5. To check whether the key is present in "Dept" in d


dictionary - Returns True, if it is present
6. We can use any datatype fro values, but keys should obey the rules

R1: Keys should be unique


Ex: emp = {10: "Ram", 20: "Ravi", 10: "Rahim"}
- Old value will be overwritten,
emp = {10: "Rahim", 20: "Ravi"}

R2: Keys should be immutable type. Use numbers, strings or tuples


If mutable keys are used, will get 'TypeError'
Dictionaries
Methods
clear() [Link]() Removes all key-value pairs from the d

copy() d1 = [Link]() Copies all items from ‘d’ into a new dictionary ‘d1’

Create a new dictionary with keys from sequence ‘s’ and


fromkeys() [Link](s, [,v]) values all set to ‘v’

Returns the value associated with key ‘k’.


get() [Link](k, [,v]) If key is not found, it returns ‘v’

Returns an object that contains key-value pairs of ‘d’.


items() [Link]() The pairs are stored as tuples in the object

keys() [Link]() Returns a sequence of keys from the dictionary ‘d’

values() [Link]() Returns a sequence of values from the dictionary ‘d’

update() [Link](x) Adds all elements from dictionary ‘x’ to ‘d’

pop() [Link](k, [,v]) Removes the key ‘k’ and its value.
Dictionaries
Programs
To create the dictionary with employee details

d = {"Name": "Ram", "ID": 1023, "Salary": 10000}

#Print the entire dictionary


print(d)

#Print only the keys


print("Keys in dic: ", [Link]())

#Print only values


print("Values: ", [Link]())

#Print both keys and value pairs as tuples


print([Link]())
Dictionaries
Programs
#To create a dictionary from the keyboard and display the items

x = {}

print("Enter 'n' value: ", end='')


n = int(input())

for i in range(n):
print("Enter the key: ", end='')
k = input()
print("Enter the value: ", end='')
v = int(input())
[Link]({k: v})

print(x)
Dictionaries
Using for loop with Dictionaries

for k in colors:
Method-1 print(k)

for k in colors:
Method-2 print(colors[k])

for k, v in [Link]():
Method-3 print("key = {}\nValue = {}". format(k, v))
Dictionaries
Sorting Dictionaries: Exercise

To sort the elements of a dictionary based on akey or value


Dictionaries
Converting Lists into Dictionary
Two step procedure
- zip()
- dict()

#To convert list into dictionary

countries = ["India", "USA"]


cities = ["New Delhi", "Washington"]

#Make a dictionary
z = zip(countries, cities)
d = dict(z)

print(d)
Dictionaries
Converting strings into dictionary
str = "Ram=23,Ganesh=20"

#Create the empty list


lst = []

for x in [Link](','):
y = [Link]('=')
[Link](y)

#Convert into dictionary


d = dict(lst)

print(d)
Dictionaries
Passing dictionary to function

By specifying the name of the dictionary as the parameter, we can pass the dictionary to the
function.

d = {10: "Ram"}
Example display(d)
Dictionaries
Ordered Dictionaries

from collections import OrderedDict

d = {10: "Ram"}
Example display(d)

Program:
#To create the ordered dictionary
from collections import OrderedDict

#Create empty dictionary


d = OrderedDict()

d[10] = 'A'
d[11] = 'B'
d[12] = 'C'
d[13] = 'D'

print(d)
THANK YOU
Classes And Objects
Team Emertxe
Creation of Class
Creation of Class
General Format

Class is a model or plan to create the objects

Class contains,

Attributes: Represented by variables

Actions : Performed on methods

Syntax of defining the class,

Syntax Example
class Classname(object): class Student:
"""docstrings""" """The below block defines attributes"""
def __init__(self):
Attributes [Link] = "Ram"
[Link] = 21
def __init__(self): [Link] = 89.75
def method1():
def method2(): """The below block defines a method"""
def putdata(self):
print("Name: ", [Link])
print("Age: ", [Link])
print("Marks: ", [Link])
Creation of Class
Program
#To define the Student calss and create an Object to it.

#Class Definition
class Student:
#Special method called constructor
def __init__(self):
[Link] = "Ram"
[Link] = 21
[Link] = 75.90

#This is an instance method


def putdata(self):
print("Name: ", [Link])
print("Age: ", [Link])
print("Marks: ", [Link])

#Create an instance to the student class


s = Student()

#Call the method using an Object


[Link]()
The Self Variable
The Self Variable


‘Self’ is the default variable that contains the memory address of the instance of the
current class

s1 = Student()  s1 contains the memory address of the instance

 This memory address is internally and by default passed to


‘self’ variable
Usage-1:

 The ‘self’ variable is used as first parameter in the


def __init__(self): constructor

Usage-2:  The ‘self’ variable is used as first parameter in the


instance methods
def putdata(self):
Constructor
Constructor
Constructor with NO parameter

Constructors are used to create and initialize the 'Instance Variables'

Example def __init__(self):


[Link] = "Ram"
[Link] = 99


Constructor will be called only once i.e at the time of creating the objects

s = Student()
Constructor
Constructor with parameter

Example def __init__(self, n = "", m = 0):


[Link] = n
[Link] = m
Instance-1 s = Student()

Will initialize the instance variables with default parameters


Instance-2 s = Student("Ram", 99)

Will initialize the instance variables with parameters passed


Constructor
Program
#To create Student class with a constructor having more than one parameter

class Student:
#Constructor definition
def __init__(self, n = "", m = 0):
[Link] = n
[Link] = m

#Instance method
def putdata(self):
print("Name: ", [Link])
print("Marks: ", [Link])

#Constructor called without any parameters


s = Student()
[Link]()

#Constructor called with parameters


s = Student("Ram", 99)
[Link]()
Types of Variables
Types Of Variables


Instance variables

Class / Static variables
Types Of Variables
Instance Variables


Variables whose separate copy is created for every instance/object

These are defined and init using the constructor with 'self' parameter

Accessing the instance variables from outside the class,

[Link]

class Sample: #Create an objects


def __init__(self): s1 = Sample()
s2 = Sample()
self.x = 10
print("s1.x: ", s1.x)
print("s2.x: ", s2.x)
def modify(self):
self.x += 1 [Link]()
print("s1.x: ", s1.x)
print("s2.x: ", s2.x)
Types Of Variables
Class Variables


Single copy is created for all instances

Accessing class vars are possible only by 'class methods'

Accessing class vars from outside the class,

[Link]

class Sample: #Create an objects


#Define class var here s1 = Sample()
s2 = Sample()
x = 10
print("s1.x: ", s1.x)
print("s2.x: ", s2.x)
@classmethod
def modify(cls): [Link]()
print("s1.x: ", s1.x)
cls.x += 1 print("s2.x: ", s2.x)
Namespaces
Namespaces
Introduction

Namespace represents the memory block where names are mapped/linked to objects

Types:

Class namespace

- The names are mapped to class variables

Instance namespace

- The names are mapped to instance variables
Namespaces
Class Namespace
#To understand class namespace Before modifyng class variable ‘n’

#Create the class 10


n
class Student:
Class Namespace
#Create class var
n = 10

#Access class var in class namespace 10 n 10


n
print(Student.n)

Instance Namespace Instance Namespace


#Modify in class namespace
Student.n += 1 After modifyng class variable ‘n’

#Access class var in class namespace


print(Student.n) n 11
Class Namespace
#Access class var in all instances
s1 = Student()
s2 = Student()
11 n 11
n
#Access class var in instance namespace
print("s1.n: ", s1.n) Instance Namespace Instance Namespace

print("s2.n: ", s2.n)

If class vars are modified in class namespace, then it reflects to all instances
Namespaces
Instance Namespace
#To understand class namespace Before modifyng class variable ‘n’

#Create the class 10


n
class Student:
Class Namespace
#Create class var
n = 10

s1 = Student() 10 n 10
n
s2 = Student()

Instance Namespace Instance Namespace


#Modify the class var in instance namespace
s1.n += 1 After modifyng class variable ‘n’

#Access class var in instance namespace


print("s1.n: ", s1.n) n 10
print("s2.n: ", s2.n) Class Namespace

11 n 10
n

Instance Namespace Instance Namespace

If class vars are modified in instance namespace, then it reflects only to


that instance
Types of Methods
Types of Methods


Types:

Instance Methods

- Accessor

- Mutator

Class Methods

Static Methods
Types of Methods
Instance Methods

Acts upon the instance variables of that class

Invoked by instance_name.method_name()

#To understanf the instance methods #Constructor called without any parameters
s = Student()
class Student: [Link]()
#Constructor definition
def __init__(self, n = "", m = 0): #Constructor called with parameters
[Link] = n s = Student("Ram", 99)
[Link] = m [Link]()

#Instance method
def putdata(self):
print("Name: ", [Link])
print("Marks: ", [Link])
Types of Methods
Instance Methods: Accessor + Mutator
Accessor Mutator
● Methods just reads the instance variables, ● Not only reads the data but also modifies
will not modify it it
● Generally written in the form: getXXXX() ● Generally wriiten in the form: setXXXX()
● Also called getter methods ● Also called setter methods

#To understand accessor and mutator #Create an objects


s = Student()
#Create the class
class Student: #Set the name
[Link]("Ram")
#Define mutator
def setName(self, name): #Print the name
[Link] = name print("Name: ", [Link]())

#Define accessor
def getName(self):
return [Link]
Types of Methods
Class Methods
● This methods acts on class level
● Acts on class variables only
● Written using @classmethod decorator
● First param is 'cls', followed by any params
● Accessed by [Link]()

#To understand the class methods

class Bird:
#Define the class var here
wings = 2

#Define the class method


@classmethod
def fly(cls, name):
print("{} flies with {} wings" . format(name, [Link]))

#Call
[Link]("Sparrow")
[Link]("Pigeon")
Types of Methods
Static Methods
● Needed, when the processing is at the class level but we need not involve the class or
instances
● Examples:
- Setting the environmental variables
- Counting the number of instances of the class
● Static methods are written using the decorator @staticmethod
● Static methods are called in the form [Link]()

#To Understand static method #Create 3 objects


s1 = Sample()
class Sample: s2 = Sample()
#Define class vars s3 = Sample()
n = 0
#Class static method
#Define the constructor [Link]()
def __init__(self):
Sample.n = Sample.n + 1

#Define the static method


@staticmethod
def putdata():
print("No. of instances created: ", Sample.n)
Passing Members
Passing Members

● It is possible to pass the members(attributes / methods) of one class to another


● Example:
e = Emp()

● After creating the instance, pass this to another class 'Myclass'


● [Link](e)
- mymethod is static
Passing Members
Example

#To understand how members of one class can be passed to another

#Define the class #Create Object


class Emp: e = Emp("Ram", 20000)
def __init__(self, name, salary):
[Link] = name #Call static method of Myclass and pass e
[Link] = salary [Link](e)

def putdata(self):
print("Name: ", [Link])
print("Salary: ", [Link])

#Define another class


class Myclass:
@staticmethod
def mymethod(e):
[Link] += 1000
[Link]()
Passing Members
Exercise

1. To calculate the power value of a number with the help of a static method
Inner Class
Inner Class
Introduction
● Creating class B inside Class A is called nested class or Inner class
● Example:
Person's Data like,
- Name: Single value
- Age: Single Value
- DoB: Multiple values, hence separate class is needed
Inner Class
Program: Version-1

#To understand inner class #Creating Object


p = Person()
class Person: [Link]()
def __init__(self):
[Link] = "Ram" #Create inner class object
[Link] = [Link]() i = [Link]
[Link]()
def display(self):
print("Name: ", [Link])

#Define an inner class


class Dob:
def __init__(self):
[Link] = 10
[Link] = 2
[Link] = 2002

def display(self):
print("DoB: {}/{}/{}" . format([Link],
[Link], [Link]))
Inner Class
Program: Version-2

#To understand inner class #Creating Object


p = Person()
class Person: [Link]()
def __init__(self):
[Link] = "Ram" #Create inner class object
[Link] = [Link]() i = Person().Dob()
[Link]()
def display(self):
print("Name: ", [Link])

#Define an inner class


class Dob:
def __init__(self):
[Link] = 10
[Link] = 2
[Link] = 2002

def display(self):
print("DoB: {}/{}/{}" . format([Link],
[Link], [Link]))
THANK YOU
Inheritance And
Polymorphism
Team Emertxe
Significance of Inheritance
Significance Of Inheritance

Example-1: [Link]

# A Python program to create Teacher class and store it into [Link] module.

# This is Teacher class. save this code in [Link] file


class Teacher:
def setid(self, id):
[Link] = id

def getid(self):
return [Link]

def setname(self, name):


[Link] = name

def getname(self):
return [Link]

def setaddress(self, address):


[Link] = address

def getaddress(self):
return [Link]

def setsalary(self, salary):


[Link] = salary

def getsalary(self):
return [Link]

When the programmer wants to use this Teacher class that is available in [Link] file,
he can simply import this class into his program and use it
Significance Of Inheritance
Program
# using Teacher class from teacher important Teacher
from teacher import Teacher

# create instance
t = Teacher()

# store data into the instance


[Link](10)
[Link]("Ram")
[Link]('HNO-10, Raj gardens, Delhi')
[Link](25000.50)

# retrive data from instance and display


print('id= ', [Link]())
print('name= ', [Link]())
print('address= ', [Link]())
print('salary= ', [Link]())
Significance Of Inheritance

programmer1

[Link]
programmer2
Significance Of Inheritance

Example-2: [Link]

# A Python program to create sudent class and store it into [Link] module
class Student:
def setid(self, id):
[Link] = id

def getid(self):
return [Link]

def setname(self, name):


[Link] = name

def getname(self):
return [Link]

def setaddress(self, address):


[Link] = address

def getaddress(self):
return [Link]

def setmarks(self, marks):


[Link] = marks

def getmarks(self):
return [Link]

Now, the second programmer who created this Student class and saved it as [Link]
can use it whenever he needs.
Significance Of Inheritance
Program
# using student class from student import student
from student import Student

# create instance
s = Student()

# store data into the instance


[Link](100)
[Link]('Rakesh')
[Link]('HNO-22, Ameerpet, Hyderabad')
[Link](970)

#Print the data


print("ID: ", [Link]())
print("Name: ", [Link]())
print("Address: ", [Link]())
print("Marks: ", [Link]())
Significance Of Inheritance
Comparision
class Teacher: class Student:
def setid(self, id):
def setid(self, id): [Link] = id
[Link] = id
def getid(self):
return [Link]
def getid(self):
def setname(self, name):
return [Link] [Link] = name

def getname(self):
def setname(self, name): return [Link]
[Link] = name
def setaddress(self, address):
[Link] = address
def getname(self):
def getaddress(self):
return [Link] return [Link]
def setmarks(self, marks):
def setaddress(self, address): [Link] = marks
[Link] = address def getmarks(self):
return [Link]
def getaddress(self):
return [Link]

def setsalary(self, salary):


[Link] = salary

def getsalary(self):
return [Link]

By comparing both the codes, we can observe 75% of the code is common
Significance Of Inheritance

from teacher import Teacher # create instance


s = Student()
class Student(Teacher):
def setmarks(self, marks): # store data into the instance
[Link] = marks [Link](100)
[Link]('Rakesh')
def getmarks(self): [Link]('HNO-22, Ameerpet, Hyderabad')
return [Link] [Link](970)

#Print the data


print("ID: ", [Link]())
print("Name: ", [Link]())
print("Address: ", [Link]())
print("Marks: ", [Link]())

Syntax:
class Subclass(Baseclass):
Significance Of Inheritance
Advantages


Smaller and easier to develop

Productivity increases

Copy of Teacher class object


id

name

address
s
salary

setid(), getid()
setname(), getname()
setaddress(), getaddress()
setsalary(), getsalary()

marks

setmarks(), getmarks()

Student class Object


Inheritance
Definition


Deriving the new classes from the existing classes such that the new classes inherit all

the members of the existing classes is called Inheritance


Syntax:

class Subclass(Baseclass):
Constructors in Inheritance
Constructors in Inheritance
Example


Like variables & Methods, the constructors in the super class are also available in the
sub-class

class Father: #Create the instance


def __init__(self): s = Son()
[Link] = 800000.00 s.display_property()

def display_property(self):
print('Father\'s property= ',[Link])

class Son(Father):
pass # we do not want to write anything in the sub class
Overriding Super Class
Constructors and Methods
Overriding super class
Constructors + Methods


Constructor Overriding
- The sub-class constructor is replacing the super class constructor

Method Overriding
- The sub-class method is replacing the super class method

Example
# overriding the base class constructor and method in sub class
class Father:
def __init__(self):
[Link] = 800000.00

def display_property(self):
print('Father\'s property= ', [Link])

class Son(Father):
def __init__(self):
[Link] = 200000.00

def display_property(self):
print('child\'s property= ', [Link])

# create sub class instance and display father's property


s = Son()
s.display_property()
The Super() Method
The super() Method


super() is a built-in method which is useful to call the super class constructor or Methods

Examples
#Call super class constructors
super().__init__()

#Call super class constructors and pass arguments


super().__init__(arguments)

#Call super class method


super().method()
The super() Method
Example

Example-1
# acceessing base class constructor in sub class

class Father:
def __init__(self, property=0):
[Link] = property

def display_property(self):
print('Father\'s property= ', [Link])

class Son(Father):
def __init__(self, property1=0, property=0):
super().__init__(property)
self.property1 = property1

def display_property(self):
print('Total property of child= ', self.property1 + [Link])

# create sub class instance and display father's property

s = Son(200000.00, 800000.00)
s.display_property()
The super() Method
Example
Example-2
# Accessing base class constructor and method in the sub class
class Square:
def __init__(self, x):
self.x = x

def area(self):
print('Area of square= ',self.x * self.x)

class Rectangle(Square):
def __init__(self, x, y):
super().__init__(x)
self.y = y

def area(self):
super().area()
print('Area of rectangle= ',self.x * self.y)

# find areas of square and rectangle


a, b = [float(x) for x in input("Enter two measurements: ").split()]
r = Rectangle(a,b)
[Link]()
Types Of Inheritance
Types of Inheritance
Single

Bank

AndhraBank StateBank

# A Python program showing single inhertiance in which two sub classes are derived from a
single base class.

# single inhertiance class StateBank(Bank):


class Bank(object): cash = 200000000
cash = 100000000
@classmethod
@classmethod def available_cash(cls):
def available_cash(cls): print([Link] + [Link])
print([Link])

class AndhraBank(Bank): a = AndhraBank()


pass a.available_cash()

s = StateBank()
s.available_cash()
Types of Inheritance
Multiple
Father Mother Syntax:

class Subclass(BaseClass1, BaseClass2, ...):

Child

# A Python program to implement multiple inhertiance using two base classes

#multiple inheritance class child(Father, Mother):


class Father: pass
def height(self):
print('Height is 6.0 foot')

class Mother: c = child()


def color(self): print('child\'s inherited qualities: ')
print('color is brown') [Link]()
[Link]()
Multiple Inheritance
Problems in MI

# A Python program to prove that only one class constructor is available to sub class in
multiple inheritance.

# when super classes have constructors

class A(object):
def __init__(self):
self.a = 'a'
print(self.a)

class B(object):
def __init__(self):
self.b = 'b'
print(self.b)

class C(A, B):


def __init__(self):
self.c = 'c'
print(self.c)
super().__init__()

# access the super class instance vars from C


o = C() # o is object of class C
Multiple Inheritance
Solutions

#A Python program to access all the instance variables of both the base classes in
multiple inheritance.

# when super classes have constructors - v2.0

class A(object): Object


def __init__(self):
self.a = 'a'
print(self.a)
super().__init__()

class B(object):
def __init__(self): A B
self.b = 'b'
print(self.b)
super().__init__()

class C(A,B):
def __init__(self):
self.c = 'c' C
print(self.c)
super().__init__()

# access the super class instance vars from C

o = C() # o is object class C


MRO(Method Resolution Operator)
MRO


In Multiple Inheritance, any specified attribute or method is searched first in the current
class. If not found, the search continues into parent classes in depth-first left to right
fasion without searching for the same class twice

1. The first principle is to search for the sub classes before going for its base classes.

Thus if class B is inherited from A, it will search B first and then goes to A

2. The second principle is that when a class is inherited from several classes, it searches
in the order from left to right in the base class.

Example: class C(A, B), then first it will search in A and then in B

3. The third principle is that it will not visit any class more than once. That means a class
in the inheritance hierarchy is traversed only once exactly
MRO

Object

A B C

X Y

P
MRO
Program

# A Python program to understand the order of execution of methods in several base classes
according to MRO.

class A(object):
def method(self):
print('A class method')
super().method()

class B(object):
def method(self):
print('B class method')
super().method()
class C(object):
def method(self):
print('C class method')

class X(A, B):


def method(self):
print('X class method')
super().method()
class Y(A, B):
def method(self):
print('Y class method')
super().method()

class P(X,Y,C):
def method(self):
print('P class method')
super().method()

P = P()
[Link]()

[Link](): Returns sequence of execution of classes


Polymorphism
Polymorphism
Polymorphism
Introduction


Variable, Object or Method exhibits different behavior in different contexts called

Polymorphism

Python has built-in Polymorphism
Polymorphism
Duck Typing Philosophy


Datatype of the variables is not explicitly declared

type(): To check the type of variable or object

x = 5 <class ‘int’>
print(type(x))
Example-1

Example-2 x = “Hello” <class ‘str’>


print(type(x))

Conclusion

1. Python’s type system is strong because every variable or object has a type that we can
check with the type() function

2. Python’s type system is ‘dynamic’ since the type of a variable is not explicitly declared,
but it changes with the content being stored
Polymorphism
Duck Typing Philosophy: Program

# A Python program to invoke a method on an object without knowing the type (or class) of
the object.
# duck typing example

# Duck class contains talk() method


class Duck:
def talk(self):
print('Quack, quack!')

#Human class contains talk() method


class Human:
def talk(self):
print('Hello, hi!')

# this method accepts an object and calls talk() method


def call_talk(obj):
[Link]()

# call call_talk() method pass an object


# depending on type of object, talk() method is executed
x = Duck()

call_talk(x)
x = Human()
call_talk(x)

During runtime, if it is found that method does not belong to that object,
there will be an error called ‘AttributeError’
Polymorphism
Attribute Error: Overcoming

# this method accepts an object and calls talk() method


def call_talk(obj):
if hasattr(obj, 'talk'):
[Link]()
elif hasattr(obj, 'bark'):
[Link]()
else:
print('Wrong object passed...')

During runtime, if it is found that method does not belong to that object,
there will be an error called ‘AttributeError’
Operator Overloading
Operator Overloading
Example-1

# A Python program to use addition operator to act on different types of objects.


# overloading the + operator
# using + on integers to add them
print(10+15)

#using + on strings to concatenate them


s1 = "Red"
s2 = "Fort"
print(s1+s2)

#using + on lists to make a single list


a = [10, 20, 30]
b = [5, 15, -10]
print(a+b)

‘+’ operator is overloaded and thus exhibits polymorphism


Operator Overloading
Example-2

# Error #Correction
# using + operator on objects # overloading + operator to act on objects

class BookX: class BookX:


def __init__(self, pages): def __init__(self, pages):
[Link] = pages [Link] = pages

class BookY: def __add__(self, other):


def __init__(self, pages): return [Link]+[Link]
[Link] = pages
class BookY:
b1 = BookX(100) def __init__(self, pages):
b2 = BookY(150) [Link] = pages
print('Total pages = ', b1 + b2)
b1 = BookX(100)
b2 = BookY(150)
print('Total pages= ', b1+b2)

def __add__(self, other):


Operator Overloading
Example-3

#A Python program to overload greater than (>) operator to make it act on class objects.
# overloading > operator
class Ramayan:
def __init__(self, pages):
[Link] = pages

def __gt__(self, other):


return [Link] > [Link]

class Mahabharat:
def __init__(self, pages):
[Link] = pages

b1 = Ramayan(1000)
b2 = Mahabharat(1500)

if(b1 > b2):


print('Ramayan has more pages')
else:
print('Mahabharat has more pages')

def __gt__(self, other):


Method Overloading
Operator Overloading
Example-1

# A Python program to show method overloading to find sum of two or three numbers.
# method overloading
class Myclass:
def sum(self, a=None, b=None, c=None):
if a!=None and b!=None and c!=None:
print('Sum of three= ', a + b + c)
elif a!=None and b!=None:
print('Sum of two= ', a + b)
else:
print('Please enter two or three arguments')

# call sum() using object


m = Myclass()
[Link](10, 15, 20)
[Link](10.5, 25.55)
[Link](100)

If a method is written such that it can perform more than one task, it is
called method overloading
Method Overriding
Operator Overriding
Example-1

# A Python program to override the super class method in sub class.


# method overriding
import math
class Square:
def area(self, x):
print('Square area= %.4f' % (x * x))

class Circle(Square):
def area(self, x):
print('Circle area= %.4f' % ([Link] *x * x))

# call area() using sub class object


c = Circle()
[Link](15)

If a method written in sub class overrides the same method in super class,
then it is called method overriding

Method overriding already discussed in Constructor & Method Overridings


THANK YOU
Abstract Classes And
Interfaces
Team Emertxe
Introduction
Introduction

Example:

To understand that Myclass method is shared by all objects


class Myclass: #All objects share same calculate() method
def calculate(self, x): obj1 = Myclass()
print("Square: ", x * x)
[Link](2)

obj2 = Myclass()
[Link](3)

obj3 = Myclass()
[Link](4)
Question


What If?

Object-1 wants to calculate square value

Object-2 wants to calculate square root

Object-3 wants to calculate Cube
Solution-1


Define, three methods in the same class

calculate_square()

calculate_sqrt()

calculate_cube()

Disadvantage:

All three methods are available to all the objects which is not advisable
Solution-2

Myclass
calculate(x):
no body

calculate(x): calculate(x): calculate(x):


square of x sqrt of x cube of x
Sub1 Sub2 Sub3

Obj1 Obj2 Obj3


Abstract Method and Class
Abstract Method & Class


Abstract Method

- Is the method whose action is redefined in sub classes as per the requirements

of the objects

- Use decorator @abstractmethod to mark it as abstract method

- Are written without body


Abstract Class

- Is a class generally contains some abstract methods

- PVM cannot create objects to abstract class, since memory needed will not be

known in advance

- Since all abstract classes should be derived from the meta class ABC which belongs to
abc(abstract base class) module, we need to import this module


- To import abstract class, use

- from abc import ABC, abstractmethod

OR

- from abc import *
Program-1

#To create abstract class and sub classes which implement the abstract method of the
abstract class
from abc import ABC, abstractmethod

class Myclass(ABC):
@abstractmethod
def calculate(self, x):
pass

#Sub class-1 Obj1 = Sub1()


class Sub1(Myclass): [Link](2)
def calculate(self, x):
print("Square: ", x * x) Obj2 = Sub2()
[Link](16)

#Sub class-2 Obj3 = Sub3()


import math [Link](3)
class Sub2(Myclass):
def calculate(self, x):
print("Square root: ", [Link](x))

#Sub class-3
class Sub3(Myclass):
def calculate(self, x):
print("Cube: ", x * x * x)
Example-2

Maruthi, Santro, Benz are all objects of class Car

Registration no. - All cars will have reg. no.

- Create var for it

Fuel Tank - All cars will have common fule tank

- Action: Open, Fill, Close

Steering - All cars will not have common steering


say, Maruthi uses- Manual steering
Santro uses - Power steering
- So define this as an Abstract Method

Brakes - Maruthi uses hydraulic brakes


- Santro uses gas brakes
- So define this as an Abstract Method
Program-2

#Define an absract class #Define the Maruthi class

from abc import * from abstract import Car

class Car(ABC): class Maruthi(Car):


def __init__(self, reg_no): def steering(self):
self.reg_no = reg_no print("Maruthi uses Manual steering")

def opentank(self): def braking(self):


print("Fill the fuel for car with reg_no: ", print("Maruthi uses hydraulic braking system")
self.reg_no)

#Create the objects


@abstractmethod
Obj = Maruthi(123)
def steering(self):
[Link]()
pass
[Link]()
[Link]()
@abstractmethod
def braking(self):
pass
Interfaces
Interfaces


Abstract classes contains both,

- Abstract methods

- Concrete Methods


Interfaces is also an Abstract class, but contains only

- Abstract methods

Plus point of Interface.

- Every sub-class may provide its own implementation for the abstract methods
Interfaces
Program-1
from abc import *

class Myclass(ABC): #Define Database


@abstractmethod class Database:
def connect(self):
pass str = input("Enter the database name: ")

@abstractmethod #Covert the string into the class name


def disconnect(self): classname = globals()[str]
pass
#create an object
x = classname()
#Sub-Class:1
class Oracle(Myclass): #Call methods
def connect(self): [Link]()
print("Connecting to oracle database...") [Link]()

def disconnect(self):
print("Disconnecting from oracle
database...")

#Sub-Class:2
class Sybase(Myclass):
def connect(self):
print("Connecting to sybase database...")

def disconnect(self):
print("Disconnecting from sybase
database...")
Interfaces
Program-2
from abc import *

class Myclass(ABC): #Define Printer


@abstractmethod class Printer:
def putdata(self, text):
str = input("Enter the printer name: ")
pass
#Covert the string into the class name
@abstractmethod classname = globals()[str]
def disconnect(self):
pass #create an object
x = classname()

#Call methods
#Sub-Class:1 [Link]("Sending to printer")
class IBM(Myclass): [Link]()
def putdata(self, text):
print(text)

def disconnect(self):
print("Disconnecting from IBM printer...")

#Sub-Class:2
class Epson(Myclass):
def putdata(self, text):
print(text)

def disconnect(self):
print("Disconnecting from Epson printer...")
THANK YOU
Exceptions
Team Emertxe
Introduction
Errors


Categories of Errors

Compile-time

Runtime

Logical
Errors
Compile-Time

What? These are syntactical errors found in the code, due to which program
fails to compile

Example Missing a colon in the statements llike if, while, for, def etc

Program Output

x = 1 py 1.0_compile_time_error.py
File "1.0_compile_time_error.py", line 5
if x == 1 if x == 1
print("Colon missing") ^
SyntaxError: invalid syntax

x = 1 py 1.1_compile_time_error.py
File "1.1_compile_time_error.py", line 8
#Indentation Error print("Hello")
if x == 1: ^
print("Hai") IndentationError: unexpected indent
print("Hello")
Errors
Runtime - 1

What? When PVM cannot execute the byte code, it flags runtime error

Example Insufficient memory to store something or inability of the PVM to


execute some statement come under runtime errors

Program Output
def combine(a, b): py 2.0_runtime_errors.py
print(a + b)
Traceback (most recent call last):
#Call the combine function File "2.0_runtime_errors.py", line 7, in <module>
combine("Hai", 25)
combine("Hai", 25)
File "2.0_runtime_errors.py", line 4, in combine
print(a + b)
TypeError: can only concatenate str (not "int") to str

"""
Conclusion:

1. Compiler will not check the datatypes.


[Link] checking is done by PVM during run-time.
"""
Errors
Runtime - 2

What? When PVM cannot execute the byte code, it flags runtime error

Example Insufficient memory to store something or inability of the PVM to


execute some statement come under runtime errors

Program Output
#Accessing the item beyond the array py 2.1_runtime_errors.py
bounds
Traceback (most recent call last):
lst = ["A", "B", "C"] File "2.1_runtime_errors.py", line 5, in <module>
print(lst[3])
print(lst[3])
IndexError: list index out of range
Errors
Logical-1

What? These errors depicts flaws in the logic of the program

Example Usage of wrong formulas

Program Output
def increment(sal): py 3.0_logical_errors.py
sal = sal * 15 / 100 New Salary: 750.00
return sal

#Call the increment()


sal = increment(5000.00)
print("New Salary: %.2f" % sal)
Errors
Logical-2

What? These errors depicts flaws in the logic of the program

Example Usage of wrong formulas

Program Output
#1. Open the file py 4_effect_of_exception.py
f = open("myfile", "w")
Enter two number: 10 0

Traceback (most recent call last):


#Accept a, b, store the result of a/b into the file
a, b = [int(x) for x in input("Enter two number: ").split()] File "4_effect_of_exception.py", line 8, in
<module>
c = a / b
c = a / b
#Write the result into the file ZeroDivisionError: division by zero
[Link]("Writing %d into myfile" % c)

#Close the file


[Link]()
print("File closed")
Errors
Common


When there is an error in a program, due to its sudden termination, the following things
can be suspected


The important data in the files or databases used in the program may be lost


The software may be corrupted


The program abruptly terminates giving error message to the user making the user
losing trust in the software
Exceptions
Introduction

An exception is a runtime error which can be handled by the programmer

The programmer can guess an error and he can do something to eliminate the harm caused by
that error called an ‘Exception’
BaseException

Exception

StandardError Warning

ArthmeticError DeprecationWarning

RuntimeWarning
AssertionError
ImportantWarning
SyntaxError

TypeError

EOFError

RuntimeError

ImportError

NameError
Exceptions
Exception Handling

The purpose of handling errors is to make program robust

Step-1 try: #To handle the ZeroDivisionError Exception


statements try:
f = open("myfile", "w")
a, b = [int(x) for x in input("Enter two numbers: ").split()]
c = a / b
[Link]("Writing %d into myfile" % c)

Step-2 except exeptionname: except ZeroDivisionError:


statements print("Divide by Zero Error")
print("Don't enter zero as input")

Step-3 finally: finally:


statements [Link]()
print("Myfile closed")
Exceptions
Program

#To handle the ZeroDivisionError Exception

#An Exception handling Example Output:


try:
f = open("myfile", "w") py 5_exception_handling.py
a, b = [int(x) for x in input("Enter two numbers: ").split()] Enter two numbers: 10 0
c = a / b Divide by Zero Error
[Link]("Writing %d into myfile" % c) Don't enter zero as input
Myfile closed
except ZeroDivisionError:
print("Divide by Zero Error")
print("Don't enter zero as input")

finally:
[Link]()
print("Myfile closed")
Exceptions
Exception Handling Syntax

try:
statements

except Exception1:
handler1

except Exception2:
handler2

else:
statements

finally:
statements
Exceptions
Exception Handling: Noteworthy
- A single try block can contain several except blocks.

- Multiple except blocks can be used to handle multiple exceptions.

- We cannot have except block without the try block.

- We can write try block without any except block.

- Else and finally are not compulsory.

- When there is no exception, else block is executed after the try block.

- Finally block is always executed.


Exceptions
Types: Program-1

#To handle the syntax error given by eval() function

#Example for Synatx error Output:


try:
Run-1:
date = eval(input("Enter the date: "))
Enter the date: 5, 12, 2018
except SyntaxError: You entered: (5, 12, 2018)
print("Invalid Date")
Run-2:
else:
Enter the date: 5d, 12m, 2018y
print("You entered: ", date)
Invalid Date
Exceptions
Types: Program-2

#To handle the IOError by open() function

#Example for IOError

try:
name = input("Enter the filename: ")
f = open(name, "r")

except IOError:
print("File not found: ", name)

else:
n = len([Link]())
print(name, "has", n, "Lines")
[Link]()

If the entered file is not exists, it will raise an IOError


Exceptions
Types: Program-3

#Example for two exceptions

#A function to find the total and average of list elements Output:


def avg(list): Run-1:
tot = 0 Type Error: Pls provide the numbers
for x in list:
Run-2:
tot += x
avg = tot / len(list) ZeroDivisionError, Pls do not give empty list
return [Link]

#Call avg() and pass the list


try:
t, a = avg([1, 2, 3, 4, 5, 'a'])
#t, a = avg([]) #Will give ZeroDivisionError
print("Total = {}, Average = {}". format(t, a))

except TypeError:
print("Type Error: Pls provide the numbers")

except ZeroDivisionError:
print("ZeroDivisionError, Pls do not give empty list")
Exceptions
Except Block: Various formats

Format-1 except Exceptionclass:

Format-2 except Exceptionclass as obj:

Format-3 except (Exceptionclass1, Exceptionclass2, ...):

Format-4 except:
Exceptions
Types: Program-3A

#Example for two exceptions

#A function to find the total and average of list elements Output:


def avg(list): Run-1:
tot = 0 Type Error / ZeroDivisionError
for x in list:
Run-2:
tot += x
avg = tot / len(list) Type Error / ZeroDivisionError
return [Link]

#Call avg() and pass the list


try:
t, a = avg([1, 2, 3, 4, 5, 'a'])
#t, a = avg([]) #Will give ZeroDivisionError
print("Total = {}, Average = {}". format(t, a))

except (TypeError, ZeroDivisionError):


print("Type Error / ZeroDivisionError”)
Exceptions
The assert Statement


It is useful to ensure that a given condition is True, It is not True, it raises

AssertionError.


Syntax:

assert condition, message


Exceptions
The assert Statement: Programs

Program - 1 Program - 2

#Handling AssertionError #Handling AssertionError

try: try:

x = int(input("Enter the number between 5 and 10: ")) x = int(input("Enter the number between 5 and 10: "))

assert x >= 5 and x <= 10 assert x >= 5 and x <= 10, "Your input is INVALID"

print("The number entered: ", x) print("The number entered: ", x)

except AssertionError: except AssertionError as Obj:

print("The condition is not fulfilled") print(Obj)


Exceptions
User-Defined Exceptions

Step-1 class MyException(Exception):


def __init__(self, arg):
[Link] = arg

Step-2 raise MyException("Message")

Step-3 try:
#code
except MyException as me:
print(me)
Exceptions
User-Defined Exceptions: Program

#To create our own exceptions and raise it when needed


class MyException(Exception):
def __init__(self, arg):
[Link] = arg

def check(dict):
for k, v in [Link]():
print("Name = {:15s} Balance = {:10.2f}" . format(k, v)) if (v < 2000.00):
raise MyException("Less Bal Amount" + k)

bank = {"Raj": 5000.00, "Vani": 8900.50, "Ajay": 1990.00}

try:
check(bank)
except MyException as me:
print(me)
THANK YOU
Files
Team Emertxe
Introduction
Introduction


A file is an object on a computer that stores data, information, settings, or commands used
with a computer program

Advantages of files

- Data is stored permanently

- Updation becomes easy

- Data can be shared among various programs

- Huge amount of data can be stored
Files
Types

Text Binary

Stores the data in the form of strings Stores data in the form of bytes

Example: Example:

“Ram” is stored as 3 characters “Ram” is stored as 3 bytes


890.45 is stored as 6 characters 89000.45 is stored as 8 bytes
Examples: Examples:

.txt, .c, .cpp .jpg, .gif or .png


Files
Opening a file
Name open()
Syntax file_handler = open("file_name", "open_mode", "buffering")

filename : Name of the file to be opened


open_mode: Purpose of opening the file
buffering: Used to stored the data temporarily
Opening Modes
w - To write the data
- If file already exist, the data will be lost
r - To read the data
- The file pointer is positioned at the begining of the file
a - To append data to the file
- The file pointer is placed at the end of the file
w+ - To write and read data
- The previous data will be deleted
r+ - To read and write
- The previous data will not be deleted
- The file pointer is placed at the begining of the file
a+ - To append and read data
- The file pointer will be at the end of the file
x - To open the file in exclusive creation mode
- The file creation fails, if already file exist
Example

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

Here, buffer is optional, if omitted 4096 / 8192 bytes will be considered.


Files
Closing a file
Name close()
Syntax [Link]()
Example #Open the file
f = open("[Link]", "w")

#Read the string


str = input("Enter the string: ")

#Write the string into the file


[Link](str)

#Close the file


[Link]()
Files
Working with text files containing strings
To read the content from files,
[Link]() : Reads all lines, displays line by line
[Link]() : Displays all strings as elements in a list
[Link]().splitlines(): To suppress the "\n" in the list

Program

#To create a text file to store strings

#Open the file


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

#Read the data from a file


str = [Link]() #Reads all data

#Display the data


print(str)

#Close the file


[Link]()

Note:

"""
[Link](n): Will read 'n' bytes from the file
"""
Files
Working with text files containing strings
[Link](offset, fromwhere)
- offset : No. of bytes to move
- fromwhere : Begining, Current, End
- Example : [Link](10, 0), move file handler from Beg forward 10 bytes.

# Appending and then reading strings, Open the file for reading data
f = open('[Link]', 'a+')

print('Enter text to append(@ at end): ')


while str != '@':
str = input() # accept string into str

# Write the string into file


if (str != '@'):
[Link](str+"\n")

# Put the file pointer to the beginning of the file


[Link](0,0)

# Read strings from the file


print('The file cotents are: ')
str = [Link]()
print(str)

# Closing the file


[Link]()
Files
Knowing If file exists or not
Sample:
if [Link](fname):
f = open(fname, "r")
else:
print(fname + "Does not exist")
[Link]() #Terminate the program
# Checking if file exists and then reading data
import os, sys

# open the file for reading data


fname = input('Enter filename : ')

if [Link](fname):
f = open(fname, 'r')
else:
print(fname+' does not exist')
[Link]()

# Read strings from the file


print('The file contents are: ')
str = [Link]()
print(str)

# Closing the file


[Link]()
Files
Exercise
Problem- 1

To count number of lines, words and characters in a text file


Problem- 2

To copy an image from one file to another


Files
The with statement
1. Can be used while opening the file

2. It will take care of closing the file, without using close() explicitly

3. Syntax: with open("file_name", "openmode") as fileObj:


Program -1

# With statement to open a file


with open('[Link]', 'w') as f:
[Link]('I am a learner\n')
[Link]('Python is attactive\n')

Program -2

# Using with statement to open a file


with open('[Link]', 'r') as f:
for line in f:
print(line)
Files
The pickle + Unpickle
1. To store the data of different types, we need to create the class for it.

2. Pickle/Serialization:
- Storing Object into a binary file in the form of bytes.
- Done by a method dump() of pickle module
- [Link](object, file)

3. Unpickle/Deserialization
- Process where byte stream is converted back into the object.
- Object = [Link](file)
Files
The pickle: Program
# A python program to create an Emp class witg employee details as instance variables.
# Emp class - save this as [Link]
class Emp:
def_init_(self, id, name, sal):
[Link] = id
[Link] = name
[Link] = sal
def display(self):
print("{:5d} {:20s} {:10.2f}".format([Link], [Link],[Link]))

# pickle - store Emp class object into [Link] file


import Emp, pickle
# Open [Link] file as a binary file for writing
f = open('[Link]', 'wb')
n = int(input('How many employees? '))
for i in range(n):
id = int(input('Enter id: '))
name = input('Enter name: ')
sal = float(input('Enter salary: '))
for i in range(n):
id = int(input('Enter id: '))
name = input('Enter name: ')
sal = float(input('Enter salary: '))
# Create Emp class object
e = [Link](id, name, sal)
# Store the object e into the file f
[Link](e, f)
#close the file
[Link]()
Files
The unpickle: Program
# A python program to create an Emp class witg employee details as instance variables.
# Emp class - save this as [Link]
class Emp:
def_init_(self, id, name, sal):
[Link] = id
[Link] = name
[Link] = sal

def display(self):
print("{:5d} {:20s} {:10.2f}".format([Link], [Link],[Link]))

# unpickle or object de-serialization


import Emp, pickle

# Open the file to read objects


f = open('[Link]', 'rb')

print('Employees details: ')


while True:
try:
#Read object from file f
obj = [Link](f)
# Display the contents of employee obj
[Link]()

except EOFError:
print('End of file reached....')
break

#Close the file


[Link]()
Random Binary File Access
using mmap
1. Using mmap, binary data can be viewed as strings
mm = [Link]([Link](), 0)

2. Reading the data using read() and readline()


print([Link]())
print([Link]())

3. We can also retrieve the data using teh slicing operator


print(mm[5: ])
print(mm[5: 10])

4. To modify / replace the data


mm[5: 10] = str

5. To find the first occurrance of the string in the file


n = [Link](name)

6. To convert name from string to binary string


name = [Link]()

7. To convert bytes into a string


ph = [Link]()

Demonstrate the code


Zip & Unzip


Zip:

- The file contents are compressed and hence the size will be reduced

- The format of data will be changed making it unreadable

Zipping

Compressed
Original
File
File

Unzipping
Zip & Unzip
Programs

# Zipping the contents of files # A Python program to unzip the contents of the files
from zipfile import * # that are available in a zip file.

# create zip file # To view contents of zipped files


f = zipfile('[Link]', 'w', 'ZIP_DEFLATED') from zipfile import*

# add some files. these are zipped # open the zip file
[Link]('[Link]') z = Zipfile('[Link]', 'r')
[Link]('[Link]')
[Link]('[Link]') # Extract all the file names which are int he zip file
[Link]()
# close the zip file
print('[Link] file created....')
[Link]()
Working With Directories
Program-1

# A Python program to know the currently working directory.

import os

# get current working directory


current = [Link]()

print('Current sirectory= ', current)


Working With Directories
Program-2

# A Python program to create a sub directory and then sub-sun directory in the current
directory.

import os
# create a sub directory by the name mysub
[Link]('mysub')

# create a sub-sub directory by the same mysub2


[Link]('mysub/mysub2')
Working With Directories
Program-3

# A Python program to use the makedirs() function to create sub and sub-sub directories.

import os

# create sub and sub-sub directories


[Link]('newsub/newsub2')
Working With Directories
Program-4

# A Python program to remove a sub directory that is inside another directory.

import os
# to remove newsub2 directory
[Link]('newsub/newsub2')
Working With Directories
Program-5

# A Python program to remove a group of directories in the path

import os
# to remove mysub3, mysub2 and then mysub.
[Link]('mysub/mysub2/mysub3')
Working With Directories
Program-6

# A Python program to rename a directory.

import os
# to rename enum as newenum
[Link]('enum', 'newenum')
Working With Directories
Program-7

# A Python program to display all contents of the current directory.

import os
for dirpath, dirnames, filenames in [Link]('.'):
print('Current path: ', dirpath)
print('Directories: ', dirnames)
print('Files: ', filenames)
print()
Running other programs
Program-7

The OS module has the system() method that is useful to run an executableprogram from our

Python program

[Link](‘dir’) Display contents of current working DIR

Example-1

Example-2 [Link](‘python [Link]’) Runs the [Link] code


THANK YOU
Regular Expressions
Team Emertxe
Regular Expressions
Regular Expressions
Introduction

 RE is a string that contains special symbols and characters to find and extract the information
 Operations:

Search

Match

Find

Split
 Also called as regex
 Module: re

This module contains the methods like

compile()

search()

match()

findall()

split()...

import re
Regular Expressions
Steps

 Step-1: Compile the RE


prog = [Link](r’m\w\w’)

 Step-2: Search the strings

str = “cat mat bat rat”

result = [Link](str)

 Step-3: Display the result

print([Link]())
Regular Expressions
Example-1: search()

import re
str = 'man sun mop run'
result = [Link](r'm\w\w', str)
if result: #if result is not None
print([Link]())

import re
str = 'man sun mop run'
prog = [Link](r'm\w\w')
result = [Link](str)
if result: #if result is not None
print([Link]())

search(): Combination of compile and run

- Point: Returns only the first string matching the RE


Regular Expressions
Example-2: findall()

import re
str = 'man sun mop run'
result = [Link](r'm\w\w', str)
print(result)

findall()
- Returns all the matching strings
- Returns in the form of the list
Regular Expressions
Example-3: match()

import re
str = 'man sun mop run'
result = [Link](r'm\w\w', str)
print([Link]())

match()
- Returns the string only if it is found in the begining of the string
- Returns None, if the string is not found
Regular Expressions
Example-4: match()

import re
str = 'sun man mop run'
result = [Link](r'm\w\w', str)
print(result)

match()
- Returns None, since the string is not found
Regular Expressions
Example-5: split()

import re
str = 'This; is the: "Core" Python\'s Lecturer'
result = [Link](r'\w+', str)
print(result)


split() - splits the RE

W : Split at non-alphanumeric character

+ : Match 1 or more occurrences of characters

split()
- splits the string into pieces according to the given RE
Regular Expressions
Example-6: Find & Replace: sub()

import re
str = 'Kumbhmela will be conducted at Ahmedabad in India.'
res = [Link](r'Ahmedabad', 'Allahabad', str)
print(res)

Syntax:
sub(RE, new, old)
RE: Sequence Characters
RE: sequence characters


Match only one character in the string

Character Description

\d Represents any digit(0 - 9)

\D Represents any non-digit

\s Represents white space Ex: \t\n\r\f\v

\S Represents non-white space character

\w Represents any alphanumeric(A-Z, a-z, 0-9)

\W Represents non-alphanumeric\b

\b Represents a space around words

\A Matches only at start of the string

\Z Matches only at end of the string


RE: sequence characters
Example-1:

To match all words starting with ‘a’

import re
str = 'an apple a day keeps the doctor away'
result = [Link](r'a[\w]*', str)

# findall() returns a list, retrieve the elements from list


for word in result:
print(word)
To match all words starting with ‘a’, not sub-words then RE will look like this

import re
str = 'an apple a day keeps the doctor away'
result = [Link](r'\ba[\w]*\b', str)

# findall() returns a list, retrieve the elements from list


for word in result:
print(word)

* Matches with 0 or more occurrences of the character


RE: sequence characters
Example-2:

To match all words starting with numeric digits

import re

str = 'The meeting will be conducted on 1st and 21st of every month'

result = [Link](r'\d[\w]*', str)

#for word in result:

print(word)

* Matches with 0 or more occurrences of the character


RE: sequence characters
Example-3:

To retrieve all words having 5 characters

import re

str = 'one two three four five six seven 8 9 10'

result = [Link](r'\b\w{5}\b', str)

print(result)
character Description

\b Matches only one space

\w Matches any alpha numeric character

{5} Repetition character


RE: sequence characters
Example-4: search()

To retrieve all words having 5 characters using search()

# search() will give the first matching word only.

import re

str = 'one two three four five six seven 8 9 10'

result = [Link](r'\b\w{5}', str)

print([Link]())
character Description

\b Matches only one space

\w Matches any alpha numeric character

{5} Repetition character


RE: sequence characters
Example-5: findall()

To retrieve all words having 4 and above characters using findall()

import re

str = 'one two three four five six seven 8 9 10'

result = [Link](r'\b\w{4,}\b', str)

print(result)

character Description

\b Matches only one space

\w Matches any alpha numeric character

{4, } Retrieve 4 or more characters


RE: sequence characters
Example-6: findall()

To retrieve all words having 3, 4, 5 characters using findall()

import re

str = 'one two three four five six seven 8 9 10'

result = [Link](r'\b\w{3, 5}\b', str)

print(result)

character Description

\b Matches only one space

\w Matches any alpha numeric character

{3, 5} Retrieve 3, 4, 5 characters


RE: sequence characters
Example-7: findall()

To retrieve only single digit using findall()

import re

str = 'one two three four five six seven 8 9 10'

result = [Link](r'\b\d\b', str)

print(result)
character Description

\b Matches only one space

\d Matches only digit


RE: sequence characters
Example-7: findall()

To retrieve all words starts with ‘t’ from the end of the string

import re

str = 'one two three one two three'

result = [Link](r't{\w}*\z', str)

print(result)

character Description

\z Matches from end of the string

\w Matches any alpha numeric character

t Starting character is ‘t’


RE: Quantifiers
RE: Quantifiers


Characters which represents more than 1 character to be matched in the string

Character Description

+ 1 or more repetitions of the preceding regexp

* 0 or more repetitions of the preceding regexp

? 0 or 1 repetitions of the preceding regexp

{m} Exactly m occurrences

{m, n} From m to n.
m defaults to 0
n defaults to infinity
RE: Quantifiers
Example-1:

To retrieve phone number of a person

import re

str = 'Tomy: 9706612345'

res = [Link](r'\d+', str)

print([Link]())

character Description

\d Matches from any digit

+ 1 or more repetitions of the preceding regexp


RE: Quantifiers
Example-2:

To retrieve only name

import re

str = 'Tomy: 9706612345'

res = [Link](r'\D+', str)

print([Link]())

character Description

\D Matches from any non-digit

+ 1 or more repetitions of the preceding regexp


RE: Quantifiers
Example-3:

To retrieve all words starting with “an” or “ak”

import re

str = 'anil akhil anant arun arati arundhati abhijit ankur'

res = [Link](r'a[nk][\w]*', str)

print(res)
RE: Quantifiers
Example-4:

To retrieve DoB from a string

import re

str = 'Vijay 20 1-5-2001, Rohit 21 22-10-1990, Sita 22 15-09-2000'

res = [Link](r'\d{2}-\d{2}-\d{4}', str)

print(res)

RE Description

\d{2}-\d{2}-\d{4} Retrieves only numeric digits in the format of 2digits-2digits-


4digits
RE: Special Character
RE: Special Characters

Character Description

\ Escape special character nature

. Matches any character except new line

^ Matches begining of the string

$ Matches ending of a string

[...] Denotes a set of possible characters


Ex: [6b-d] matches any characters 6, b, c, d
[^...] Matches every character except the ones inside brackets
Ex: [^a-c6] matches any character except a, b, c or 6
(...) Matches the RE inside the parentheses and the result can be captured

R | S matches either regex R or regex S


RE: Special Characters
Example-1:

To search whether a given string is starting with ‘He’ or not

import re

str = "Hello World"

res = [Link](r"^He", str)

if res:

print("String starts with 'He'")

else

print("String does not start with 'He'")

RE Description
“^He” Search from the begining
RE: Special Characters
Example-2:

To search whether a given string is starting with ‘He’ or not from the end

import re

str = "Hello World"

res = [Link](r"World$", str)

if res:

print("String ends with 'World'")

else

print("String does not end with 'World'")

RE Description
“World$” Search from the end
RE: Special Characters
Example-3:

To search whether a given string is starting with ‘World’ or not from the end by
ignoring the case

import re

str = "Hello World"

res = [Link](r"world$", str, [Link])

if res:

print("String ends with 'world'")

else:

print("String does not end with 'world'")


RE Description
“World$” Search from the end

[Link] Ignore the case

[Link]
RE: Special Characters
Example-4:

To retrieve the timings am or pm

import re

str = 'The meeting may be at 8am or 9am or 4pm or 5pm.'

res = [Link](r'\dam|\dpm', str)

print(res)
RE: On Files
RE: On Files
Example-1:

To retrieve the emails from the file

import re

# open file for reading

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

# repeat for each line of the file

for line in f:

res = [Link](r'\s+@\S+', line)

# display if there ara some elements in result

if len(res)>0:

print(res)

# close the file

[Link]()
RE: On Files
Example-2:

To retrieve the data and write to another file

# Open the files

f1 = open('[Link]', 'r')

f1 = open('[Link]', 'w')

# repeat for each line of the file f1

for line in fi:

res1 = [Link](r'\d{4}', line) # exptract id no from f1

res2 = [Link](r'\d{4,}.\d{2}', line) # extract salary from f1

print([Link](), [Link]()) # display them

[Link]([Link]()+"\t") # write id no into f2

[Link]([Link]()+"\n") # write salary into f2

# close the files

[Link]()

[Link]()
RE: On HTML Files
RE: On HTML Files
Example-1:

To retrieve info from the HTML file

Step-1:
import [Link] Import this module

f = [Link](r’[Link]
Ex:

f = [Link](r’[Link]
[Link] Module name

urlopen To open the html files

[Link] Protocol to open the local files

~|Python\[Link] Under home DIR, under Python sub-DIR the [Link] file is
present
RE: On HTML Files
Example-1:

Step-2: read and decode

text = [Link]() To read the file content

str = [Link]() Since the HTML file contains the information in the byte strings

Step-3: Apply RE
r'<td>\w+</td>\s<td>(\w+)<\td>\s<td>(\d\d.\d\d)<\td>'
THANK YOU
Threads
Team Emertxe
Introduction
Creating Threads
Creating Threads
Introduction


Python provides ‘Thread’ class of threading module to create the threads


Various methods of creating the threads:


Method-1: Without using the class


Method-2: By creating a sub-class to Thread class


Method-3: Without creating a sub-class to Thread class
Creating Threads
Method-1: Without using class

Step-1:

- Create a thread by creating an object class and pass the function name as target
for the thread

Syntax t = Thread(target = function_name, [args = (arg1, arg2, ...)])

target Represents the function on which thread will act

args Represents the tuple of arguments which are passed to the function


Step-2:

- Start the thread by using start() method

[Link]()
Creating Threads
Program-1: No arguments
Creating a thread without using a class

Output:
from threading import *

Hello I am running
#Create a function Hello I am running
def display(): Hello I am running
print("Hello I am running") Hello I am running
Hello I am running
#Create a thread and run the function 5 times
for i in range(5):
#Create the thread and specify the function as its target
t = Thread(target = display)

#Run the thread


[Link]()
Creating Threads
Program-2: With arguments
Creating a thread without using a class

#To pass arguments to a function and execute it using a thread

from threading import * Output:

#Create a function Hello


def display(str): Hello
print(str) Hello
Hello
#Create a thread and run the function for 5 times Hello

for i in range(5):
t = Thread(target = display, args = ("Hello", ))
[Link]()
Creating Threads
Method-2: Creating Sub-class to Thread

Step-1: Create a new class by inheriting the Thread class
Example
 class MyThread(Thread):
MyThread New Class
Thread Base Class


Step-2: Create an Object of MyThread class
t1 = MyThread()


Step-3: Wait till the thread completes
[Link]()
Creating Threads:
Program-1: Creating Sub-class to Thread
Creating a thread by creating the sub-class to thread class

#Creating our own thread Output:


from threading import Thread
1
#Create a class as sub class to Thread class 2
class MyThread(Thread):
3
#Override the run() method of Thread class 4
def run(self): 5
for i in range(1, 6):
print(i)

#Create an instance of MyThread class


t1 = MyThread()

#Start running the thread t1


[Link]()

#Wait till the thread completes its job


[Link]()

run() method will override the run() method in the Thread class
Creating Threads:
Program-2:
Creating a thread that access the instance variables of a class

#A thread that access the instance variables Output:


from threading import *

#Create a class as sub class to Thread class Hello


class MyThread(Thread):
def __init__(self, str):
Thread.__init__(self)
[Link] = str

#Override the run() method of Thread class


def run(self):
print([Link])

#Create an instance of MyThread class and pass the string


t1 = MyThread("Hello")

#Start running the thread t1


[Link]()

#Wait till the thread completes its job


[Link]()

Thread.__init__(self): Calls the constructor of the Thread class


Creating Threads
Method-3: Without creating sub-class to
Thread class

Step-1: Create an independent class


Step-2: Create an Object of MyThread class

obj = MyThread(‘Hello’)


Step-3: Create a thread by creating an object to ‘Thread’ class
t1 = Thread(target = [Link], args = (1, 2))
Creating Threads
Method-3: Without creating sub-class to
Thread class: Program

Creating a thread without sub-class to thread class

from threading import * Output:

#Create our own class Hello


class MyThread:
The args are: 1 2
#A constructor
def __init__(self, str):
[Link] = str

#A Method
def display(self, x, y):
print([Link])
print("The args are: ", x, y)

#Create an instance to our class and store Hello string


Obj = MyThread("Hello")

#Create a thread to run display method of Obj


t1 = Thread(target = [Link], args = (1, 2))

#Run the thread


[Link]()
Thread Class Methods
Single Tasking using a Thread
Single Tasking Thread
Introduction


A thread can be employed to execute one task at a time


Example:


Suppose there are three task executed by the thread one after one, then it is

called single tasking

Problem: Preparation of the Tea

Task-1: Boil milk and tea powder for 5 mins

Task-2: Add sugar and boil for 3 mins

Task-3: Filter it and serve

#A method that performs 3 tasks one by one

def prepareTea(self):

self.task1()

self.task2()

self.task3()
Single Tasking Thread
Program

#Single tasking using a single thread


from threading import *
from time import *

#Create our own class #Create an instance to our class


class MyThread: obj = MyThread()
#A method that performs 3 tasks one by one
def prepareTea(self): #Create a thread and run prepareTea method of Obj
self.task1() t = Thread(target = [Link])
self.task2() [Link]()
self.task3()

def task1(self):
print("Boil milk and tea powder for 5
mins...", end = '')
sleep(5)
print("Done")

def task2(self):
print("Add sugar and boil for 3 mins...",
end = '')
sleep(3)
print("Done")

def task3(self):
print("Filter and serve...", end = '')
print("Done")
Multi Tasking using a Multiple Thread
Multi Tasking Threads
Program-1
#Multitasking using two threads
from
 threading
Using moreimport
than *one thread is called Multi-threading, used in multi-tasking
from time import *

#Create our own class


class Theatre:
Output:
#Constructor that accepts a string
def __init__(self, str):
[Link] = str Run-1:

#A method that repeats for 5 tickets Cut Ticket : 1


def movieshow(self): Show chair : 1
for i in range(1, 6): Cut Ticket : 2
print([Link], ":", i) Show chair : 2
sleep(1) Cut Ticket : 3
Show chair : 3
Cut Ticket : 4
Show chair : 4
#Create two instamces to Theatre class Cut Ticket : 5
obj1 = Theatre("Cut Ticket")
obj2 = Theatre("Show chair") Show chair : 5

#Create two threads to run movieshow() Run-2: Race Condition


t1 = Thread(target = [Link])
t2 = Thread(target = [Link]) Cut Ticket : 1
Show chair : 1
#Run the threads Cut Ticket : 2
[Link]()
[Link]() Show chair : 2
Show chair : 3
Cut Ticket : 3
Cut Ticket : 4
Show chair : 4
Cut Ticket : 5
Show chair : 5
Multi Tasking Threads
Race-Condition


Using more than one thread is called Multi-threading, used in multi-tasking

Race-condition is a situation where threads are not acting in a expected sequence,
leading to the unreliable output

Race-condition can be avoided by ‘Thread Synchronization’
Multi Tasking Threads
Program-2
#Multitasking using two threads
from

Using more
threading than* one thread
import is called Multi-threading, used in multi-tasking
from time import *

#Create instance to railway class


#Create our own class #Specify only one berth is available
class Railway: obj = Railway(1)
#Constrauctor that accepts no. of available berths
def __init__(self, available): #Create two threads and specify 1 berth is needed
[Link] = available t1 = Thread(target = [Link], args = (1, ))
t2 = Thread(target = [Link], args = (1, ))
#A method that reserves berth
def reserve(self, wanted): #Give names to the threads
[Link]("First Person")
#Display no. of available births [Link]("Second Person")
print("Available no. of berths = ", [Link])
#Start running the threads
#If available >= wanted, allot the berth [Link]()
if ([Link] >= wanted): [Link]()
#Find the thread name
name = current_thread().getName()

#Display the berth is allotted for the person


print("%d berths are alloted for %s" % (wanted, name))

#Make time delay so that ticket is printed


sleep(1.5)

#Decrease the number of available berths


[Link] -= wanted

else:

#If avaible < wanted, then say sorry


print("Sorry, no berths to allot")

The output of the above code is not correct. Run multiple times & see the o/p
Thread Synchronization
Thread Synchronization
Introduction
Thread When a thread is already acting on an object, preventing any other
Synchronization thread from acting on the same object is called ‘Thread
Synchronization’ OR ‘Thread Safe’
OR
Thread Safe

Synchronized The object on which the threads are synchronized is called synchronized
Object object or Mutex(Mutually exclusive lock)

Techniques 1. Locks (Mutex)

2. Semaphores
Thread Synchronization
Mutex

1. Creating the lock

l = Lock()

2. To lock the current object

[Link]()

3. To unlock or release the object

[Link]()
Thread Synchronization
Mutex: Program
#Create instance to railway class
#Create our own class
class Railway: #Specify only one berth is available
#Constrauctor that accepts no. of available berths obj = Railway(1)
def __init__(self, available):
[Link] = available
#Create two threads and specify 1 berth is needed
#Create a lock Object
self.l = Lock() t1 = Thread(target = [Link], args = (1, ))
t2 = Thread(target = [Link], args = (1, ))
#A method that reserves berth
def reserve(self, wanted):

#lock the current object #Give names to the threads


[Link]() [Link]("First Person")
[Link]("Second Person")
#Display no. of available births
print("Available no. of berths = ", [Link])
#Start running the threads
#If available >= wanted, allot the berth
if ([Link] >= wanted): [Link]()
#Find the thread name [Link]()
name = current_thread().getName()

#Display the berth is allotted for the person


print("%d berths are alloted for %s" % (wanted, name))

#Make time delay so that ticket is printed


sleep(1.5)

#Decrease the number of available berths


[Link] -= wanted

else:

#If avaible < wanted, then say sorry


print("Sorry, no berths to allot")

#Task is completed, release the lock


[Link]()
Thread Synchronization
Semaphore
Semaphore Is an object that provides synchronization based on a counter

Creation l = Semaphore(counter)

#Counter value will be 1 by default

Usage #Acquire the lock


[Link]()

#Critical Section

#Release the lock


[Link]()
Thread Synchronization
Mutex: Program
#Create instance to railway class
#Create our own class
class Railway: #Specify only one berth is available
#Constrauctor that accepts no. of available berths obj = Railway(1)
def __init__(self, available):
[Link] = available
#Create two threads and specify 1 berth is needed
#Create a lock Object
self.l = Semaphore() t1 = Thread(target = [Link], args = (1, ))
t2 = Thread(target = [Link], args = (1, ))
#A method that reserves berth
def reserve(self, wanted):

#lock the current object #Give names to the threads


[Link]() [Link]("First Person")
[Link]("Second Person")
#Display no. of available births
print("Available no. of berths = ", [Link])
#Start running the threads
#If available >= wanted, allot the berth
if ([Link] >= wanted): [Link]()
#Find the thread name [Link]()
name = current_thread().getName()

#Display the berth is allotted for the person


print("%d berths are alloted for %s" % (wanted, name))

#Make time delay so that ticket is printed


sleep(1.5)

#Decrease the number of available berths


[Link] -= wanted

else:

#If avaible < wanted, then say sorry


print("Sorry, no berths to allot")

#Task is completed, release the lock


[Link]()
Dead Locks
Dead Locks
Introduction

bookticket #Book Ticket thread


lock-1:
lock on train
lock-2:
Train lock on compartment

#Cancel Ticket thread


lock-2:
Compartment
lock on compartment
lock-1:
lock on train

cancelticket

When a thread has locked an object and waiting for another object to be released by another thread,
and the other thread is also waiting for the first thread to release the fisrt object, both threads
will continue to wait forever. This condition is called Deadlock
Dead Locks
Program
#Dead lock of threads #Create a function for cancelling a ticket
from threading import * def cancelticket():
[Link]()
#Take two locks print("Cancelticket locked compartment")
l1 = Lock() print("Cancelticket wants to lock on train")
l2 = Lock()
[Link]()
print("Cancelticket locked train")
[Link]()
[Link]()
print("Cancellation of ticket is done...")

#Create a function for booking a ticket #Create two threads and run them
def bookticket(): t1 = Thread(target = bookticket)
[Link]() t2 = Thread(target = cancelticket)
print("Bookticket locked train")
print("Bookticket wants to lock on compartment") [Link]()
[Link]()
[Link]()
print("Bookticket locked compartment")
[Link]()
[Link]()
print("Booking ticket done...")
Dead Locks
Avoiding

bookticket #Book Ticket thread


lock-1:
lock on train
lock-2:
Train lock on compartment

#Cancel Ticket thread


lock-1:
Compartment
lock on compartment
lock-2:
lock on train

cancelticket
Dead Locks
Program: Avoiding Deadlocks
#Dead lock of threads #Create a function for cancelling a ticket
from threading import * def cancelticket():
[Link]()
#Take two locks print("Cancelticket locked compartment")
l1 = Lock() print("Cancelticket wants to lock on train")
l2 = Lock()
[Link]()
print("Cancelticket locked train")
[Link]()
[Link]()
print("Cancellation of ticket is done...")

#Create a function for booking a ticket #Create two threads and run them
def bookticket(): t1 = Thread(target = bookticket)
[Link]() t2 = Thread(target = cancelticket)
print("Bookticket locked train")
print("Bookticket wants to lock on compartment") [Link]()
[Link]()
[Link]()
print("Bookticket locked compartment")
[Link]()
[Link]()
print("Booking ticket done...")
Communication between Threads
Threads Communication
Introduction

lst prod
1, 2, 3, 4

dataprodover
False

Producer Consumer
Threads Communication
Program
from threading import * #Create the consumer class
from time import * class Consumer:
def __init__(self, prod):
[Link] = prod

def consume(self):
#sleep for 100ms a s long as dataprodover is False
while [Link] == False:
sleep(0.1)
#Display the content of list when data production is over
print([Link])

#Create producer class #Create producer object


class Producer: p = Producer()
def __init__(self):
[Link] = [] #Create consumer object and pass producer object
[Link] = False c = Consumer(p)

def produce(self): #Create producer and consumer threads


#create 1 to 10 items and add to the list t1 = Thread(target = [Link])
for i in range(1, 11): t2 = Thread(target = [Link])
[Link](i)
sleep(1) #Run the threads
print("Item produced...") [Link]()
[Link]()
#Inform teh consumer that the data production is completed
[Link] = True
Threads Communication
Improving Efficiency


Using notify() and wait()

Using queue
Threads Communication
Improving Efficiency: notify(), wait()
#Create Producer Class #Create Consumer class
class Producer: class Consumer:
def __init__(self): def __init__(self, prod):
[Link] = [] [Link] = prod
[Link] = Condition()
def consume(self):
def produce(self): #Get lock on condition object
#Lock the conditional object [Link]()
[Link]()
#Wait only for 0 seconds after the production
#Create 1 to 10 items and add to the list [Link](timeout = 0)
for i in range(1, 11):
[Link](i) #Release the lock
sleep(1) [Link]()
print("Item produced...")
#Display the contenst of list
#Inform the consumer that production is completed print([Link])
[Link]()

#Release the lock


[Link]()
Threads Communication
Improving Efficiency: Queues

prod

[Link]()

[Link]()
6 5 4 3 2 1

Producer Consumer
Threads Communication
Improving Efficiency: Queues

#Create Producer class #Create Consumer class


class Producer: class Consumer:
def __init__(self): def __init__(self, prod):
self.q = Queue() [Link] = prod

def produce(self): def consume(self):


#Create 1 to 10 items and add to the queue #Receive 1 to 10 items from the queue
for i in range(1, 11): for i in range(1, 11):
print("Producing item: ", i) print("Receiving item: ", [Link](i))
[Link](i)
sleep(1)
Daemon Threads
Daemon Threads
Introduction

● Sometimes, threads should be run continuosly in the memory


● Example

- Internet Server

- Garbage collector of Python program


● These threads are called Daemon Threads
● To make the thread as Daemon, make

[Link] = True
Daemon Threads
Program
#To display numbers from 1 to 5 every second #To display numbers from 1 to 5 every second
def display(): def display():
for i in range(5): for i in range(5):
print("Normal thread: ", end = '') print("Normal thread: ", end = '')
print(i + 1) print(i + 1)
sleep(1) sleep(1)

#Create a normal thread and attach it to display() and run it


t = Thread(target = display)
[Link]()

#Create another thread and attach it to display_time()


d = Thread(target = display_time)

#make the thread daemon


[Link] = True

#Run the daemon thread


[Link]()
THANK YOU
Python2 Vs Python3
Team Emertxe
Division
Division

2.x 3.x

print 5 / 2 print (5 / 2)

Output Output

2 2.5
Print
Print

2.x 3.x

print "Hello World" print ("Hello World")

Output Output

Hello World Hello World


Unicode
Unicode

2.x 3.x

print(type('Hello')) print(type('Hello'))

print(type(b'Hello')) print(type(b'Hello'))

Output Output

<type 'str'> <class 'str'>


<type 'str'> <class 'bytes'>
xrange
Xrange

2.x 3.x

for x in xrange(1, 5): for x in xrange(1, 5):


print(x) print(x)

Output Output

1 Original exception was:


2 Traceback (most recent call last):
3 File "[Link]", line 1, in <module>
4 for x in xrange(1, 5):
NameError: name 'xrange' is not defined
Raising Exceptions
Raising Exceptions

2.x 3.x

print ('Python')
print 'Python'
raise IOError("file error")
raise IOError, "file error"

Output Output

Traceback (most recent call last): Original exception was:


File "[Link]", line 2, in <module> Traceback (most recent call last):
raise IOError, "file error" File "1_3x.py", line 2, in <module>
IOError: file error raise IOError("file error")
OSError: file error
Raising Exceptions

2.x 3.x

print 'Python' print ('Python')


try: try:
Generate_Name_error Generate_Name_error
except NameError, err: except NameError as err:
print err, '--> our error message' print (err, '--> our error message')

Output Output

Python Python
name 'Generate_Name_error' is not defined --> name 'Generate_Name_error' is not defined -->
our error message our error message
THANK YOU

You might also like