Python Book Pages (1)
Python Book Pages (1)
1
1) Language Fundamentals
Introduction
1. Python is a general-purpose high-level programming language.
2. Python was developed by Guido Van Rossum in 1989 while working
at National Research Institute at Netherlands.
3. But officially Python was made available to public in 1991. The official
Date of birth for Python is: Feb 20th 1991.
4. Python is recommended as first programming language for beginners.
Features of Python
1. Simple and easy to learn:
2. Freeware and Open Source:
3. High Level Programming language:
4. Platform Independent:
5. Dynamically Typed:
6. Extensive Library
2
Python Versions:
Current Versions:
By mistake if we are using any other symbol like $ then we will get
syntax error.
• Cash = 10 √
• Cash = 20 x
3
2. Identifier should not starts with digit
• 123total x
• otal123 √
Identifier:
4
3) Reserved Words in Python
Note:
1. All Reserved words in Python contain only alphabet symbols.
2. Except the following 3 reserved Upper case words, all contain only
Lower case alphabet symbols.
• True • False • None
Eg: a = true x
A = True √
>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def',
'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import',
'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try',
'while', 'with', 'yield']
5
Data Types in Python
We can use int data type to represent whole numbers (integral values)
Eg: a=10
Type (a) #int
6
Note:
In Python 2 we have long data type to represent very large integral values.
But in Python3 there is no long type explicitly and we can represent long
values\also by using int type only.
We can use float data type to represent floating point values (decimal values)
Eg: f=1.234
Type (f) float
We can use this data type to represent Boolean values. The only allowed
Values for this data type are:
True and False
Internally Python represents True as 1 and False as 0
b=True
type (b) => bool
Eg:
a=10 b=20
c=a<b print(c)==>True
True + True ==>2 True-False ==> 1
7
4) STR Type:
For this requirement we should go for triple single quotes (''') or triple double
quotes (""")
s1='''CrawCyber'''
s1="""Craw
Cyber"""
We can also use triple quotes to use single quote or double quote in our String.
''' This is " character'''
'This i " Character'
We can embed one string in another string
print(i)
8
Output ==> 0 to 9
r = range(10,20)
for i in r :
print(i)
Output ==> 10 to 19
We can access elements present in the range Data Type by using index.
r=range(10,20)
r[0]==>10
r[15]==>IndexError: range object index out of range We cannot modify the
values of range data type
Eg: r[0]=100
TypeError: 'range' object does not support item assignment We can create
a list of values with range data type
Eg: l = list(range(10))
print(l)
output ==> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
9
Ex:-
l1 = [1,2,3,4,5,'Name',1.3,True]
print(l1)
output
[1,2,3,4,5,'Name',1.3,True]
Ex:-
l1 = [1,2,3,4,5,'Name',1.3,True]
print(l1)
# accessing eliment using index
print(l1[2])
output
[1,2,3,4,5,'Name',1.3,True]
3
1. Tuple is exactly same as List except that it is immutable. i.e once we creates
Tuple object, we cannot perform any changes in that object.
Ex:-
With one Element
b = 10,
c = (10,)
c = (10) int
With Multiple Elements
d = (10, 20, 30, 40)
e = (10, 20, -50, 21.3, ‘Security’)
f = 10, 20, -50, 21.3, ‘Security’
10
8) Set Data Type:
s={100,0,10,200,10,'Name'}
print(s) # {0, 100, 'Name', 200, 10}
print(s[0]) ==>TypeError: 'set' object does not support
indexing
11
d1 = {}
d1['a'] = 'apple'
d1['ab'] = 'Ball'
d1['abc'] = 'cat'
print(d1)
We can convert one type value to another type. This conversion is called
Typecasting or Type coercion.
The following are various inbuilt functions for type casting.
1.int () 2.float () 3.bool () 4.str ()
1. Int ()
Eg:
int(123.987)
Output=> 123 Output=> 0
int(True) int("10")
Output=> 1 Output=> 10
int(False) int("10.5")
12
2) Float ():
We can use float() function to convert other type values to float type.
float(10) float("10")
Output=> 10.0 Output=> 10.0
float(True) float("10.5")
Output=> 1.0 Output=> 10.5
float(False) float("ten")
Output=> 0.0
ValueError: could not convert string to float: 'ten'
3) Bool ():
We can use this function to convert other type values to bool type.
Eg:
bool(0)==>False
bool(1)==>True bool(0.0)==>False
bool(10)===>True bool("True")==>True
bool(10.5)===>True bool("False")==>True
bool(0.178)==>True bool("")==>False
4) Str ():
We can use this method to convert other type values to str type Eg:
Str (10) | Str (10.5) | Str (True)
5) Operators
1. Arithmetic Operators:
+ ==>Addition
- ==>Subtraction
* ==>Multiplication
/ ==>Division operator
% ===>Modulas operator
// ==>Floor Division operator
Eg 1:
a=10
b=20 a > b ==>is False
print("a < b is ",a<b) a >= b ==> is False
print("a <= b is ",a<=b) a < b ==>is True
a <= b ==>is True
14
print ("a > b is ",a>b)
We can apply relational operators for str types also
Eg 2:
a="sunil"
b="sunil"
print("a > b is ",a>b) a > b ==> is False
print("a >= b is ",a>=b) a >= b ==> is True
print("a < b is ",a<b) a < b ==> is False
print("a <= b is ",a<=b) a <= b ==> is True
Eg:
print(True>True) False
print(True>=True) True
print(10 >True) True
print(False > True) False
print(10>'sunil')
15
Equality operators:
= = , !=
We can apply these operators for any type even for incompatible types also
10==20 False==False
False True
10!= 20 "Name"=="Name"
True True
10==True 10=="Name"
False False
Logical Operators:
and, or , not
We can apply for all types.
For Boolean type’s behaviour:
and ==> If both arguments are True then only result is True
or ====> If at least one argument is True then result is True
Ex: x = 5
16
print (x > 3 or x < 4)
Ex: x = 5
print (not(x > 3 and x < 10))
Bitwise Operators:
& ==> If both bits are 1 then only result is 1 otherwise result is 0
| ==> If atleast one bit is 1 then result is 1 otherwise result is 0
^ ==> If bits are different then only result is 1 otherwise result is 0
~ ==> bitwise complement operator 1==>0 & 0==>1
<< ==> Bitwise Left shift
>> ==>Bitwise Right Shift
17
Shift Operators:
18
Assignment Operators:
Special operators:
1) Identity Operators
We can use identity operators for address comparison. If 2 identity operators are
available
1. is 2. is not
Note:
We can use is operator for address comparison whereas == operator for content
comparison.
2. Membership Operators:
We can use Membership operators to check whether the given object present in the
given collection.(It may be String, List, Set, Tuple or Dict)
Eg:
x="hello learning Python is very easy!!!"
print('h' in x) #True
print('d' in x) #False
print('d' not in x) #True
print('Python' in x) #True
Eg:
list1=['sunny','bunny','chinny','pinny']
print("sunny" in list1) #True
print("tunny" in list1) #False
print("tunny" not in list1) #True
20
6) Input and Output Statements
1. Raw_input():
This function always reads the data from the keyboard in the form of String
Format. We have to convert that string type to our required type by using the
corresponding type casting methods.
2. Input ():
input() function can be used to read data directly in our required format. We
are not required to perform type casting.
***Note: But in Python 3 we have only input() method and raw_input() method
is not available.
Python3 input() function behaviour exactly same as raw_input() method of
Python 2. i.e every input value is treated as str type only.
raw_input() function of Python 2 is renamed as input() function in Python3
21
Eg: type(input("Enter Any Value: "))
Enter value :10
<class 'str'>
Enter value :10.5
<class 'str'>
Enter value :True
<class 'str'>
Q. Write a program to read 2 numbers from the keyboard and print sum.
Q. Write a program to read Employee data from the keyboard and print that data.
Output :
Enter Employee No: 101 Enter Employee Address: saket
Enter Employee Name: Name Employee Married ? [True |
Enter Employee Salary: 40000 False]: True
22
Employee Name : Name
Employee Salary: 40000.0
Please Confirm Information Employee Address: saket
Employee No : 101 Employee Married? : True
Eval ():
Eval () can evaluate the Input to list, tuple, set, etc based the provided Input.
Output Statements:
Note:
Print ("Hello"+"World")
Print ("Hello","World")
Output
HelloWorld
a,b,c=10,20,30 output:-
print(a,b,c,sep=',') 10,20,30
print(a,b,c,sep=':') 10:20:30
24
Eg: s = "Name"
a = 25
s1 = "Python"
s2 = "AI / ML / DS"
print("Hello", s, "Your Age is", a)
print("You are teaching ", s1, "and", s2)
Output
===> Hello Sunil Your Age is 25
You are Teaching Python and AI / ML / DS
Flow control describes the order in which statements will be executed at runtime.
1) Conditional Statements
if
if condition :
statement
or
25
if condition :
statement-1
If condition is true then statements will be executed
Eg: 1
Name = input("Enter Name :")
if name =="Name" :
print ("Hello Name Good Morning")
print ("How Are You")
Output ===>
Enter Name : Name
Hello Sunil Good Morning
How Are You
Eg: 2
name=input("Enter Name :") Output:-
if name=="Sunil" : Enter Name:Sunil
print("Hello Name Good Morning" How are you
print("How Are You")
2) if-else:
if condition :
Action-1
else :
Action-2
Action-3
Eg:
Brand = input ("Enter Your Favourite Brand:")
if brand == "RC" :
print ("It is childrens brand")
elif brand == "KF":
print ("It is not that much kick")
elif brand == "FO":
print ("Buy one get Free One")
else :
print ("Other Brands are not recommended")
Output:-
Enter Your Favourite Brand : RC
It is childrens brand Enter Your Favourite Brand : KF, It is not that much kick
Enter Your Favourite Brand : FO, Buy one get Free One
Enter Your Favourite Brand : KA, Other Brands are not recommended
Note:
1. else part is always optional
Hence the following are various possible syntaxes.
1. if
2. if - else
3. if-elif-else
4. if-elif
27
Q. Write a program to find biggest of given 3 numbers from the command
prompt?
n1 = int (input ("Enter First Number:"))
n2 = int (input ("Enter Second Number:"))
n3 = int (input ("Enter Third Number:"))
if n1>n2 and n1>n3: Output:-
print ("Biggest Number is:",n1) Enter First Number:10
elif n2>n3:
print ("Biggest Number is:",n2) Enter Second Number:23
else : Enter Third Number:34
print ("Biggest Number is:",n3) Biggest Number is: 34
Q Write a program to check whether the given number is in between 1 and 10?
N = int(input("Enter Number:"))
if n> = 1 and n<=10:
print ("The number",n,"is in between 1 to 10")
else:
print ("The number",n,"is not in between 1 to 10")
Output:-
Enter Number : 5
The number 5 is in between 1 to 10
Q. Write a program to take a single digit number from the key board and print is
value in English word?
Eg
0 ==> ZERO
1 ==> ONE
N = int(input("Enter a digit from o to 9:"))
if n == 0: print ("THREE")
print ("ZERO") elif n == 4:
elif n == 1: print ("FOUR")
print ("ONE") elif n == 5:
elif n == 2: print ("FIVE")
print ("TWO") elif n == 6:
elif n == 3:
28
print ("EIGHT")
print ("SIX") elif n == 9:
elif n == 7: print ("NINE")
print ("SEVEN") elif n == 10:
elif n == 8: print ("TEN")
else:
print ("Please Enter The Digit From 0 to 10")
Output==>
Enter a digit from o to 9: 7
SEVEN
Iterative Statements
If we want to execute a group of statements multiple times then we should go for
Iterative statements.
Python supports 2 types of iterative statements.
1. for loop 2. while loop
1) for loop
If we want to execute some action for every element present in some sequence
(it may be string or collection) then we should go for for loop.
Syntax: for x in sequence: body
Where sequence can be string or any collection.
Body will be executed for every element present in the sequence.
29
Eg 1: To print characters present in the given string
OUTPUT
S
u
s="Sunny "
for x in s : n
print (x) n
y
Output ==>
Enter some String: Name
The character present at 0 index is : s
While loop:
If we want to execute a group of statements iteratively until some condition
false,then we should go for while loop.Syntax:
Eg: To print numbers from 1 to 10 by using while loop
x=1
while x <=10:
print(x)
x=x+1
Output ===>
Enter number: 10
The sum of first 10 numbers is: 55
31
Eg:-
Write a program to prompt user to enter some name until entering Name
name="" Output ===>
while name!="Name": Enter Name:karan
name=input("Enter Name:")
print("Thanks for Enter Name:Name
confirmation") Thanks for confirmation
Infinite Loops:
i=0
while True:
i=i+1
print(i,"Hello")
OutPut
Outer Loop 0
Inner Loop 0 Inner Loop 0
Inner Loop 1 Inner Loop 1
Inner Loop 2 Inner Loop 2
Outer Loop 1 Rest of the code
32
Ex:-
Nested While Loop:
i=1
while i<5:
print ("Outer Loop",i)
j=1
while j<5:
print ("Inner Loop")
j+=1
i+=1
Output
Outer Loop 1 Outer Loop 2
Inner Loop Inner Loop
Inner Loop Inner Loop
Inner Loop Inner Loop
Inner Loop Inner Loop
Ex:-
n = int (input("Enter Number of rows"))
for i in range(1,n+1):
for j in range(1,i+1):
print("*",end=" ")
print()
33
Ex:- 1) *
i=1 2) **
while i <= 5:
j=1 3) ***
while j<=i: 4) ****
print ("*",end="") 5) *****
j =j+1
print () 6) ******
i=i+1 7) *******
3) Question
i=1
while i <= 5:
j=1
while j<=i:
print (i,end="")
j =j+1
print ()
i=i+1
Output 333
1 4444
22 55555
4) Question print ()
I=1 I = i+1
while i <= 5:
j=1
Output
while j< = i:
print (j,end="") 1
j =j+1 12
Transfer Statements
1) Break:
We can use break statement inside loops to break loop execution based on some
condition.
34
Eg:
for i in range(10):
if i==7:
print ("Processing is enough.. plz break")
break
print (i)
Eg:
Cart = [10,20,30,40,50,60,70,80] print ("To place this order insure
for item in cart: must be required")
if item > 500: break
print (item)
Output==>
10 50
20 60
30 70
40 80
To place this order insurance must be required
2) Continue:
We can use continue statement to skip current iteration and continue next iteration.
Eg 1: To print odd numbers in the Output===>>
range 0 to 9 Enter the Any Number10
1
n1=int(input("Enter the
Any Number")) 3
for i in range(n1): 5
if i%2!=0: 7
continue
print(i) 9
Eg:
Cart = [10,20,30,40,500,600,70,80]
for item in cart:
35
if item >=500:
print ("We cannot process this item :",item)
continue
print(item)
Output==>
10
20
30
40
We cannot process this item : 500
We cannot process this item : 600
70
80
Python Arrays
In Python, Array is an object that provide a mechanism for storing several data items
with only one identifier, thereby simplifying the task of data management. Array is
beneficial if you need to store group of elements of same datatype.
In Python, Arrays can increase or decrease their size dynamically
36
# Create Array Example 2
import array as ar
stu_roll = ar.array('i', [101, 102, 103, 104, 105])
print(stu_roll[0])
print(stu_roll[1])
print(stu_roll[2])
print(stu_roll[3])
print(stu_roll[4])
37
# Create Array and iterate using while Loop with index
from array import *
stu_roll = array('i', [101, 102, 103, 104, 105])
n = len(stu_roll)
i = 0
while(i<n):
print(stu_roll[i])
i+=1
String
The most commonly used object in any project and in any programming, language is
String only. Hence, we should aware complete information about String data type.
What is String?
Any sequence of characters within either single quotes or double quotes is considered
as a String.
Syntax:
s='sunil'
s="sunil "
n1 = '10'
s ='a'
String ab = 'bs'
Note: In most of other languages like C, C++,Java, a single character with in single
quotes is treated as char data type value. But in Python we are not having char data
type. Hence it is treated as String only.
Eg:
ch='a'
type(ch)
<class 'str'>
38
Eg:
s='''Craw
Cyber
Security'''
We can also use triple quotes to use single quotes or double quotes as symbol inside
String literal.
Eg:
s='This is ' single quote symbol' ==>invalid
s='This is \' single quote symbol' ==>valid
s="This is ' single quote symbol"====>valid
s='This is " double quotes symbol' ==>valid
s='The "Python Notes" by 'sunil' is very helpful' ==>invalid
s="The "Python Notes" by ' sunil ' is very helpful"==>invalid
s='The \"Python Notes\" by \' sunil \' is very helpful' ==>valid
s='''The "Python Notes" by ' sunil ' is very helpful''' ==>valid
39
Eg:
s=' sunil '
s=' sunil '
s[0] = 'd'
s[4] = 'a'
s[-1] = 'a'
s[10] = Index Error: string index out of range
Note: If we are trying to access characters of a string with out-of-range index then we
will get error saying: Index Error
Q. Write a program to accept some string from the keyboard and display its characters
by index wise (both positive and negatives index)
Ex:-
s=input ("Enter Some String:")
i=0
for x in s:
print("The character present at positive index {} and at
negatives index {} is {}".format(i,i-len(s),x))
i=i+1
Output:
Syntax: s[Beginindex:endindex:step]
40
Begin index: From where we have to consider slice(substring) endindex: We
have to terminate the slice(substring) at endindex-1 step: incremented value
Note: If we are not specifying Begin index then it will consider from Beginning
of the string. If we are not specifying end index then it will consider up to end
of the string
The default value for step is 1
Eg:
s="Learning Python is very very easy!!!"
s[1:7:1]
if +ve then it should be forward direction (left to right) and we have to consider begin
to end-1 if -ve then it should be backward direction (right to left) and we have to
consider begin to end+1
***Note:
In the backward direction if end value is -1 then result is always empty. In the forward
direction if end value is 0 then result is always empty.
In forward direction:
Left to right
default value for Begin: 0
default value for end: length of string default value for step: +1
In backward direction:
Note:
1.To use + operator for Strings, compulsory both arguments should be str type
2.To use * operator for Strings, compulsory one argument should be str and other
argument should be int
Checking Membership:
We can check whether the character or string is the member of another string or not by
using in and not in operators
s='sunil'
print('l' in s) #True
print('z' in s) #False
Program:
s=input("Enter main string:")
subs=input("Enter sub string:")
if subs in s:
42
print(subs,"is found in main string")
else:
print(subs,"is not found in main string")
Output:
Enter main string:python
Enter sub string:y
y is found in main string
Comparison of Strings:
We can use comparison operators (<,<=,>,>=) and equality operators(==,!=) for
strings. Comparison will be performed based on alphabetical order.
Eg:
s1=input ("Enter first string:")
s2=input ("Enter Second string:")
if s1==s2:
print ("Both strings are equal")
elif s1<s2:
print ("First String is less than Second String")
else:
print ("First String is greater than Second String")
Output:-
Enter first string: Sameer
Enter Second string: kadeer
First String is greater than Second String
Eg:
city=input ("Enter your city Name:")
scity=city.strip()
if scity=='Hyderabad':
print ("Hello Hyderabad..Adab")
43
elif scity=='Chennai':
print ("Hello Madras...Vanakkam")
elif scity=="Bangalore":
print("Hello Kannadiga...Shubhodaya")
else:
print("your entered city is invalid")
Finding Substrings:
We can use the following 2 methods
For forward direction:
find()
index()
1.find ():
s.find(substring)
Returns index of first occurrence of the given substring. If it is not available then we
will get -1
Eg:
s="Learning Python is very easy"
print(s.find("Python")) #9
print(s.find("Java")) # -1
print(s.find("r"))#3
Note: By default find() method can search total string. We can also specify the
boundaries to search.
s.find(substring,bEgin,end)
It will always search from begin index to end-1 index
44
Eg:
s="sunilkumarpython "
print(s.find('a'))#8
print(s.find('a',7,15))#8
print(s.find('z',7,15))#-1
index() method:
index() method is exactly same as find() method except that if the specified substring
is not available then we will get Value Error.
Eg:-
s=input("Enter main string:")
subs=input("Enter sub string:")
try:
n=index(subs)
except ValueError:
print("substring not found")
else:
print("substring found")
Output:
D:\python_classes>py test.py
Enter main string: learning python is very easy
Enter sub string: python
substring found
D:\python_classes>py test.py
Enter main string: learning python is very easy
Enter sub string: java
substring not found
45
Counting substring in the given String:
We can find the number of occurrences of substring present in the given string by
using count() method.
Eg:
s="abcabcabcabcadda" Output:
print(s.count('a')) 6
print(s.count('ab')) 4
print(s.count('a',3,7)) 4
Eg1:
s="Learning Python is very difficult"
s1=s.replace("difficult”, “easy")
print(s1)
Output:
Learning Python is very easy
46
Splitting of Strings:
Eg1:
s="cyber security solutions" Output:
for x in l: cyber
print(x) security
solutions
Eg2: Output
s="22-02-2018" 22
l=s.split('-') 02
for x in l: 2018
print(x)
Joining of Strings:
We can join a group of strings (list or tuple) write the given seperator.
s=seperator. join(group of strings)
Eg:1
t=('sunny','bunny','chinny')
s='-'.join(t)
print(s)
Output: sunny-bunny-chinny
47
Eg2:
l=['Hyderabad','Singapore','London','Dubai']
s=':'.join(l)
print(s)
output
hyderabad:singapore:london:dubai
Eg:
s='learning Python is very Easy' print(s.upper())
print(s.lower())
print(s.swapcase())
print(s.title())
print(s.capitalize())
Output:
LEARNING PYTHON IS VERY EASY
learning python is very easy
LEARNING pYTHON IS VERY eASY
Learning Python Is Very Easy
Learning python is very easy
48
Checking starting and ending part of the string:
Python contains the following methods for this purpose
1.s.startswith(substring)
2.s.endswith(substring)
Eg:
s='learning Python is very easy' Output
print(s.startswith('learning')) True
print(s.endswith('learning')) False
print(s.endswith('easy')) True
We can format the strings with variable values by using replacement operator {} and
format() method.
Eg:
name='sunil'
salary=10000
age=25
print("{} 's salary is {} and his age is {}".format(name,salary,age))
print("{0} 's salary is {1} and his age is {2}".format(name,salary,age))
print("{x} 's salary is {y} and his age is {z}".format(z=age,y=salary,x=name))
Output:
sunil 's salary is 10000 and his age is 25
sunil 's salary is 10000 and his age is 25
sunil 's salary is 10000 and his age is 25
49
List Data Structure
We can differentiate duplicate elements by using index and we can preserve insertion
order by using index. Hence index will play very important role.
Python supports both positive and negative indexes. +ve index means from left to right
where as negative index means right to left
50
list=eval(input("Enter List:"))
print(list)
print(type(list))
1)Deletion
del statement is used to delete an element of list or we can delete entire list using del
statement.
Ex:-
a = [10, 20, -50, 21.3, 'Security']
print("Before Deletion: ")
print(a)
print()
# Deleting single element of List
print("After Deletion:")
del a[2]
print(a)
print()
# Deleting entire List
del a
print(a) # It will show error as List a has been deleted
append( ) Function
This method is used to add an element at the end of the existing list.
51
Syntax:-
list_name.append(new_element)
Ex:-
# Append Method
a = [10, 20, -50, 21.3, 'Security']
print("Before Appending:")
for element in a:
print (element)
# Appending an element
a.append(100)
print()
print("After Appending")
for element in a:
print (element)
print("List:")
for element in a:
print(element)
insert( ) Function
This method is used to insert an element in a particular position of the existing list.
Syntax:-
list_name.insert(position_number, new_element)
Ex-:
#insert() Method
a = [10, 20, 30, 10, 90, 'Cybersecurity']
print("Before:”, a)
a.insert(3, 'Subscribe')
print("After:",a)
for element in a:
print (element)
52
With list() function:
Ex:-
# Creating Empty List using list Function
a = list()
print(a)
print(type(a))
pop () Function
This method is used to remove last element from the existing list.
Syntax:-
list_name.pop( )
#pop() method
a = [10, 20, 30, 10, 90, 'Security']
print("Before POP:", a)
a.pop()
print("After POP:", a)
for element in a:
print(element)
pop (n)
This method is used to remove an element specified by position number, from the
existing list and returns removed element.
Syntax:-
list_name.pop(position_number)
Ex:-
#pop(positon_number) method
a = [10, 20, 30, 10, 90, 'Security']
print("Before POP:", a)
n = a.pop(2)
print("After POP:", a)
for element in a:
print(element)
print("Removed Element:",n)
53
Remove() Function
This method is used to remove first occurrence of given element from the existing list.
If it doesn’t found the element, shows valueError.
Syntax:-
list_name.remove(element)
Ex:-
#remove(element) method
a = [70, 10, 30, 10, 90, 'Security']
print("Before Remove:", a)
a.remove(10)
print("After Remove:", a)
for element in a:
print(element)
index() Method
This method returns position number of first occurrence of given element in the list. If
it doesn’t found the element, shows valueError.
Syntax:-
list_name.index(element)
Ex:-
#index() Method
a = [10, 20, 30, 10, 90, 'Security']
num = a.index(10)
print(num)
reverse ()Function
This method is used to reverse the order of elements in the list.
Syntax:-
list_name.reverse( )
Ex:-
#reverse() Method
a = [10, 20, 30, 10, 90, 'Security']
print("Before Reverse:", a)
a.reverse()
print("After Reverse:", a)
54
for element in a:
print(element)
extend() Function
This method is used to append another list or iterable object at the end of the list.
Syntax:-
list_name.extend(lst)
Ex:-
#extend() Method
a = [10, 20, 30, 10, 90, 'Security']
b = [100, 200, 300]
print("Before Extend:",a)
a.extend(b)
print("After Extend:",a)
for element in a:
print(element)
count() Function
This method returns number of occurrence of a specified element in the list.
Syntax:-
list_name.count(specified_element)
Ex:-
#count() Method
a = [10, 20, 30, 10, 90, 'Security']
num = a.count(10)
print(num)
sort() Function
This method is used to sort the elements of the list into ascending order.
Syntax:-
list_name.sort()
Ex:-
#sort() Method
a = [10, 5, 90, 10, 30]
print("Before Sort",a)
a.sort()
print("After Sort",a)
for element in a:
55
print(element)
clear() Function
This method is used to delete all the elements from the list
Syntax:-
list_name.clear()
Ex:-
#clear() Method
a = [10, 5, 90, 10, 30]
print("Before Clear”, a)
a.clear()
print("After Clear”, a)
Slicing on List
Slicing on list can be used to retrieve a piece of the list that contains a group of
elements. Slicing is useful to retrieve a range of elements.
Ex:-
x = [101, 102, 103, 104, 105, 106, 107]
print("Original List")
n = len(x)
for i in range(n):
print(i, "=", x[i])
print()
print("Last 4 Elements")
d = x[-4:]
for i in d:
print(i)
print()
56
f = x[-5:-3]
for i in f:
print(i)
List Concatenation
Ex:-
a = [10, 20, 30]
b = [1, 2, 3]
result = a + b
print(result)
Ex:-
a = [10, 20, 30]
b = [1, 2, 3]
c = [101, 102, 103]
print(a)
print(b)
print(c)
result = a + b + c
print(result)
Repetition of list
Ex:-
a = [1, 2, 3]
print(a)result = a * 3 print(result)
57
Nested list
A list within another list is called as nested list or nesting of a list.
Ex:-
a = [10, 20, 30, [50, 60]]
b = [50, 60]
a = [10, 20, 30, b]
Ex:-
# Nested List
# Example 1
a = [10, 20, 30, [50, 60]]
print(a)
print(a[0])
print(a[1])
print(a[2])
print(a[3])
print(a[3][0])
print(a[3][1])
# Example 2
b = [50, 60]
a = [10, 20, 30, b]
print("A:",a)
print("B:",b)
print(a[0])
print(a[1])
print(a[2])
print(a[3])
print(a[3][0])
print(a[3][1])
58
Tuple Data Structure
Syntax:- tuple_name = ()
Ex:- a = ()
Creating Tuple
We can create tuple by writing elements separated by commas inside parentheses.
With one Element
b = 10,
c = (10,)
c = (10) int
Ex:-
d = (10, 20, 30, 40)
59
e = (10, 20, -50, 21.3, ‘Security’)
f = 10, 20, -50, 21.3, ‘Security’
Index() method
An index represents the position number of an tuple’s element. The index start from 0
on wards and written inside square braces.
60
for element in a:
print(element)
print()
# With Index
print("Access With Index")
n = len(a)
for i in range(n):
print(i, a[i])
print(a[i])
i+=1
61
Ex:-
# Access Tuple using while Loop
a = (10, 21.3, 'Security')
n = len(a)
i = 0
while i<n:
print(a[i])
i+=1
Slicing on Tuple
Slicing on tuple can be used to retrieve a piece of the tuple that contains a group of
elements. Slicing is useful to retrieve a range of elements.
Syntax:-
new_tuple_name = tuple_name[start:stop:stepsize]
Ex:-
x = (101, 102, 103, 104, 105, 106, 107)
print("Original Tuple")
n = len(x)
for i in range(n):
print(i, "=", x[i])
print()
print("Last 4 Elements")
d = x[-4:]
62
for i in d:
print(i)print()
print(i)
print()
print("Last 5 Elements with [-5-(-3)]= 2 elements towards right")
f = x[-5:-3]
for i in f:
print(i)
Tuple Concatenation
Ex:-
a = (10, 20, 30)
b = (1, 2, 3)
c = (101, 102, 103)
print(a)
print(b)
print(c)
result = a + b + c
print(result)
63
Delete tuple
Ex:-
# Deleting Tuple
a = (10, 20, -50, 21.3, 'Security')
b=del a
print(b)
print()
Repetition of Tuple
sorted() Function
To sort elements based on default natural sorting order
Ex:-
t=(40,10,30,20)
t1=sorted(t)
print(t1)
print(t)
64
min() and max() functions:
These functions return min and max values according to default natural sorting order.
Eg:
t=(40,10,30,20) Output:-
print(min(t)) [10, 20, 30, 40]
print(max(t)) (40, 10, 30, 20)
1.If we want to represent a group of unique values as a single entity then we should go
for set.
2.Duplicates are not allowed.
3.Insertion order is not preserved.But we can sort the elements.
4.Indexing and slicing not allowed for the set.
5.Heterogeneous elements are allowed.
6.Set objects are mutable i.e. once we creates set object we can perform any changes in
that object based on our requirement.
7.We can represent set elements within curly braces and with comma seperation
8.We can apply mathematical operations like union,intersection,difference etc on set
objects.
Creating a Set
A set is created by placing all the items (elements) inside curly braces {}, separated by
comma. A set does not accept duplicate elements.
Elements can be of different types except mutable element, like list, set or dictionary.
Ex:-
a = {10, 20, 30}
a = {10, 20, 30, “Security”, “Raj”, 40}
a = {10, 20, 30, “Security”, “Raj”, 40, 10, 20}
65
Ex:-
#Cretaing Set with elements
a = {10, 20, 'Security', 'Raj', 40}
print(a)
Accessing elements
Ex:-
# Access Set using for loop
#Cretaing Set with elements
a = {10, 20, 'Security', 'Raj', 40}
for i in a:
print(i)
Eg
s = {10,20,30,40} Output
print(s) {40,10,20,30}
print(type(s))
66
We can create set objects by using set() function
s=set(any sequence)
Eg:
l = [10,20,30,40,10,20,10]
s=set(l)
print(s) # {40, 10, 20, 30}
Eg 2:
1.s=set(range(5))
2.print(s)#{0,1,2,3,4}
Note: While creating empty set we have to take special care. Compulsory we should
use set() function.
s={} ==>It is treated as dictionary but not empty set.
Eg:
s=set()
print(s)
print(type(s))
.
Eg:
s={10,20,30}
s.add(40)
print(s) #{40, 10, 20, 30}
67
2.update(x,y,z...):
To add multiple items to the set.
Arguments are not individual elements and these are Iterable objects like
List,range etc. All elements present in the given Iterable objects will be
added to the set.
Ex:-
s={10,20,30}
l=[40,50,60,10]
s.update(l,range(5))
print(s)
3.copy():
Returns copy of the set. It is cloned object.
s={10,20,30}
s1=s.copy()
print(s1)
4.pop():
It removes and returns some random element from the set.
Eg:
68
s={40,10,30,20} Output:-
print(s) {40, 10, 20, 30}
print(s.pop()) 40
print(s) {10, 20, 30}
5.remove(x):
It removes specified element from the set.
If the specified element not present in the Set then we will get KeyError
Ex:-
s={40,10,30,20}
s.remove(30)
print(s) # {40, 10, 20}
s.remove(50) ==>KeyError: 50
6.discard(x):
It removes the specified element from the set.
If the specified element not present in the set then we won't get any error.
Ex:-
s={10,20,30}
s.discard(10)
print(s) ===>{20, 30}
s.discard(50)
print(s) ==>{20, 30}
7.clear():
To remove all elements from the Set.
s={10,20,30} output:-
print(s) {10,20,30}
s.clear() set()
69
Mathematical Operation on the Set
1.union():
x.union(y) ==>We can use this function to return all elements present in both sets
x.union(y) or x|y
Eg:
x={10,20,30,40}
y={30,40,50,60}
print(x.union(y)) #{10, 20, 30, 40, 50, 60}
print(x|y) #{10, 20, 30, 40, 50, 60}
2.intersection():
x.intersection(y) or x&y
Returns common elements present in both x and y
Eg:
x={10,20,30,40}
y={30,40,50,60}
print(x.intersection(y)) #{40, 30}
print(x&y) #{40, 30}
3.difference():
x.difference(y) or x-y returns the elements present in x but not in y
Eg:
x={10,20,30,40}
y={30,40,50,60}
print(x.difference(y)) #{10, 20}
print(x-y) #{10, 20}
70
Membership Operators
(in , not in)
Eg:
s=set("sunil") Output
print(s) {'i', 'n', 's', 'l', 'u'}
print('s' in s) #true True
Output
Enter word to search for vowels: sunil
The different vowel present in sunil are {'i', 'u'}
71
indexing and slicing concepts are not applicable
How to create Dictionary?
d={}
or
Ex:-
d=dict()
we are creating empty dictionary. We can add entries as follows
d[100]="sunil"
d[200]="Ravi"
d[300]="shiva"
print(d) #{100: 'sunil', 200: 'Ravi', 300: 'shiva'}
If the specified key is not available then we will get Key Error print(d[400]) # Key
Error: 400
Q. Write a program to enter name and percentage marks in a dictionary and display
information on the screen
rec={}
n=int(input("Enter number of students: "))
i=1
while i <=n:
name=input("Enter Student Name: ")
marks=input("Enter % of Marks of Student: ")
rec[name]=marks
i=i+1
72
print("Name of Student","\t","% of marks")
for x in rec:
print("\t",x,"\t\t",rec[x])
Output
Enter number of students: 3
Enter Student Name: sunil
Enter % of Marks of Student: 60%
Enter Student Name: Ravi
Enter % of Marks of Student: 70%
Enter Student Name: shiva
Enter % of Marks of Student: 70%
If the key is not available then a new entry will be added to the dictionary with the
specified key-value pair
If the key is already available then old value will be replaced with new value.
Eg :
d={100:"Sunil",200:"ravi",300:"shiva"}
print(d)
d[400]="Pavan"
print(d)
d[100]="sunny"
print(d)
Output
{100: 'Sunil', 200: 'ravi', 300: 'shiva'}
{100: 'sunny', 200: 'ravi', 300: 'shiva', 400: 'Pavan'}
73
How to delete elements from dictionary?
del d[key]
It deletes entry associated with the specified key. If the key is not available then we
will get Key Error Value
Eg:
d={100:"sunil",200:"ravi",300:"shiva"}
print(d)
del d[100] Output
print(d) {100: 'sunil', 200: 'ravi', 300: 'shiva'}
del d[400]
Functions of Dictionary
1. dict():
To create a dictionary
2.len()
Returns the number of items in the dictionary
3.clear():
To remove all elements from the dictionary
4.get():
To get the value associated with the key
d.get()
d[104]
74
If the key is available then returns the corresponding value otherwise returns
None. It won’t raise any error.
d.get(key,defaultvalue)
If the key is available then returns the corresponding value otherwise returns
default
Eg:
d={100:"sunil",200:"ravi",300:"shiva"}
print(d[100]) ==>sunil
print(d[400]) ==>KeyError:400
print(d.get(100)) ==sunil
print(d.get(400)) ==>None
print(d.get(100,"Guest")) ==sunil
print(d.get(400,"Guest")) ==>Guest
3.pop():
d.pop(key)
It removes the entry associated with the specified key and returns the corresponding
value
If the specified key is not available then we will get Key Error
Eg:
d={100:"sunil ",200:"ravi",300:"shiva"}
print(d.pop(100))
print(d)
print(d.pop(400))
sunil
{200: 'ravi', 300: 'shiva'}
Key Error: 400
75
4.popitem():
It removes an arbitrary item(key-value) from the dictionaty and returns it.
Eg:
d={100:"sunil",200:"ravi",300:"shiva"}
print(d.popitem())
print(d)
Output
(300,'shiva')
{100:'sunil', 200: 'ravi'}
If the dictionary is empty then we will get KeyError
d={}
print(d.popitem()) ==>KeyError: 'popitem(): dictionary is empty'
5.keys():
It returns all keys associated with dictionary
Eg:
d={100:"sunil",200:"ravi",300:"shiva"}
print(d.keys()) Output
for k in d.keys(): dict_keys([100,200,300])
print(k) 100
200
300
6.values():
It returns all values associated with the dictionary:
Eg :-
d={100:"sunil",200:"ravi",300:"shiva"} Output
print(d.values())
dict_values([‘sunil’,’ravi’,’shiva’])
76
for v in d.values(): sunil
print(v) ravi
shiva
7.setdefault():
d.setdefault(k,v)
If the key is already available then this function returns the corresponding value.
If the key is not available then the specified key-value will be added as new
item to the dictionary.
Ex:-
d={100:"sunil",200:"ravi"} Output
print(d.setdefault(400,"pavan")) {100: 'sunil', 200: 'ravi', 400: 'pavan'}
print(d) sunil
print(d.setdefault(100,"sunil")) {100: 'sunil', 200: 'ravi',400: 'pavan'}
print(d)
10.update():
d.update(x)
All items present in the dictionary x will be added to dictionary d
Q. Write a program to take dictionary from the keyboard and print the sum of values?
marks[Yes|No]")
if option=="No":
break
print("Thanks for using our application")
Output:-
Functions
Function are subprograms which are used to compute a value or perform a task.
Types of Functions
i) Built in Function Ex:-print(),type(),id() etc
ii) User-defined Function
78
Advantage of Function
.Write once and use it as many time as you need. This provides code resuability.
.Function facilitates easy of code maintenance.
.Divde Large task into many small task so it will help you debug code.
.you can remove or add new feature to a function anytime.
Function Defination.
We can define a function using def keyword by function name with parentheses.
This is also called as Creating a Function,Writing a Function,Defining a Function.
Syntax:
def Function_name():
Local Variable
block of statement
return (variable or expression)
Syntax:-
def Function_name(paral,para2....):
Local Variable
block of statement
return (variable or expression)
Calling Functions
A Function runs only when we call it, function can not run on its own.
Syntax:-
79
Ex: -
add ( )
add (20)
add(10.56)
item(“python”)
Ex:-
# Defining Function one time
def disp():
name = "cybersecurity"
print("Welcome to", name)
# Calling Function as many time as we need
disp()
disp()
80
Actual Argument - Function call arguments are actual arguments
#Example 1
def pw(x, y):
z = x**y
print(z)
pw(5, 2)
#Example 2
def pw(x, y):
z = x**y
print(z)
pw(2, 5)
These arguments are passed to the function with name-value pair so keyword
arguments can identify the formal argument by their names.
81
The keyword argument’s name and formal argument’s name must match.
#Example 1
def show(name, age):
print(f"Name: {name} Age: {age}")
show(name="sam", age=62)
#Example 2
def show(age, name):
print(f"Name: {name} Age: {age}")
show(name="sam",age=62)
Sometime we mention default value to the formal argument in function definition and
we may not required to provide actual argument, In this case default argument will be
used by formal argument.
#Default Arguments
#Example 1
def show(name, age):
print(f"Name: {name} Age: {age}")
show(name="sam", age=62)
#Example 2
def show(name, age=27):
print(f"Name: {name} Age: {age}")
show(name="sam")
Variable length argument is an argument that can accept any number of values.
The variable length argument is written with * symbol.
It stores all the value in a tuple.
#Example 2
def add(*num):
z = num[0]+num[1]+num[2]
print("Addition:", z)
add(5,2,4,5)
Keyword Variable length argument is an argument that can accept any number of
values provided in the form of key-value pair.
The keyword variable length argument is written with ** symbol.
It stores all the value in a dictionary in the form of key-value pair.
Local Variable
The variable which are declared inside a function called as Local Variable.
# Local Variable
# Example 1
def show():
x = 10 # Local Variable
print(x) # Accessing Local Variable inside Function
show()
#Accessing Local Variable outside Function
print(x) # It will show error
83
# Example 2
def add(y):
x = 10 # Local Variable
print(x) # Accessing Local Variable inside Function
print(x+y) # Accessing Local Variable inside Function
add(20)
#Accessing Local Variable outside Function
print(x) # It will show error
Global Variables
# Global Variable
# Example 1
a = 50 # Global Variable
def show():
x = 10 # Local Variable
print(x) # Accessing Local Variable inside Function
print(a) # Accessing Global Variable inside Function
show()
# Accessing Global Variable outside Function
print("Global Variable A:",a)
print(x)
Global Keyword
If local variable and global variable has same name then the function by
default refers to the local variable and ignores the global variable.
It means global variable is not accessible inside the function but possible to
access outside of function.
In this situation, If we need to access global variable inside the function we
can access it using global keyword followed by variable name
#Example 1
a = 50
def show():
84
a = 10
print("A:",a) # It will show local variable value
show()
print("A:",a) # It will show global variable value
Anonymous Functions
Syntax:-
lambda argument_list : expression
Ex:-
lambda x : print(x)
lambda x, y : x + y
85
Python Date & Time
time ( ) Function – This function return the time in seconds since the epoch
as a floating point number. The specific date of the epoch and the handling
of leap seconds is platform dependent.
ctime ( ) Function – This function is used to get current date and time. When
we pass epoch time in seconds to the function, it returns corresponding date
and time in string format. When we do not pass epoch time, it returns current
date and time in string format.
Ex:-
et = ctime(epoch)
print("Epoch Date and Time:", et)
ct = ctime()
print("Current Date and Time:", ctime())
print()
86
ct = ctime()
print("Current Date and Time:", ctime())
print()
# #
stobj = localtime()
print("struct_time Object:", stobj)
# print()
# #
print("Year:", stobj.tm_year)
print("Month:", stobj.tm_mon)
print("Date:", stobj.tm_mday)
print("Hour:", stobj.tm_hour)
print("Minute:", stobj.tm_min)
print("Second:", stobj.tm_sec)
# print()
print(stobj.tm_mday, end="/")
print(stobj.tm_mon, end="/")
print(stobj.tm_year)
print(stobj.tm_hour, end=":")
print(stobj.tm_min, end=":")
print(stobj.tm_sec)
# # print()
Advantages:-
Type of Files
#Ex:-
lst = []
for i in range(4):
name = input('Enter Name :')
lst.append(name)
for i in lst:
print(i)
lst = []
for i in lst:
print(i)
No data in list
f = open('student.txt', mode='w')
f.write('Hello\n')
f.write('Craw Cyber Security \n')
f.write('How are you')
f.close()
print('Writing Success')
Ex:-
Write the data from list to file.
places = []
for i in range(4):
name = input('Enter Name :')
places.append(name)
with open('listfile.txt', 'w') as filehandle:
for listitem in places:
filehandle.write("%s\n" % listitem)
Ex:-
Read the data from list to file.
places = []
with open('listfile.txt', 'r') as filehandle:
filecontents = filehandle.readlines()
for line in filecontents:
current_place = line[:-1]
places.append(current_place)
print(places)
88
Text Mode & Binary Mode
Text Mode – A file opened in text mode, treats its contents as if it contains
text strings of the str type.
When you get data from a text mode file, Python first decodes the raw bytes
Binary Mode – A file opened in Binary Mode, Python uses the data in the
file without any decoding, binary mode file reflects the raw data in the file.
f = open('student.txt', mode='w')
f.write('Hello\n')
f.write('Craw Cyber Security \n')
f.write('How are you')
f.close()
print('Writing Success')
f = open('student.txt', mode='r')
data = f.read()
print(data)
f.close()
f = open('student.txt', mode='rb')
data = f.read()
print(data)
f.close()
Opening a File
If we want to use a file or its data, first we have to open it.
open( ) – Open ( ) function is used to open a file. It returns a pointer to the beginning
of the file. This is called file handler or file object.
f = open('student.txt', mode='r')
print(f)
Closing a File
close( ) – This method is used to close, opened file.
89
Once we close the file, file object is deleted from the memory hence file
will be no longer accessible unless we open it again.
If you don’t explicitly close a file, Python’s garbage collector will eventually
destroy the object and close the open file for you, but the file may stay open
for a while so You
f = open('student.txt')
f.close()
Ex:-
Modules
A module is a file containing Python definitions and statements.
A module is a file containing group of variables, methods, function and classes etc.
They are executed only the first time the module name is encountered in an import
statement.
The file name is the module name with the suffix .py appended.
Ex:- mymodule.py
Type of Modules:-
User-defined Modules
Built-in Modules
Ex:- array, math, numpy, sys
It will not only separate your logics but also help you to debug your code easily as you
know which logic is defined in which module.
When a module is developed, it can be reused in any program that needs that module.
Database.py
calculate.py
search.py
Creating a Module
Database.py def add(a,b):
calculate.py return(a+b)
search.py def sub(a,b): calculate.py
return(a-b)
def add(a,b):
return a+b
def sub(a,b):
return a-b
result.py
Syntax:-
import module_name
import module_name as alias_name
from module_name import f_name as alias_f_name
from module_name import *
Note - Modules can import other modules
import module_name
This does not enter the names of the functions defined in module directly
in the current symbol table; it only enters the module name there.
cal.add(10, 20)
cal.sub(20, 10)
add = cal.add
add(10, 20)
Ex:-#cal.py <--- cal Module
a = 50
def name():
print("From Module cal")
def add(a,b):
return a+b
def sub(a,b):
return a-b
Ex:-
c.add(10, 20)
93
c.sub(20, 10)
add = c.add
add(10, 20)
a = 50
def name():
print("From Module cal")
def add(a,b):
return a+b
def sub(a,b):
return a-b
There is a variant of the import statement that imports names from a module directly
into the importing module’s symbol table.
Ex:- from cal import add, sub
Ex:-
add(10, 20)
sub(20, 10)
a = 50
def name():
94
print("From Module cal")
def add(a,b):
return a+b
def sub(a,b):
return a-b
def add(a,b):
return a+b
def sub(a,b):
return a-b
Packages
Packages are a way of structuring Python’s module namespace by using “dotted
module names”.
A package can have one or more modules which means, a package is collection of
modules and packages.
Creating Package
Package is nothing but a Directory/Folder which MUST contain a special file called
__init__.py.
__init__.py file can be empty, it indicates that the directory it contains is a Python
package, so it can be imported the same way a module can be imported.
96
Create Package
└───SMS
│ cyber.py
│ __init__.py
│
├───Admin
│ │ product.py
│ │ service.py
│ │ __init__.py
│ │
│ ├───Common
│ │ │ footer.py
│ │ │ header.py
│ │ │ __init__.py
│ │ │
│ │ └───__pycache__
│ │ footer.cpython-38.pyc
│ │ header.cpython-38.pyc
│ │ __init__.cpython-38.pyc
│ │
│ └───__pycache__
97
│ product.cpython-38.pyc
│ service.cpython-38.pyc
│ __init__.cpython-38.pyc
│
├───Tech
│ │ profile.py
│ │ work.py
│ │ __init__.py
│ │
│ └───__pycache__
│ profile.cpython-38.pyc
│ work.cpython-38.pyc
│ __init__.cpython-38.pyc
│
└───User
│ profile.py
│ request.py
│ __init__.py
│
└───__pycache__
profile.cpython-38.pyc
request.cpython-38.pyc
__init__.cpython-38.pyc
98
Object Oriented Programming
Class
What is Attribute ?
Attributes are represented by variable that contains data.
What is Method?
Method performs an action or task. It is similar to function.
class Classname(object) :
def __init__(self):
self.variable_name = value
self.variable_name = ‘value’
def method_name(self):
Body of Method
Create Class
class Mobile:
def __init__(self):
self.model = ‘RealMe X’
def show_model (self):
print(‘Model:’, self.model)
99
# Example 1
class Myclass(object):
def show(self):
print("I am a Method")
x = Myclass()
x.show()
# Example 2
class Myclass:
def show(self):
print("I am a Method")
x = Myclass()
x.show()
Object
Object is class type variable or class instance. To use a class, we should create an
object to the class.
Instance creation represents allotting memory necessary to store the actual data of the
variables.
Each time you create an object of a class a copy of each variables defined in the class
is created.
In other words you can say that each object of a class has its own copy of data
members defined in the class.
Syntax: -
object_name = class_name()
object_name = class_name(arg)
# Example 3
class Mobile:
def __init__(self):
self.model = 'RealMe X'
def show_model(self):
print("Model:", self.model)
# Creating Object of Class
realme = Mobile()
# print(realme)
100
# Accessing Variable from outside class
print(realme.model)
# Assign Variable a new value
realme.model='RealMe Pro2'
print(realme.model)
# Accessing Method from outside class
realme.show_model()
# Example 4
class Mobile:
def __init__(self):
self.model = 'RealMe X'
def show_model(self):
price = 100000 # Local Varaible
print("Model:", self.model, "and Price:", price)
realme = Mobile()
# Accessing Method from outside Class
realme.show_model()
# Example 5
class Mobile:
# Constructor
def __init__(self, m):
self.model = m
object_name.variable_name
realme.model
object_name.method_name ( )
realme.show_model ( );
object_name.method_name (parameter_list)
realme.show_model(1000);
101
There are different types of OOPS
Inheritance
Abstraction
Polymorphism
Inheritance
The mechanism of deriving a new class from an old one (existing class) such that the new
class inherit all the members (variables and methods) of old class is called inheritance or
derivation.
Old Class
||
New Class
All classes in python are built from a single super class called ‘object’ so whenever we
create a class in python, object will become super class for them internally.
class Mobile(object):
class Mobile:
The main advantage of inheritance is code reusability.
# Inheritance
class Father: # Parent Class
money = 1000
def show(self):
print("Parent Class Instance Method")
@classmethod
def showmoney(cls):
print("Parent Class Class Method:", cls.money)
@staticmethod
def stat():
a = 10
print("Parent Class Static Method:", a)
102
Abstraction
A class derived from ABC class which belongs to abc module, is known as abstract
class in Python.
ABC Class is known as Meta Class which means a class that defines the behavior of
other classes. So we can say, Meta Class ABC defines that the class which is derived
from it becomes an abstract class.
Abstract Class can have abstract method and concrete methods.
Abstract Class needs to be extended and its method implemented.
PVM can not create objects of an abstract class.
Ex:-
from abc import ABC, abstractmethod
Class Father(ABC):
Ex:-
from abc import ABC, abstractmethod
class Father(ABC):
@abstractmethod
def disp(self): # Abstract Method
pass
Abstract Method
@abstractmethod
def area(self):
pass
def gun(self):
print("Gun = AK47")
class Army(DefenceForce):
def area(self):
print("Army Area = Land", self.id)
class AirForce(DefenceForce):
def area(self):
print("AirForce Area = Sky", self.id)
class Navy(DefenceForce):
def area(self):
print("Navy Area = Sea", self.id)
a = Army()
af = AirForce()
n = Navy()
a.gun()
a.area()
print()
af.gun()
af.area()
print()
n.gun()
n.area()
Polymorphism 104
Polymorphism is a word that came from two greek words, poly means many and
morphos means forms.
If a variable, object or method perform different behavior according to situation, it is
called polymorphism.
Method Overloading
Method Overriding
Ex:-
# Duck Typing
class Duck:
def walk(self):
print("thapak thapak thapak thapak")
class Horse:
def walk(self):
print("tabdak tabdak tabdak tabdak")
class Cat:
def talk(self):
print("Meow Meow")
def myfunction(obj):
obj.walk()
d = Duck()
myfunction(d)
h = Horse()
myfunction(h)
c = Cat()
myfunction(c)
Method Overloading
When more than one method with the same name is defined in the same class, it is
known as method overloading.
In python, If a method is written such that it can perform more than one task, it is
called method overloading.
105
# This Method Overloading Concept is not available in Python
# So it will show error
class Myclass:
def sum(self, a):
print("1st Sum Method", a)
def sum(self):
print("2nd Sum Method")
obj = Myclass()
obj.sum()
obj.sum(10)
Method Overriding
class Add:
def result(self, a, b):
print(“Addition:”, a+b)
class Multi(Add):
def result(self, a, b):
print(“Multiplication:”, a*b)
m = Multi()
m.result(10, 20)
# Method Overriding
class Add:
def result(self, a, b):
print('Addition:', a+b)
class Multi(Add):
def result(self, a, b):
print('Multiplication:', a*b)
m = Multi()
m.result(10, 20)
m = Add()
m.result(10, 20)
106
# Method Call super()
class Add:
def result(self, x, y):
print('Addition:', x+y)
class Multi(Add):
def result(self, a, b):
super().result(10,20)
print('Multiplication:', a*b)
m = Multi()
m.result(10, 20)
Exception Handling
Exception
Type of Exception
Exception Handle
Try – The try block contains code which may cause exceptions.
107
Syntax-
try:
statements
Except – The except block is used to catch an exception that is raised in the
try block. There can be multiple except block for try block.
Syntax-
except ExceptionName:
statements
a = 10
b = 0
d = a/b
print(d)
print('Rest of the Code')
Else – This block will get executed when no exception is raised. Else
block is executed after try block.
Syntax-
else:
statements
Ex:-
a = 10
b = 5
try:
d = a/b
print(d)
print('Inside Try')
108
except ZeroDivisionError:
print('Division by Zero Not allowed')
else:
print('Inside Else')
a = 10
b = 0
try:
d = a/b
print(d)
print('Inside Try')
except ZeroDivisionError as o:
print(o)
print('Rest of the Code')
NameError
a = 10
b = 0
try:
d = a/g
print(d)
a = 10
b = 0
try:
d = a/b
print(d)
109
except (NameError, ZeroDivisionError) as obj:
print(obj)
print('Rest of the Code')
Multithreading
Thread
Thread is a separate flow of execution. Every thread has a task/process
110
Main Thread
When we start any Python Program, one thread begins running immediately, which is
called Main Thread of that program created by PVM.
The main thread is created automatically when your program is started.
import threading
t = threading.current_thread().getName()
print(t)
Ex:-
import threading
t = threading.current_thread().getName()
print(t)
Output
MainThread
Creating a Thread
111
Thread class of threading module is used to create threads. To create our own thread
we need to create an object of Thread Class.
112
Ex-:
Output
Thread Running
Ex:-
Output:-
Thread Running: 10 20
class ChildClassName(Thread):
statements
Thread_object = ChildClassName ()
113
Ex:-
class Mythread(Thread):
pass
t = Mythread()
Ex:-
# Creating a thread by creating a child class to Thread class
# Importing Thread Class from threading Module
from threading import Thread
class Mythread(Thread):
pass
t = Mythread()
print(t.name)
Output
Thread-1
run( ) – Every thread will run this method when thread is started.
We can override this
method and write our own code as body of the method. A thread will terminate
automatically when it comes out of the run( ) Method.
join ( ) – This method is used to wait till the thread completely executes
the run ( ) method.
run()
# Creating a thread by creating a child class to Thread class
# Importing Thread Class from threading Module
from threading import Thread
class Mythread(Thread):
def run(self):
print("Run Method")
t = Mythread()
t.start()
114
join()
# Creating a thread by creating a child class to Thread class
# Importing Thread Class from threading Module
from threading import Thread
class Mythread(Thread):
def run(self):
for i in range(5):
print("Child Thread")
t = Mythread()
t.start()
t.join()
for i in range(5):
print("Main Thread")
Output
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Main Thread
Main Thread
Main Thread
Main Thread
Main Thread
Regular Expression
A regular expression is a special text string for describing a search pattern.
You can think of regular expressions as wildcards on steroids.
You are probably familiar with wildcard notations such as *.txt to find all text files in a
file manager.
Match Function
This function determines if the RE matches at the beginning of the string.
Syntax re.match(pattern,string)
115
pattern : This is the regular expression to be matched.
String: This is the string which would be searched to match the pattern at the
beginning of String
Search Function
Scan through a string,looking for any location where this RE matches.
Syntax : re.search(pattern,string)
pattern : This is the regular expression to be matched.
String: This is the string which would be searched to match the pattern at the
beginning of String
Patterns
Except for control characters,(+ ? . * ^ $ () [] {} | \ ) , all characters match
themselves.
Ex:-
import re
pattern=r"^abc"
myString="abcdef"
print(re.match(pattern,myString))
Output:-
<re.Match object; span=(0, 3), match='abc'>
Ex 2 :-
import re
pattern=r"^abc"
myString="abdef"
print(re.match(pattern,myString))
116
output:-
None
Ex:-1
import re
pattern =r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
email="abc@gmail.com"
rs = re.match(pattern,email)
print(rs)
Output:-
<re.Match object; span=(0, 13), match='abc@gmail.com'>
Ex:-2
import re
pattern =r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
email="abcgmail.com"
rs = re.match(pattern,email)
print(rs)
Output:-
None
Ex:-3
import re
pattern =r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
email="abcgmail.co.in"
rs = re.match(pattern,email)
if rs==None:
print("Email invalid")
else:
print("Email is valid ")
print(rs)
Output:-
117
<re.Match object; span=(0, 15), match='abc@gmail.co.in'>
Tkinter − Tkinter is the Python interface to the Tk GUI toolkit shipped with Python.
We would look this option in this chapter.
There are many other interfaces available, which you can find them on the net.
Tkinter Programming
Tkinter is the standard GUI library for Python. Python when combined with Tkinter
provides a fast and easy way to create GUI applications. Tkinter provides a powerful
object-oriented interface to the Tk GUI toolkit.
Creating a GUI application using Tkinter is an easy task. All you need to do is perform
the following steps −
Tkinter Widgets
1.Button
The Button widget is used to add buttons in a Python application. These buttons can
display text or images that convey the purpose of the buttons. You can attach a
function or a method to a button which is called automatically when you click the
button.
Ex:
import tkinter
import tkinter.messagebox
top = tkinter.Tk()
118
def helloCallBack():
tkinter.messagebox.showinfo( "Hello Python", "Hello World")
B.pack()
top.mainloop()
Checkbutton
Ex:-
from tkinter import *
import tkinter
top = tkinter.Tk()
CheckVar1 = IntVar()
CheckVar2 = IntVar()
C1 = Checkbutton(top, text = "Male", variable = CheckVar1, \
onvalue = 1, offvalue = 0, height=5, \
width = 20)
C2 = Checkbutton(top, text = "Female", variable = CheckVar2, \
onvalue = 1, offvalue = 0, height=5, \
width = 20)
C1.pack()
C2.pack()
top.mainloop()
Entry
The Entry widget is used to accept single-line text strings from a user.
Ex:-
from tkinter import *
top = Tk()
L1 = Label(top, text="User Name")
L1.pack( side = LEFT)
E1 = Entry(top, bd =5)
E1.pack(side = RIGHT)
top.mainloop()
Frame
119
The Frame widget is very important for the process of grouping and
Ex:-
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
root.mainloop()
Listbox
The Listbox widget is used to display a list of items from which a user can select a
number of items.
Ex:-
Label
This widget implements a display box where you can place text or images.
The text displayed by this widget can be updated at any time you want.
Database
Database is integrated collection of related information along with the details so that it
is available to the several user for the different application.
MySQL
CRUD Operations
Create
121
Read
Update
Delete
Requirements
MySQL
It is an open source database management system application which will help us to
manage the database like store and retrieve data.
To work with MySQL in Python program we have to import connector sub module of
mysql module.
import mysql.connector
Creating Connection
Syntax: -
connection_object = connect(user=‘username’, password=‘pass’ host=
‘localhost’, port=3306);
Check Connection
eg:-
import mysql.connector
conn = mysql.connector.connect(user=‘root’, password=‘geek’, host=‘local)
print(conn.is_connected())
Eg:-
import mysql.connector
mydb = mysql.connector.connect(
host = "localhost",
user = "root",
password = "",
database = "pythonDB"
)
if mydb.is_connected():
print("Database Succesfully Connected")
else:
print("Database Not Connected...")
mydb.close()
Close Connection
Operations
1. Create Database
2. Show Database
Connecting Database
connect()– This method is used to open or establish a new connection. It
returns an object representing the connection.
123
Syntax: -
connection_object = connect(user=‘username’, password=‘pass’, database=
‘dbname’, host=‘localhost’, port=3306);
eg: -
import mysql.connector
conn = mysql.connector.connect(user=‘root’, password=‘’,
host=‘localhost’,Connecting to Database
Ex:-
mydb = mysql.connector.connect(
host = "localhost",
user = "root",
password = "",
database = "pythonDB"
)
Show Database
Ex:-
import mysql.connector
mydb = mysql.connector.connect(
host = "localhost",
user = "root",
password = "",
database = "pythonDB"
)
if mydb.is_connected():
print("Database Succesfully Connected")
124
else:
print("Database Not Connected...")
sql = 'SHOW DATABASES'
myc = mydb.cursor()
myc.execute(sql)
for d in myc:
print(d)
myc.close()
mydb.close()
Operations
1. Create Table
2. Show Table
3. Insert Data
4. Delete Data
5. Update Data
Create Table
Ex:-
# Create Table
import mysql.connector
mydb = mysql.connector.connect(
host = "localhost",
user = "root",
password = "",
database = "pythonDB"
)
if mydb.is_connected():
print("Database Succesfully Connected")
else:
print("Database Not Connected...")
sql = 'CREATE TABLE student1(stuid INT AUTO_INCREMENT
PRIMARY KEY, name VARCHAR(20), roll INT, fees FLOAT)'
125
myc = mydb.cursor()
myc.execute(sql)
myc.close()
mydb.close()
mydb.close()
Show Tables:-
# Show Table
import mysql.connector
mydb = mysql.connector.connect(
host = "localhost",
user = "root",
password = "",
database = "pythonDB"
)
if mydb.is_connected():
print("Database Succesfully Connected")
else:
print("Database Not Connected...")
sql = 'SHOW TABLES'
myc = mydb.cursor()
myc.execute(sql)
for t in myc:
print(t)
myc.close()
mydb.close()
Insert Data
# Insert Single Row
import mysql.connector
mydb = mysql.connector.connect(
host = "localhost",
user = "root",
password = "",
database = "pythonDB"
)
if mydb.is_connected():
print("Database Succesfully Connected")
else:
126
print("Database Not Connected...")
sql = 'INSERT INTO student1(name, roll, fees)
VALUES("Sumit", 103, 30000.50)'
myc = mydb.cursor()
try:
myc.execute(sql)
mydb.commit() # Committing the change
print(myc.rowcount, 'Row Inserted')
# Number of Row Inserted
print(f'Stu ID: {myc.lastrowid} Inserted')
# Last inserted ID
except:
mydb.rollback() # Rollback the change
print('Unable to Insert Data')
myc.close() # Close Cursor
mydb.close() # Close Connection
Delete Data
Ex1:-
# Delete Row
import mysql.connector
mydb = mysql.connector.connect(
host = "localhost",
user = "root",
password = "",
database = "pythonDB"
)
if mydb.is_connected():
print("Database Succesfully Connected")
else:
print("Database Not Connected...")
sql = 'DELETE FROM student1 WHERE stuid=3'
myc = mydb.cursor()
try:
myc.execute(sql)
mydb.commit() # Committing the change
print(myc.rowcount, 'Row Deleted')
except:
mydb.rollback() # Rollback the change
print('Unable to Delete Data')
myc.close() # Close Cursor
mydb.close() # Close Connection
128
Update Row
Ex1:-
# Update Row
import mysql.connector
mydb = mysql.connector.connect(
host = "localhost",
user = "root",
password = "",
database = "pythonDB"
)
if mydb.is_connected():
print("Database Succesfully Connected")
else:
print("Database Not Connected...")
sql = 'UPDATE student1 SET fees=200 WHERE stuid=4'
myc = mydb.cursor()
try:
myc.execute(sql)
mydb.commit() # Committing the change
print(myc.rowcount, 'Row Updated')
except:
mydb.rollback() # Rollback the change
print('Unable to Update Data')
myc.close() # Close Cursor
mydb.close() # Close Connection
129
host = "localhost",
user = "root",
password = "",
database = "pythonDB"
)
if mydb.is_connected():
print("Database Succesfully Connected")
else:
print("Database Not Connected...")
sql = 'SELECT * FROM student1'
myc = mydb.cursor()
try:
myc.execute(sql)
rows = myc.fetchall()
for r in rows:
print(r)
print('Total Rows:',myc.rowcount)
except:
print('Unable to Retrieve Data')
myc.close() # Close Cursor
mydb.close() # Close Connection
130
message = "Hey this was sent using python"
server =smtplib.SMTP('smtp.gmail.com',587)
server.starttls()
server.login(sender_email)
print("Login success ")
server.sendmail(sender_email,rec_email,message)
print("Email has been sent to ",rec_email)
Data Science
1.Numpy
What is NumPy?
NumPy is a Python library used for working with arrays.
It also has functions for working in domain of linear algebra, Fourier transform, and
matrices.
NumPy stands for Numerical Python.
Ex
import numpy
arr = numpy.array([1, 2, 3, 4, 5])
print(arr)
Output
[1, 2, 3, 4, 5]
131
Pandas
What is Pandas?
Pandas is a Python library used for working with data sets. It has
functions for analyzing, cleaning, exploring, and manipulating data.
The name "Pandas" has a reference to both "Panel Data", and
"Python Data Analysis" and was created by Wes McKinney in 2008.
Ex:-
import pandas as pd
mydataset = {
'cars': ["BMW", "Volvo", "Ford"],
'passings': [3, 7, 2]
}
myvar = pd.DataFrame(mydataset)
print(myvar)
Output
0 BMW 3
1 Volvo 7
2 Ford 2
Matplotlib
What is Matplotlib?
Matplotlib is a low level graph plotting library in python that serves as a
visualization utility.
Matplotlib was created by John D. Hunter.
Matplotlib is open source and we can use it freely.
Matplotlib is mostly written in python, a few segments are written in C,
Objective-C and JavaScript for Platform compatibility.
132
Ex:-
#Three lines to make our compiler able to draw:
import sys
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
xpoints = np.array([0, 6])
ypoints = np.array([0, 250])
plt.plot(xpoints, ypoints)
plt.show()
#Two lines to make our compiler able to draw:
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()
Output:-
133
Machine Learning
Role of ML
Image Recognition
Speech Recognition
Google Assistance
Ex:-
from scipy import stats
speed = [99,86,87,88,111,86,103,87,94,78,77,85,86]
x = stats.mode(speed)
print(x)
Output:
ModeResult(mode=array([86]), count=array([3]))
Artificial Intelligence
KEYS
Artificial intelligence refers to the simulation of human intelligence in
machines. The goals of artificial intelligence include learning, reasoning,
and perception. AI is being used across different industries including
finance and healthcare.
Weak AI tends to be simple and single-task oriented, while strong AI
carries on tasks that are more complex and human-like.
135