Python Programming Features Overview
Python Programming Features Overview
Python
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
● 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
Faster Slower
Compulsory to declare the data types of variables Data Types are not required
Absence of GC GC is present
Supports Single and multi dimensional arrays Supports only single dimension
Comments
Comments
Single Line Comments
● Starts with # symbol
● Comments are non-executable statements
● 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
-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)
● 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:
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:
bytearray Data-type
Sequences
bytearray
● bytearray is similar to bytes
● Difference is items in bytearray is modifiable
● Example-1:
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:
range Data-type
Sequences
range
● range represents sequence of numbers
● Numbers in range are not modifiable
● Example-1:
● Example-3:
17 #Create the list with range of numbers
18 lst = list(range(10))
19 print(lst)
Data Types
Sets
Sets
● 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:
● Example-6:
● Example-2:
9 #One more methos to create the frozen set
10 fs = frozenset("abcdef")
11 print(fs)
Data Types
Mapping Types
Mapping
● Example-2:
10 #Print all the keys
11 print([Link]())
12
13 #Print all the values
14 print([Link]())
Mapping
● Example-3:
● Example-4:
24 #create the dictionary and populate dynamically
25 d = {}
26 d[10] = "Ram"
27
28 print(d)
Data Types
● 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
= a = b = 1
+=
-+ Example-2:
*+ a = 1; b = 1
/=
%= Example-3:
**=
a, b = 1, 2
//=
n = 10
print(-n)
Example-2:
num = -10
num = -num
print(num)
OPERATORS
Relational
Operator Example Result
== a == b False
!= a != b True
Example-2:
and a and b 2
or a or b 1
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")
or a or b True
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 1011(11)
^ a ^ b 0000 0001(1)
Example-1:
names = ["Ram", "Hari", "Thomas"]
for i in names:
print(i)
Example-2:
postal = {"Delhi": 110001, "Chennai": 600001, "Bangalore": 560001}
Operator Description
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
^ Bitwise XOR
| Bitwise OR
in, not in, is, is not, <, <=, >, >=, !=, == Comparisons, including membership tests and identity
tests
not Boolean not
or Boolean or
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"+"World") HelloWorld
a, b = 1, 2
print(a, b) 1 2
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
● Step-2a: If programmer does not want to display description, then above step can
be skipped
parser = [Link]()
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
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
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")
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
Syntax:
Example-1
import array
#Create an array
a = [Link]("i", [1, 2, 3, 4])
#Create an array
a = array("i", [1, 2, 3, 4])
#Create an array
a = array('u', ['a', 'b', 'c', 'd'])
#Here, 'u' stands for unicode character
#Create an array
a = array('i', [1, 2, 3, 4])
#To retrieve the items of an array using array index using while loop
#Create an array
a = array('i', [1, 2, 3, 4])
Example arr[1: 4: 1]
#Create an array
x = array('i', [10, 20, 30, 40, 50, 60])
#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)
#Stride 2 means, after 0th Item, retrieve every 2nd Item from x
y = x[0: 7: 2]
print(y)
#To retrieve the items of an array using array index using for loop
#Create an array
a = array('i', [1, 2, 3, 4])
Method Description
[Link](x) Appends x at the end of the array a. ‘x’ can be another array or an
iterable object
Method Description
#Append 6 to an array
[Link](6)
print(a)
#Insert 11 at position 1
[Link](1, 11)
print(a)
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
Note: If one item in the array is of float type, then Python interpreter converts
remaining items into the float datatype
a = array([1, 2, 3, 4, 5])
print(a)
Example-5 arange(0, 10, 1.5) Produces [0. 1.5 3. 4.5 6. 7.5 9.]
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.]
a = zeros(5, int)
print(a)
a2 = array([1, 2, 3, 4])
2. Syntactically clearer
- Writing a + b is clearer than using the loops
power(a, n) Calculates a ^ n
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
a = array([1, 2, 3])
b = array([3, 2, 3])
c = a > b
print(c)
logical_and(), logical_or() and logical_not() are useful to get the Boolean array as a
result of comparing the compound condition
a = array([1, 2, 3])
b = array([3, 2, 3])
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
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)
c = nonzero(a)
‘Aliasing means not copying’. Means another name to the existing object
a = arange(1, 6)
b = a
print(a)
print(b)
view(): To create the duplicate array
Also called as ‘shallow copying’
a = arange(1, 6)
b = [Link]() #Creates new array
print(a)
print(b)
copy(): To create the copy the original array
Also called as ‘deep copying’
a = arange(1, 6)
b = [Link]() #Creates new array
print(a)
print(b)
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’
a = array([1, 2, 3])
print([Link])
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
print([Link])
print([Link])
print([Link])
print([Link])
Multi Dimensional Arrays
Attributes of an Array: The itemsize
● The ‘itemsize’ attribute gives the memory size of an array element in bytes
print([Link])
print([Link])
Multi Dimensional Arrays
Attributes of an Array: The dtype
● The ‘dtype’ attribute gives the datatype of the elements in the array
print([Link])
print([Link])
Multi Dimensional Arrays
Attributes of an Array: The nbytes
● The ‘nbytes’ attribute gives the total number of bytes occupied by an array
print([Link])
print([Link])
Multi Dimensional Arrays
Methods of an Array: The reshape()
● The ‘reshape’ method is useful to change the shape of an array
a = arange(10) Outputs:
print(a)
#Change to 1D array
a = [Link]()
print(a)
Multi Dimensional Arrays
Methods of creating an 2D-Array
Example-1:
[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]
[[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
[[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
[[6 7]
[8 9]
[10 11]]
Multi Dimensional Arrays
Indexing of an 2D-Array
a[:, :] Produces:
a[:]
a[: :] [[1 2 3]
[4 5 6]
[7 8 9]]
#Display 0th row
a[0, :]
a = matrix(a) [[1 2 3]
[4 5 6]]
print(a)
[[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)
Function max()
min()
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-3 s = """
Welcome to Python
"""
Example-4 s = '''
Welcome to Python
'''
n = len(str)
print("Len: ", n)
Strings And Characters
Indexing the Strings
Both positive and Negative indexing is possible in 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
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
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
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
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)
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)
n = [Link](‘Delhi’)
n = [Link](‘e’, 0, 3)
n = [Link](‘e’, 0, len(str))
Strings And Characters
Strings are Immutable
Immutable object is an object whose content cannot be changed
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
print(str1)
Strings And Characters
Splitting And Joining Strings
Syntax [Link](‘character’)
lst = [Link](',')
Syntax [Link](str)
str1 = "-".join(str)
Strings And Characters
Changing the Case of the Strings
Methods upper()
lower()
swapcase()
title()
str = "Python is the future"
Methods startswith()
endswith()
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
Syntax
"format string with replacement fields". format(values)
id = 10
name = "Ram"
sal = 19000.45
print("{}, {}, {}". format(id, name, sal))
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
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
Example
def sum(a, b):
""" This function finds sum of two numbers """
c = a + b
print('Sum= ', c)
Example Description
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
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
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))
lst 1, 2, 3, 4
Outside the
function
Heap
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
sum = 0
for i in args:
sum += i
print('Sum of all numbers= ', (farg + sum))
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
The global variable can be accessed inside the function using the global keyword
- global var
def myfunction():
myfunction()
Syntax to get a copy of the global variable inside the function and work on it
- globals()[“global_var_name”]
def myfunction():
a = 2 # a is local var
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
A function calling itself is called as Recursions
Example-1
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
Syntax
Example
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)
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
Problem
To calculate sum of numbers from 1 to 50 using reduce() & lambda functions
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
res = decor(num)
Function Decorators
Complete Program
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
# 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
Generator: Function that returns sequence of values
It is written like ordinary function but it uses ‘yield’ statement
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: '))
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
def display():
print('Hello Python')
if __name__ == '__main__':
else:
import one
Indexing + Slicing can be applied on list
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
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
Membership
name = "Ram"
print(name in s)
Repetition
t1 = (1, 2, 3)
t2 = t1 * 3
print(t2)
Tuple
Functions To Process Tuples
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
Example
copy() d1 = [Link]() Copies all items from ‘d’ into a new dictionary ‘d1’
pop() [Link](k, [,v]) Removes the key ‘k’ and its value.
Dictionaries
Programs
To create the dictionary with employee details
x = {}
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
#Make a dictionary
z = zip(countries, cities)
d = dict(z)
print(d)
Dictionaries
Converting strings into dictionary
str = "Ram=23,Ganesh=20"
for x in [Link](','):
y = [Link]('=')
[Link](y)
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
d = {10: "Ram"}
Example display(d)
Program:
#To create the ordered dictionary
from collections import 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
‘Self’ is the default variable that contains the memory address of the instance of the
current class
Constructor will be called only once i.e at the time of creating the objects
s = Student()
Constructor
Constructor with 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])
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]
Single copy is created for all instances
Accessing class vars are possible only by 'class methods'
Accessing class vars from outside the class,
[Link]
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’
s1 = Student() 10 n 10
n
s2 = Student()
11 n 10
n
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
#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]()
class Bird:
#Define the class var here
wings = 2
#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]()
def putdata(self):
print("Name: ", [Link])
print("Salary: ", [Link])
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
def display(self):
print("DoB: {}/{}/{}" . format([Link],
[Link], [Link]))
Inner Class
Program: Version-2
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.
def getid(self):
return [Link]
def getname(self):
return [Link]
def getaddress(self):
return [Link]
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()
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 getname(self):
return [Link]
def getaddress(self):
return [Link]
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()
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 getsalary(self):
return [Link]
By comparing both the codes, we can observe 75% of the code is common
Significance Of Inheritance
Syntax:
class Subclass(Baseclass):
Significance Of Inheritance
Advantages
Smaller and easier to develop
Productivity increases
name
address
s
salary
setid(), getid()
setname(), getname()
setaddress(), getaddress()
setsalary(), getsalary()
marks
setmarks(), getmarks()
Deriving the new classes from the existing classes such that the new classes inherit all
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
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])
super() is a built-in method which is useful to call the super class constructor or Methods
Examples
#Call super class constructors
super().__init__()
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])
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)
Bank
AndhraBank StateBank
# A Python program showing single inhertiance in which two sub classes are derived from a
single base class.
s = StateBank()
s.available_cash()
Types of Inheritance
Multiple
Father Mother Syntax:
Child
# A Python program to prove that only one class constructor is available to sub class in
multiple inheritance.
class A(object):
def __init__(self):
self.a = 'a'
print(self.a)
class B(object):
def __init__(self):
self.b = 'b'
print(self.b)
#A Python program to access all the instance variables of both the base classes in
multiple inheritance.
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__()
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 P(X,Y,C):
def method(self):
print('P class method')
super().method()
P = P()
[Link]()
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
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
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
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
# Error #Correction
# using + operator on objects # overloading + operator to act on objects
#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
class Mahabharat:
def __init__(self, pages):
[Link] = pages
b1 = Ramayan(1000)
b2 = Mahabharat(1500)
# 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')
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
class Circle(Square):
def area(self, x):
print('Circle area= %.4f' % ([Link] *x * x))
If a method written in sub class overrides the same method in super class,
then it is called method overriding
Example:
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
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-3
class Sub3(Myclass):
def calculate(self, x):
print("Cube: ", x * x * x)
Example-2
Maruthi, Santro, Benz are all objects of class Car
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 *
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 *
#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
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:
What? When PVM cannot execute the byte code, it flags runtime error
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
Program Output
def increment(sal): py 3.0_logical_errors.py
sal = sal * 15 / 100 New Salary: 750.00
return sal
Program Output
#1. Open the file py 4_effect_of_exception.py
f = open("myfile", "w")
Enter two number: 10 0
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
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.
- When there is no exception, else block is executed after the try block.
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]()
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-4 except:
Exceptions
Types: Program-3A
It is useful to ensure that a given condition is True, It is not True, it raises
AssertionError.
Syntax:
Program - 1 Program - 2
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"
Step-3 try:
#code
except MyException as me:
print(me)
Exceptions
User-Defined Exceptions: Program
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)
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:
f = open("[Link]", "w")
Program
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+')
if [Link](fname):
f = open(fname, 'r')
else:
print(fname+' does not exist')
[Link]()
2. It will take care of closing the file, without using close() explicitly
Program -2
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]))
def display(self):
print("{:5d} {:20s} {:10.2f}".format([Link], [Link],[Link]))
except EOFError:
print('End of file reached....')
break
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.
# 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
import os
# 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')
# A Python program to use the makedirs() function to create sub and sub-sub directories.
import os
import os
# to remove newsub2 directory
[Link]('newsub/newsub2')
Working With Directories
Program-5
import os
# to remove mysub3, mysub2 and then mysub.
[Link]('mysub/mysub2/mysub3')
Working With Directories
Program-6
import os
# to rename enum as newenum
[Link]('enum', 'newenum')
Working With Directories
Program-7
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
Example-1
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
result = [Link](str)
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]())
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
\W Represents non-alphanumeric\b
import re
str = 'an apple a day keeps the doctor away'
result = [Link](r'a[\w]*', str)
import re
str = 'an apple a day keeps the doctor away'
result = [Link](r'\ba[\w]*\b', str)
import re
str = 'The meeting will be conducted on 1st and 21st of every month'
print(word)
import re
print(result)
character Description
import re
print([Link]())
character Description
import re
print(result)
character Description
import re
print(result)
character Description
import re
print(result)
character Description
To retrieve all words starts with ‘t’ from the end of the string
import re
print(result)
character Description
Characters which represents more than 1 character to be matched in the string
Character Description
{m, n} From m to n.
m defaults to 0
n defaults to infinity
RE: Quantifiers
Example-1:
import re
print([Link]())
character Description
import re
print([Link]())
character Description
import re
print(res)
RE: Quantifiers
Example-4:
import re
print(res)
RE Description
Character Description
import re
if res:
else
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
if res:
else
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
if res:
else:
[Link]
RE: Special Characters
Example-4:
import re
print(res)
RE: On Files
RE: On Files
Example-1:
import re
f = open('[Link]', 'r')
for line in f:
if len(res)>0:
print(res)
[Link]()
RE: On Files
Example-2:
f1 = open('[Link]', 'r')
f1 = open('[Link]', 'w')
[Link]()
[Link]()
RE: On HTML Files
RE: On HTML Files
Example-1:
Step-1:
import [Link] Import this module
f = [Link](r’[Link]
Ex:
f = [Link](r’[Link]
[Link] Module name
~|Python\[Link] Under home DIR, under Python sub-DIR the [Link] file is
present
RE: On HTML Files
Example-1:
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
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)
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
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
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
#A Method
def display(self, x, y):
print([Link])
print("The args are: ", x, y)
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
def prepareTea(self):
self.task1()
self.task2()
self.task3()
Single Tasking Thread
Program
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 *
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 *
else:
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)
2. Semaphores
Thread Synchronization
Mutex
l = Lock()
[Link]()
[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):
else:
Creation l = Semaphore(counter)
#Critical Section
else:
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
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])
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]()
prod
[Link]()
[Link]()
6 5 4 3 2 1
Producer Consumer
Threads Communication
Improving Efficiency: Queues
- Internet Server
[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)
2.x 3.x
print 5 / 2 print (5 / 2)
Output Output
2 2.5
Print
Print
2.x 3.x
Output Output
2.x 3.x
print(type('Hello')) print(type('Hello'))
print(type(b'Hello')) print(type(b'Hello'))
Output Output
2.x 3.x
Output Output
2.x 3.x
print ('Python')
print 'Python'
raise IOError("file error")
raise IOError, "file error"
Output Output
2.x 3.x
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