0% found this document useful (0 votes)
2 views

Python Book Pages (1)

The document outlines a comprehensive agenda for learning Python, covering topics from language fundamentals to advanced concepts like machine learning and artificial intelligence. It includes details on Python's history, features, data types, operators, and various programming constructs. Additionally, it emphasizes Python's versatility and suitability for beginners as well as its applications in diverse fields.

Uploaded by

Hex39
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python Book Pages (1)

The document outlines a comprehensive agenda for learning Python, covering topics from language fundamentals to advanced concepts like machine learning and artificial intelligence. It includes details on Python's history, features, data types, operators, and various programming constructs. Additionally, it emphasizes Python's versatility and suitability for beginners as well as its applications in diverse fields.

Uploaded by

Hex39
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 135

Python Agendas

01) Language Fundamentals


02) Python Variables & Data Types / Identifiers
03) Reserved Words
04) Python Data Type Casting
05) Operators
06) Input and Output Statements
07) Flow Control Statements
08) Python Loop Concepts
09) Python Arrays
10) Strings
11) List Data Structure
12) Tuple Data Structure
13) Set Data Structure
14) Dictionary Data Structure
15) Functions
16) Python Date & Time
17) File Handling (Input & Output)
18) Modules
19) Packages
20) Oops
21) Exception Handling
22) Multithreading
23) Regular Expression
24) Graphical User Interface
25) Python Database connection
26) Python Mail Sending Program
27) Data Science
28) Machine Learning
29) Artificial Intelligence

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.

Where we can use Python:


We can use everywhere. The most common important application areas are
1. For developing Desktop Applications
2. For developing web Applications
3. For developing database Applications
4. For Network Programming
5. For developing games
6. For Data Analysis Applications
7. For Machine Learning
8. For developing Artificial Intelligence Applications
9. For IOT Internet of T

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:

Python 1.0V introduced in Jan 1994


Python 2.0V introduced in October 2000
Python 3.0V introduced in December 2008

Current Versions:

Python 3.9.1 Introduced in December 2020


Python 3.9.0 Python 3.9.2
Python 3.9.2 Introduced in February 27, 2021

2) Python Variables & Data Types / Identifiers

A name in Python program is called identifier.


It can be class name or function name or module name or variable name.
Ex  a=10

 Rules to define identifiers in Python:

1. The only allowed characters in Python are


• Alphabet symbols (either lower case or upper case)
• Digits (0 to 9)
• underscore symbol ( _ )

By mistake if we are using any other symbol like $ then we will get
syntax error.
• Cash = 10 √
• Cash = 20 x

3
2. Identifier should not starts with digit
• 123total x
• otal123 √

3. Identifiers are case sensitive of course Python language is case sensitive


Language.
• Total =10
• TOTAL=999
• Print (total) #10
• Print (TOTAL) #999

Identifier:

1. Alphabet Symbols (Either Upper case OR Lower case)


2. If Identifier is start with Underscore (_) then it indicates it is private.
3. Identifier should not start with Digits.
4. Identifiers are case sensitive.
5. We cannot use reserved words as identifiers Eg: def = 10 x
6.There is no length limit for Python identifiers. But not recommended
to use too lengthy identifiers.
7. Dollar ($) Symbol is not allowed in Python.

Q. Which of the following are valid Python identifiers?


1) 123 total x
2) Total 123 √
3) Java 2 share √
4) Cash x
5) Abc_abc_ √
6) Def x
7) If x

4
3) Reserved Words in Python

In Python some words are reserved to represent some meaning or functionality.


Such type of words are called Reserved words.

There are 33 reserved words available in Python.


• True, False, None
• And, or, not, is
• if, elif, else
• While, for, break, continue, return, in, yield
• Try, except, finally, raise, assert
• Import, from, as, class, def, pass, global, nonlocal, lambda
del, with

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

Data Type represent the type of data present inside a variable.


In Python we are not required to specify the type explicitly. Based on value
Provided, the type will be assigned automatically. Hence Python is
Dynamically typed Language.

Python contains the following inbuilt data types


1. Int 2. Float 3. Bool 4. str 5. Range 6. List 7. Tuple 8. Set 9. dict

Note: Python contains several inbuilt functions


1. Type () to check the type of variable
2. Print () to print the value //// In Python everything is object

1) Int Data Type:

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.

2) Float Data Type:

We can use float data type to represent floating point values (decimal values)
Eg: f=1.234
Type (f) float

We can also represent floating point values by using exponential form


(Scientific notation).

3) Bool Data Type:

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:

str represents String data type.


A String is a sequence of characters enclosed within single quotes or double
quotes. s1='Karan' s1="Sam"
By using single quotes or double quotes we cannot represent multi line string
literals. s1="Karan Sharma"

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

5) Range Data Type:

Range Data Type represents a sequence of numbers.


The elements present in range Data type are not modifiable. i.e range Data type is
immutable
Form-1: Range (10) generate numbers from 0 to 9
Eg:
r=range(10)
for i in r :

print(i)

8
Output ==> 0 to 9

Form-2: Range (10,20) generate numbers from 10 to 19


Eg:

r = range(10,20)
for i in r :
print(i)

Output ==> 10 to 19

Form-3: Range(10,20,2) 2 means increment value


r = range(10,20,2)
for i in r :
print(i)

Output ==> 10,12,14,16,18

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]

6) Range Data Type:


If we want to represent a group of individual objects as a single entity where
Insertion order preserved and duplicates are allowed, then we should go for List.

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

7) Tuple Data Type

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’

e = (10, 20, -50, 21.3, 'Security')


print(e)
# accessing element using index
print(e[2])
Output (10, 20, -50, 21.3, 'Security')
-50

10
8) Set Data Type:

If we want to represent a group of values without duplicates where order is not


important then we should go for set Data Type.
1. Insertion order is not preserved
2. Duplicates are not allowed
3. Heterogeneous objects are allowed
4. Index concept is not applicable
5. It is mutable collection

s={100,0,10,200,10,'Name'}
print(s) # {0, 100, 'Name', 200, 10}
print(s[0]) ==>TypeError: 'set' object does not support
indexing

*set is growable in nature, based on our requirement we can increase or decrease


the size.
s.add(60)
s
{0, 100, 'Name', 200, 10, 60}
s.remove(100)
s
{0, 'Name', 200, 10, 60

9) dict Data Type:

If we want to represent a group of values as key-value pairs then we should


go for dict data type.
Duplicate keys are not allowed but values can be duplicated. If we are trying to
insert an entry with duplicate key then old value will be replaced with new value.

Eg: d = {101: 'sunil', 102: 'ravi', 103: 'shiva'}


print(d)

Output => {101: 'sunil', 102: 'ravi', 103: 'shiva'}

11
d1 = {}
d1['a'] = 'apple'
d1['ab'] = 'Ball'
d1['abc'] = 'cat'
print(d1)

Output==> {'a': 'apple', 'ab': 'Ball', 'abc': 'cat'}

Note: dict is mutable and the order wont be preserved.


Note:
1. In general we can use bytes and byte array data types to represent binary
information like images, video files etc
2. In Python2 long data type is available. But in Python3 it is not available and
we can represent long values also by using int type only.
3. In Python there is no char data type. Hence we can represent char values also
by using str type.

4) Python Data Type Casting

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")

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


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

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

Operator is a symbol that performs certain operations. Python provides


the following set of operators
1. Arithmetic Operators
2. Relational Operators or Comparison Operators
3. Logical operators
13
4. Bitwise operators
5. Assignment operators
6. Special operators

1. Arithmetic Operators:
+ ==>Addition
- ==>Subtraction
* ==>Multiplication
/ ==>Division operator
% ===>Modulas operator
// ==>Floor Division operator

** ==>Exponent operator or power operator Eg: test.py:


a=10
b=2
print('a+b=',a+b) // a+b= 12
print('a-b=',a-b) // a-b= 8
print('a*b=',a*b) // a*b= 20
print('a/b=',a/b) // a/b= 5.0
print('a//b=',a//b) // a//b= 5
print('a%b=',a%b) // a%b= 0
print('a**b=',a**b) // a**b= 100

Relational Operators or Comparison Operators

>, >=, <, <=

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')

TypeError: '>' not supported between instances of


'int' and 'str'

Eg: a=10 b=20


if(a>b):.
print("a is greater than b")
else:
print("a is not greater than b")
Output==> a is not greater than b

Note: Chaining of relational operators is possible. In the chaining, if all


comparisons returns True then only result is True. If atleast one comparison
returns False then the result is False
Eg:
10<20 ==>True
10<20<30 ==>True
10<20<30<40 ==>True
10>20<30<40>50 ==>False

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

Note: Chaining concept is applicable for equality operators. If at least one


comparison returns False then the result is False. Otherwise the result is true.
Eg: 10==20==30==40
False
10==10==10==10
True

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

not ==> Complement


True and False ==>False Ex: x = 5
True or False ===>True print (x > 3 and x < 10)
True
not False ==>True

Ex: x = 5

16
print (x > 3 or x < 4)

Ex: x = 5
print (not(x > 3 and x < 10))

Bitwise Operators:

We can apply these operators bitwise.


These operators are applicable only for int and Boolean types.
By mistake if we are trying to apply for any other type then we will get Error.

&, |, ^, ~, <<, >>


Print (4&5) ==> valid
Print (10.5 & 5.6) ==>
TypeError: unsupported operand type(s) for &: 'float' and 'float'
Print (True & True) ==> valid

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

Print (4&5) ==> 4


Print (4|5) ==> 5
Print (4^5) ==> 1

17
Shift Operators:

<< Left shift operator


After shifting the empty cells we have to fill with zero
Print (10<<2) ==> 40

>> Right Shift operator


After shifting the empty cells we have to fill with sign bit.( 0 for +ve and 1 for -ve)
Print (10>>2) ==>2

We can apply bitwise operators for Boolean types also


Print (True & False) ==>False
Print (True | False) ===>True
Print (True ^ False) ==>True
Print (~True)==>-2
Print (True<<2) ==>4
Print (True>>2) ==>0

18
Assignment Operators:

We can use assignment operator to assign value to the variable.


Eg: x=10
We can combine assignment operator with some other operator to form compound
assignment operator.

Eg: x+=10====> x = x+10


x =10
x = x+10
x+=20
Print (x)

The following is the list of all possible compound assignment operators


in Python
+=, -=, *=, /=, %=, //=, **= &=, |=, ^=, >>=, <<=
Eg: x=10
x+=20 ==> x =x+20
Print (x) ==>30

Special operators:

Python defines the following 2 special operators


1. Identity Operators
2. Membership operators

1) Identity Operators

We can use identity operators for address comparison. If 2 identity operators are
available
1. is 2. is not

Eg: a=10 b=10


print (a is b) //True
19
Eg : a="durga"
x=True
y=True b="durga"
print( x is y) //True print (id(a))
print (id(b))
print (a is b)

Eg: list1 = ["one","two","three"]


list2=["one","two","three"]
print(id(list1))
print(id(list2))

print(list1 is list2) #False


print(list1 is not list2) #True
print(list1 == list2) #True

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)

in  Returns True if the given object present in the specified Collection


not in  Returns True if the given object not present in the specified Collection

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

Reading dynamic input from the keyboard:


In Python 2 the following 2 functions are available to read dynamic input
from the keyboard.
1.raw_input ()
2.input ()

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.

Eg: x = raw_input ("Enter First Number:")


print(type(x)) It will always print str type only for any input type only this
output 2.0

2. Input ():

input() function can be used to read data directly in our required format. We
are not required to perform type casting.

X = input ("Enter Value)


type (x)
10 ===> int
"sunil"===>str
10.5===>float
True==>bool

***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.

x=input("Enter The First Number")


y=input("Enter The Secont Number")
i=int (x)
j=int (y)
z = i+j
print ("The sum of two Numbers" ,z)
x=int (input ("Enter The First Number"))
y=int (input ("Enter The Secont Number"))
z = x+y
print("The sum of two Numbers" ,z)

Q. Write a program to read Employee data from the keyboard and print that data.

Eno = int (input ("Enter Employee No:"))


Ename = Input ("Enter Employee Name:")
Esal = float(input("Enter Employee Salary:"))
Eaddr = input("Enter Employee Address:")
Married = bool(input("Employee Married ? [True | False]:"))
Print ("Please Confirm Information")
Print ("Employee No :",eno)
Print ("Employee Name :",ename)
Print ("Employee Salary :",esal)
Print ("Employee Address :",eaddr)
Print ("Employee Married ? :",married)

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 Function take a String and evaluate the Result.


Eg: x = eval (“10+20+30”)
Print (x)
Output: 60

Eg: x = eval (input (“Enter Expression”))


Enter Expression: 10+2*3/4
Output 11.5

Eval () can evaluate the Input to list, tuple, set, etc based the provided Input.

Eg: l = eval (input ('Enter List'))


Print (type (l))
Print (l)

Output Statements:

We can use print() function to display output.


Form-1: print () without any argument Just it prints new line character
Form-2:
#print(String):
print("Hello World")
#We can use escape characters also
print("Hello \n World")
print("Hello \t World")
#We can use repetetion operator (*) in the string
print(10*"Hello")
print("Hello"*10)
#We can use + operator also
print("Hello"+"World")
23
Note:
If both arguments are String type then + operator acts as concatenation operator.
If one argument is string type and second is any other type like int then we will
get Error If both arguments are number type then + operator acts as arithmetic
addition operator.

Note:
Print ("Hello"+"World")
Print ("Hello","World")
Output
HelloWorld

By default output values are seperated by space.If we want we can specify


seperator by using "sep" attribute

a,b,c=10,20,30 output:-
print(a,b,c,sep=',') 10,20,30
print(a,b,c,sep=':') 10:20:30

Form-4: print () with end attribute: Output:


Print ("Hello") Hello
Print ("Craw") Craw
Print ("Cyber") Cyber
Print ("Security") Security

If we want output in the same line with space


Print ("Hello",end=' ')
Print ("Craw", end=' ')
Print ("Cyber",end=' ')

OutPut ==> Hello Craw Cyber Security

Form-5: print (String,variable list):


We can use print() statement with String and any number of arguments.

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

7) Flow Control Statements

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

if condition is true then Action-1 will be executed otherwise Action-2 will


be executed.
Eg: 3
Name = input("Enter Name:") output
if name == "Name" : Enter Name : Sunil
print ("Hello Name Good Morning") Hello sunil good morning
else: How are you
print ("Hello Guest Good Moring")
print("How are you!!!")
26
3) if-elif-else:
Syntax:

if condition1: lif condition3:


Action-1 Action-3
elif condition2: elif condition4:
Action-2 Action-4
else:
Default Action
Based condition the corresponding action will be executed.

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

Enter a digit from o to 9:11


Please Enter The Digit From 0 to 9

Python Loop Statement

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

Eg 2: To print characters present in string index wise:


S = input ("Enter some String: ")
I=0
for x in s :
print ("The character present at ",i,"index is :",x)
I = i+1

Output ==>
Enter some String: Name
The character present at 0 index is : s

Eg 3: To print Hello 10 times


Eg 4: To display numbers from 0 to 10
for x in range(10) :
print("Hello") for x in range(10) :
print(x)

Eg 5: To display odd numbers from 0 to 20


for x in range(21):
if (x%2==0):
print(x)

Eg 6: To display numbers from 10 to 1 in descending order


for x in range(10,0,-1) :
print (x)
30
Eg 7: To print sum of numbers presents inside list

List = eval ("Enter List") Output ==>


sum = 0 Enter List 1,3,4,5,6
for x in list:
sum = sum+x The Sum Of = 19
print ("The Sum Of =",sum)

Ex:- st = 'python' Output:-


N = len (st) 0=S
for i in range(n): 1= a
print (i,'=',st[i]) 2=m
print ('Rest of the code')

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

Eg: To display the sum of first n numbers


N=5
Sum = 0
I=1
while I <= n:
sum = nam+i
I = i+e
Print ("The sum of first",n,"numbers is :",sum)

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")

Nested For Loop:


Sometimes we can take a loop inside another loop, which are also known as nested
loops.
Ex:-
for i in range(2):
print("Outer Loop",i)
for j in range(3):
print("Inner Loop",j)
print("Rest of the code")

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

Outer Loop 3 Outer Loop 4


Inner Loop Inner Loop
Inner Loop Inner Loop
Inner Loop Inner Loop
Inner Loop Inner Loop

Q. Write a program to display * 's in Right angled triangled form


*
**
***
****

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

.Arrays can store only one type of data.


.In Python, The size of array is not fixed. Array can increase or decrease their size
dynamically.
.Array and List are not same.
.Array uses less memory than List.

# Create Array Example 1


import array
stu_roll = array.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])

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])

# Create Array Example 3


from array import *
stu_roll = 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])

# Create Array Example 4


from array import *
stu_roll = array('f', [10, 20, 10.3, 40, 1.5])
print(stu_roll[0])
print(stu_roll[1])
print(stu_roll[2])
print(stu_roll[3])
print(stu_roll[4])

# Create Array and iterate using for Loop


from array import *
stu_roll = array('i', [101, 102, 103, 104, 105])
for element in stu_roll:
print(element)

# Create Array and iterate using for Loop with index

from array import *


stu_roll = array('i', [101, 102, 103, 104, 105])
n = len(stu_roll)
for i in range(n):
print(i, "=", stu_roll[i])

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

How to define multi-line String literals:


We can define multi-line String literals by using triple single or double triple quotes.

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

How to access characters of a String:


We can access characters of a string by using the following ways.

1.By using index


2.By using slice operator

1.By using index:

Python supports both +ve and -ve index.


+ve index means left to right(Forward direction) +tv
-ve index means right to left(Backward direction) –tv

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:

Enter Some String: sunil


The character present at positive index 0 and at negatives index -5 is s
The character present at positive index 1 and at negatives index -4 is u
The character present at positive index 2 and at negatives index -3 is n
The character present at positive index 3 and at negatives index -2 is i
The character present at positive index 4 and at negatives index -1 is l

2.Accessing characters by using slice operator:

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]

Behaviour of slice operator:


s[Begin: end: step]
step value can be either +ve or –ve

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:

default value for Begin: -1


default value for end: -(length of string+1)
Note: Either forward or backward direction, we can take both +ve and -ve values for
begin and end index.
41
Mathematical Operators for String:
We can apply the following mathematical operators for Strings.
1. + operator for concatenation
2. * operator for repetition
Ex:-
print("craw"+"cyber") #crawcyber
print("craw"*2) # crawcraw

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

len() in-built function:


We can use len() function to find the number of characters present in the string.
Eg:
s='sunil'
print(len(s)) #5

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

Removing spaces from the string:


We can use the following 3 methods
1.strip () ==>To remove spaces both sides

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")

Enter your city Name: Hyderabad


Hello Hyderabad..Adab

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.

1.s.count(substring) ==> It will search through out the string


2.s.count(substring, Start, end) ===> It will search from bEgin index to end-1 index

Eg:
s="abcabcabcabcadda" Output:
print(s.count('a')) 6
print(s.count('ab')) 4
print(s.count('a',3,7)) 4

Replacing a string with another string:


syntax:
s.replace(oldstring,newstring)
inside s, every occurrence of oldstring will be replaced with nesting.

Eg1:
s="Learning Python is very difficult"
s1=s.replace("difficult”, “easy")
print(s1)
Output:
Learning Python is very easy

Eg2: All occurrences will be replaced


s="ababababababab"
s1=s.replace("a","b") Output: bbbbbbbbbbbbbb
print(s1)

46
Splitting of Strings:

We can split the given string according to specified seperator by using


split() method.
syntax
l=s.split(seperator)
The default seperator is space. The return type of split() method is List

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

Changing case of a String:


We can change case of a string by using the following 5 methods.

1.upper()===>To convert all characters to upper case


2.lower() ===>To convert all characters to lower case
3.swapcase()===>converts all lower case characters to upper case and all upper case
characters to lower case
4.title() ===>To convert all character to title case. i.e first character in every word
should be upper case and all remaining characters should be in lower case.
5.capitalize() ==>Only first character will be converted to upper case and all remaining
characters can be converted to lower case

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

Formatting the Strings:

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

If we want to represent a group of individual objects as a single entity where insertion


order preserved and duplicates are allowed, then we should go for List.
insertion order preserved. duplicate objects are allowed heterogeneous objects are
allowed.
List is dynamic because based on our requirement we can increase the size and
decrease the size.
In List the elements will be placed within square brackets and with comma seperator.

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

[10,"A","B",20, 30, 10]

List objects are mutable we can change the content.


Creation of List Objects:
1.We can create empty list object as follows...
1)list=[]
2)print(list)
3)print(type(list))

2.If we know elements already then we can create list as follows


list=[10,20,30,40]

3.With dynamic input:

50
list=eval(input("Enter List:"))
print(list)
print(type(list))

Accessing using while loop


# Accessing List using while loop
a = [10, 20, -50, 21.3, 'Cybersecurity']
print("Accessing List using while Loop")
n = len(a)
i = 0
while i < n:
print(i, "=", a[i])
i+=1

1)Deletion
del statement is used to delete an element of list or we can delete entire list using del
statement.

a = [10, 20, -50, 21.3, ‘Cybersecurity’]


Deleting Element
del a[2]
Deleting Entire List
del a

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)

Getting User input


a = []
n = int(input("Enter Number of Elements: "))
for i in range(n):
a.append(int(input("Enter 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))

# Creating list using list Function and range function


b = list(range(0, 5))
print(b)
print(type(b))

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("From 0th Position to last Position")


b = x[0:]
for i in b:
print(i)
print()

print("Last 4 Elements")
d = x[-4:]
for i in d:
print(i)
print()

print("Last 5 Elements with [-5-(-3)]= 2 elements towards right")

56
f = x[-5:-3]
for i in f:
print(i)

List Concatenation

+ operator is used to do concatenation the list.

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

* Operator is used to repeat the elements of list.


Ex:-
b = [1, 2, 3]
result = b * 3
print(result)

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

1.Tuple is exactly same as List except that it is immutable. i.e., once we


create Tuple
object, we cannot perform any changes in that object.
Hence Tuple is Read Only version of List.
2.If our data is fixed and never changes then we should go for Tuple.
3.Insertion Order is preserved
4.Duplicates are allowed
5.Heterogeneous objects are allowed.
6.We can preserve insertion order and we can differentiate duplicate objects
by using index. Hence index will play very important role in Tuple also.
7.We can represent Tuple elements within Parenthesis and with comma
seperator. Parenthesis are optional but recommended to use.

Creating Empty Tuple

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

With Multiple Elements

Ex:-
d = (10, 20, 30, 40)
59
e = (10, 20, -50, 21.3, ‘Security’)
f = 10, 20, -50, 21.3, ‘Security’

# Creating Tuple with Multiple element


d = (10, 20, 30, 40)
e = (10, 20, -50, 21.3, 'Security')
f = 10, 20, -50, 21.3, 'Security' # tuple e and f are same
print()
# Access using index
print("Accessing Tuple d:")
print("d[0] =", d[0])
print("d[1] =", d[1])
print("d[2] =", d[2])
print("d[3] =", d[3])
print()

print("Accessing Tuple e:")


print("e[0] =", e[0])
print("e[1] =", e[1])
print("e[2] =", e[2])
print("e[3] =", e[3])
print("e[4] =", e[4])
print()

print("Accessing Tuple f:")


print("f[0] =", f[0])
print("f[1] =", f[1])
print("f[2] =", f[2])
print("f[3] =", f[3])
print("f[4] =", f[4])

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.

Ex:- a = (10, 20, -50, 21.3, ‘Security’)


# Access Tuple using for Loop
a = (10, 21.3, 'Security')
# Without Index
print("Access Without Index")

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])

Accessing using for loop

a = (10, 20, -50, 21.3, ‘Security’)


Without index
for element in a:
print(element)
With index
n = len(a)
for i in range(n):
print(a[i])
Ex:-
print("Access With Index")
n = len(a)
for i in range(n):
print(i, a[i])

Accessing using while loop


a = (10, 20, -50, 21.3, ‘Security’)
n = len(a)
i=0
while i < n :

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("From 1st Position to 4th Position")


a = x[1:5]
for i in a:
print(i)
print()

print("From 0th Position to last Position")


b = x[0:]
for i in b:
print(i)
print()

print("From 0th Position to 4th Position")


c = x[:5]
for i in c:
print(i)
print()

print("Last 4 Elements")
d = x[-4:]
62
for i in d:
print(i)print()

print("From 0th Position to 6th Position stride 2")


e = x[0:7:2]
for i in e:

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

+ operator is used to do concatenation the tuple.


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)

63
Delete tuple

You can delete entire tuple but not an element of tuple.


a = (10, 20, -50, 21.3, ‘Security’)
del a

Ex:-
# Deleting Tuple
a = (10, 20, -50, 21.3, 'Security')
b=del a
print(b)
print()

Repetition of Tuple

* Operator is used to repeat the elements of tuple.


Ex:-
b = (1, 2, 3)
result = b * 3
print(result)
Ex:-
a = (1, 2, 3)
print(a)
result = a * 3
print(result)

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)

Set Data Structure

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)

Creating Empty Set

We can create an empty set using set( ) function.


a = set()

#Creating Empty Set


x = set()

Accessing elements

a = {10, 20, “Security”, “Raj”, 40}


print(a[0])

Ex:-
# Access Set using for loop
#Cretaing Set with elements
a = {10, 20, 'Security', 'Raj', 40}
for i in a:
print(i)

Creation Set Object

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))
.

Important Function of Set


1.add(x):
Adds item x to the set

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)

Q. What is the difference between add() and update() functions in set?


We can use add() to add individual item to the Set,where as we can use update()
function to add multiple items to Set.

Q. Which of the following are valid for set s?


s.add(10)
s.add(10,20,30) TypeError: add() takes exactly one argument (3 given)
s.update(l) TypeError: 'int' object is not iterable
s.update(range(1,10,2),range(0,10,2))

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

print('z' in s) #false False

Q. Write a program to print different vowels present in the given word?


Ex:-
w=input("Enter word to search for vowels: ")
s=set(w)
v={'a','e','i','o','u'}
d=s.intersection(v)
print("The different vowel present in",w,"are",d)

Output
Enter word to search for vowels: sunil
The different vowel present in sunil are {'i', 'u'}

Dictionary Data Structure


We can use List, Tuple and Set to represent a group of individual objects as a single
entity.
If we want to represent a group of objects as key-value pairs then we should go for
Dictionary.
Duplicate keys are not allowed but values can be duplicated. Heterogeneous objects
are allowed for both key and values. insertion order is not preserved
Dictionaries are mutable Dictionaries are dynamic

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'}

How to access data from the dictionary?


We can access data by using keys.

d={100:'durga' ,200:'ravi', 300:'shiva'}


print(d[100]) #durga
print(d[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%

How to update dictionaries?

d={100: 'sunil', 200: 'ravi', 300: 'shiva'}


d[key]=value

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

d=dict() ===>It creates empty dictionary


d=dict({100:"durga",200:"ravi"}) ==>creates dictionary with specified elements
d=dict([(100,"durga"),(200,"shiva"),(300,"ravi")])==> creates dictionary with
the given list of tuple elements

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?

d=eval(input("Enter dictionary:")) Output


s=sum(d.values()) dictionary:{'A':100,'B':200,'C':300}
print("Sum= ",s) Sum= 600

Q. Write a program to accept student name and marks from the


keyboard and creates a dictionary. Also display student marks by
Taking student name as input?

n=int(input("Enter the number of students: "))


d={}
for i in range(n):
77
name = input("Enter Student Name: ")
marks = input("Enter Student Marks: ")
d[name]=marks
while True:
name = input("Enter Student Name to get Marks")
marks = d.get(name, -1)
if marks==-1:
print("Student Not Found")
else:
print("The Marks of",name,"are",marks)
option=input("Do you want to find another student

marks[Yes|No]")
if option=="No":
break
print("Thanks for using our application")

Output:-

Enter the number of students: 2


Enter Student Name: sunil
Enter Student Marks: 80
Enter Student Name: karan
Enter Student Marks: 70
Enter Student Name to get Markssunil
The Marks of sunil are 80
Do you want to find another student marks[Yes|No]No
Thanks for using our application

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)

def add(): def add(y):_


x=10 x = 10
y =20 c = x+y
c =x+y print(c)
print(c)

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()

# Seprate Function for Addition


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

# Seprate Function for Subtraction


def sub():
x = 10
y = 20
c = y - x
print(c)
sub()
sub()

Actual and Formal Argument

Formal Argument - Function definition parameters are called as formal arguments

80
Actual Argument - Function call arguments are actual arguments

def add (x, y) : <==== Formal Arguments


c=x+y
print(c)
add(10, 20) <=== Actual Argument

Type of Actual Arguments


(i)Positional Arguments
(ii)Keyword Arguments
(iii)Default Arguments
(iv)Variable Length Arguments
(v)Keyword Variable Length Arguments

(i) Positional Arguments


These arguments are passed to the function in correct positional order.
The number of arguments and their positions in the function definition should be
equal to the number and position of the argument in the function call.

#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)

(ii) Keyword Arguments

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)

(iii) Default Arguments

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")

(iv) Variable Length Arguments

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.

#Variable Length Arguments


#Example 1
82
def add(x, y):
z = x+y
print("Addition:", z)
(5, 2)

#Example 2
def add(*num):
z = num[0]+num[1]+num[2]
print("Addition:", z)
add(5,2,4,5)

(v) Keyword Variable Length Arguments

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.

#Keyword Variable Length Arguments


#Example 1
def add(**num):
z = num['a']*num['b']*num['c']
print("Addition:", z)

add(a=5, b=2, c=4)

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

When a variable is declared above a function, it becomes global variable.


These variables are available to all the function which are written after it.
The scope of global variable is the entire program body written below it

# 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

A function without a name is called as Anonymous Function. It is also known


as Lambda Function.
Anonymous Function are not defined using def keyword rather they are
defined using lambda keyword.

Syntax:-
lambda argument_list : expression
Ex:-
lambda x : print(x)
lambda x, y : x + y

# Anonymous Function or Lambda Function

#Example 1 Single Argument


show = lambda x : print(x)
show(5)

#Example 2 Two Arguments


add = lambda x,y : (x+y)
print(add(5, 2))

#Example 3 Return Multiple


add_sub = lambda x,y : (x+y, x-y)
a, s = add_sub(5, 2)
print(a)
print(s)

#Example 2 with Default Argument


add = lambda x,y=3 : (x+y)
print(add(5))

85
Python Date & Time

Following modules are used to work with date, time


(i)time
(ii)datetime

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

from time import time, ctime, localtime


epoch = time()
print(epoch)
print("epoch seconds:", epoch)

et = ctime(epoch)
print("Epoch Date and Time:", et)

ct = ctime()
print("Current Date and Time:", ctime())
print()

localtime ( ) Function – This function is used to convert seconds into date


and time. It returns an object struct_time which can be used to access the
attributes either using an index or using a name.

from time import time, ctime, localtime


epoch = time()
print(epoch)
print("epoch seconds:", epoch)
et = ctime(epoch)
print("Epoch Date and Time:", et)
# 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()

File Handling (Input & Output)


Files
File is the collection of data that is available to a program. We can retrieve and use data
stored in a file whenever we required.

Advantages:-

Stored Data is permanent unless someone remove it.


Stored data can be shared.
It is possible to update or remove the data.

Type of Files

There are two type of files:-


Text File – It stores data in the form of characters. It is used to store characters and
strings
87
Binary File – It stores data in the form of bytes, a group of 8 bits each. It is used to
store text, images, pdf, csv, video and audio.

#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

How to create 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')

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

using either a platform-dependent encoding or, specified one.

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

should always close opened file

f = open('student.txt')
f.close()

File Object Variables


name – This shows the name of specified file.
Syntax:- file_object.name

mode – This shows mode (purpose) of the file.


Syntax:- file_object.mode

closed – This used to check whether file has closed or not.


It shows True if file is closed else shows False.
Syntax:- file_object.closed

File Object Method

readable() – This method is used to check whether file is readable or not.


It returns True if file is readable else returns False.
Syntax:- file_object.readable()

writable() – This method is used to check whether file is writable or not.


It returns True if file is writable else returns False.
Syntax:- file_object.writable()

Ex:-

# Opening for Reading


f = open('student.txt', mode='r')
print('File Name:', f.name)
print('File Mode:', f.mode)
print('File Readable:', f.readable())
90
print('File Writable:', f.writable())
print('File Closed:', f.closed)
f.close()
print('File Closed:', f.closed)

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

When & Why use Modules


Assume that you are building a very large project, it will be very difficult to manage all
logic within one single file so If you want to separate your similar logic to a separate
file, you can use module.

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)

Ex:-define a folder and create two files


91
cal.py
#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

result.py

# result.py <--- Main Module

import cal # Importing Cal Module


print("cal Module's variable:", cal.a)
cal.name() # Accessing Cal Module's Function
a = cal.add(10,20) # Accessing Cal Module's Function
print(a)
b = cal.sub(20, 10) # Accessing Cal Module's Function
print(b)

How to use Module


import statement is used to import modules.

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.

Ex:- import cal


How to access Methods, Functions, Variable and Classes ?
Using the module name you can access the functions.
Syntax:- module_name.function_name()
92
Ex:-

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

# result.py <--- Main Module


from cal import a, name # Importing Cal Module
print("cal Module's variable:", a) # Accessing Cal Module's Variable
name() # Accessing Cal Module's Function
add = s(10,20) # Accessing Cal Module's Function
print(add)
b = sub(20, 10) # Accessing Cal Module's Function
print(b)

Import module_name as alise 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. If the module name is followed by
as, then the name following as is bound directly to the imported module.
Ex:- import cal as c

How to access Methods, Functions, Variable and Classes ?


Using the alias_name you can access the functions.

Ex:-
c.add(10, 20)
93
c.sub(20, 10)

add = c.add
add(10, 20)

#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

# result.py <--- Main Module


import cal as c # Importing Cal Module
print("cal Module's variable:", c.a) # Accessing Cal Module's Var
c.name() # Accessing Cal Module's Function
a = c.add(10,20) # Accessing Cal Module's Function
print(a)
b = c.sub(20, 10) # Accessing Cal Module's Function
print(b)

From module_name import function_name

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

How to access Methods, Functions, Variable and Classes ?


You can access the functions directly by it’s name.

Ex:-
add(10, 20)
sub(20, 10)

#cal.py <--- cal Module

a = 50
def name():

94
print("From Module cal")

def add(a,b):
return a+b

def sub(a,b):
return a-b

# geekyshows.py <--- Main Module

from cal import a, name, add as s, sub # Importing Cal Module

print("cal Module's variable:", a) # Accessing Cal Module's Var


name() # Accessing Cal Module's Function
add = s(10,20) # Accessing Cal Module's Function
print(add)
b = sub(20, 10) # Accessing Cal Module's Function
print(b)

From module_name import *


This imports all names except those beginning with an underscore (_).
Ex:- from cal import *

How to access Methods, Functions, Variable and Classes ?


You can access the functions directly by it’s name.

#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

# result.py <--- Main Module


from cal import * # Importing Cal Module
print("cal Module's variable:", a) # Accessing Cal Module's Var
name() # Accessing Cal Module's Function
a = add(10,20) # Accessing Cal Module's Function
print(a)
b = sub(20, 10) # Accessing Cal Module's Function
95
print(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.

A package can contain packages.


Package is nothing but a Directory/Folder

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

How to use Package

Syntax:- import packageName.moduleName


Syntax:- import packageName.subPackageName.moduleName
Ex:- import Admin.service
Ex:- import Admin.Common.footer

How to Access Variable, Function, Method, Class etc. ?


Syntax:- packageName.moduleName.functionName()
Syntax:- packageName.subPackageName.moduleName.functionName()
Ex:- Admin.service.admin_service( )
Ex:- Admin.Common.footer.admin_common_footer( )

98
Object Oriented Programming

Class

A Python class is a group of attributes and methods or Functions.

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.

How to create class

class Classname(object) :
def __init__(self):
self.variable_name = value
self.variable_name = ‘value’
def method_name(self):
Body of Method

class - class keyword is used to create a class


object - object represents the base class name from where all classes in Python are
derived. This class is also derived from object class. This is optional.
self – self is a variable which refers to current class instance/object.

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

def show_model(self, p):


price = p # Local Varaible
print("Model:", self.model, "and Price:", price)
# Passing Argument to Constructor
realme = Mobile('Realme X')
# Accessing Method from outside Class
realme.show_model(10000)

Accessing class member using object


We can access variable and method of a class using class object or instance of class.

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)

class Son(Father): # Child Class


def disp(self):
print("Child Class Instance Method")
s = Son()
s.disp()
s.show()
s.showmoney()
s.stat()

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

def show(self): # Concrete Method


print('Concrete Method')

# my = Father() # Not possible to create


object of a abstract class
class Child(Father):
def disp(self):
print("Defining Abstract Method")
c = Child()
c.disp()
c.show()
#

Abstract Method

A abstract method is a method whose action is redefined in the child classes


as per the requirement of the object.
We can declare a method as abstract method by using @abstractmethod decorator.
103
Ex:-
from abc import ABC, abstractmethod
Class Father(ABC):
@abstractmethod
def disp(self):
pass
Ex:-
from abc import ABC, abstractmethod
class DefenceForce (ABC):
def __init__(self):
self.id = 101

@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

An exception is a runtime error which can be handled by the programmer.


All exceptions are represented as classes in Python.

Type of Exception

Built-in Exception – Exceptions which are already available in Python


Language. The base class for all built-in exceptions is Base Exception class.

User Defined Exception – A programmer can create his own exceptions,


called user-defined exceptions.

Need of Exception Handling


When an exception occurs, the program terminates suddenly.
Suddenly termination of program may corrupt the program.
Exception may cause data loss from the database or a file.

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

Ex:- With out Exception Handling

a = 10
b = 0
d = a/b
print(d)
print('Rest of the Code')

Ex:- With Exception Handling


a = 10
b = 0
try:
d = a/b
print(d)
print('Inside Try')
except ZeroDivisionError:
print('Division by Zero Not allowed')
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')

print('Rest of the Code')

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)

except ZeroDivisionError as obj:


print(obj)

except NameError as ob:


print(ob)
print('Rest of the Code')

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

Using Multiple Threads in program or process

The main important application areas of multi threading are:


i)Multimedia Graphic
ii)Animations
iii)Video Games
iv)Web Servers
v)Application Servers

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.

Following are the ways of creating threads:-

i) Creating a thread without using a class


ii) Creating a thread by creating a child class to Thread class

Creating a thread without using a class

from threading import Thread


thread_object = Thread(target=function_name, args=(arg1, arg2, …))
thread_object – It represents our thread.

target – It represents the function on which the thread will act.


args – It represents a tuple of arguments which are passed to the function.
Ex:-
t = Thread(target=disp, args=(10,20))

How to Start Thread

Once a thread is created it should be started by calling start() Method.


from threading import Thread
def disp(a, b):
print(“Thread Running:”, a, b)
t = Thread(target=disp, args=(10, 20))
t.start()

from threading import Thread


def disp(a, b):
print(“Thread Running:”, a, b)
for i in range(5):
t = Thread(target=disp, args=(10, 20))
t.start()

112
Ex-:

# Importing Thread Class from threading Module


from threading import Thread
def disp():
print("Thread Running")
# Creating Thread Class Object
t = Thread(target=disp)
# Starting Thread
t.start()

Output

Thread Running

Ex:-

# Importing Thread Class from threading Module

from threading import Thread


def disp(a, b):
print("Thread Running:", a, b)
# Creating Thread Class Object
t = Thread(target=disp, args=(10, 20))
# Starting Thread
t.start()

Output:-

Thread Running: 10 20

Create a Thread by creating a child class to Thread cass


We can create our own thread child class by inheriting Thread Class from threading
module.

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

Thread Class’s Methods

start ( ) – Once a thread is created it should be started by calling


start() Method.

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.

Function of regular Expression

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.

You can escape a control character by preceding with a backslash.

| Alternation, or the ”or” operator.


^ Matches at the beginning of lines.
$ Matches at the end of a line.
\d Matches digits
\D Matches non digits

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

Graphical User Interface


Python provides various options for developing graphical user interfaces (GUIs). Most
important are below.

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 −

1) Import the Tkinter module.


2) Create the GUI application main window.
3) Add one or more of the above-mentioned widgets to the GUI application.
4) Enter the main event loop to take action against each event triggered by the user.
import tkinter
top = tkinter.Tk()
top.mainloop()

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 = tkinter.Button(top, text ="Hello", command = helloCallBack)

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

organizing other widgets in a somehow friendly way. It works like a container,


which is responsible for arranging the position of other widgets.

Ex:-

from tkinter import *


root = Tk()
frame = Frame(root)
frame.pack()

bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )

redbutton = Button(frame, text="Red", fg="red")


redbutton.pack( side = LEFT)

greenbutton = Button(frame, text="Brown", fg="brown")


greenbutton.pack( side = LEFT )

bluebutton = Button(frame, text="Blue", fg="blue")


bluebutton.pack( side = LEFT )
blackbutton = Button(bottomframe, text="Black", fg="black")
blackbutton.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:-

from tkinter import *


top = Tk()
Lb1 = Listbox(top)
Lb1.insert(1, "Python")
Lb1.insert(2, "Perl")
Lb1.insert(3, "C")
Lb1.insert(4, "PHP")
Lb1.insert(5, "JSP")
Lb1.insert(6, "Ruby")
Lb1.pack()
120
top.mainloop()

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.

from tkinter import *


root = Tk()
var = StringVar()
label = Label( root, textvariable=var, relief=RAISED )
var.set("Hey!? How are you doing?")
label.pack()
root.mainloop()

Python Database connection

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.

Python Supports various Databases


MySQL
SQLite 3
MongoDB
Oracle OCI8
PostgreSQL

MySQL

MySQL is an open source database management system application which will


help us to manage the database like store and retrieve data.

CRUD Operations
Create
121
Read
Update
Delete

Requirements

SQL – To write sql queries.

MySQL – We have to install MySQL in our system. It is an open source database


management system application which will help us to manage the database like store
and retrieve data. We have to set the path variable to bin directory of MySQL server.

Connector or Driver – A connector is a program that establishes connection between


Python programs and MySQL database without installing connector it is not possible
make communication between python program and MySQL database.

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

connect()– This method is used to open or establish a new connection. It returns an


object representing the connection.

Syntax: -
connection_object = connect(user=‘username’, password=‘pass’ host=
‘localhost’, port=3306);

Check Connection

is_connected() – This method is used to check if the connection to MySQL is


122
established or not. It returns True if the connection is established successfully.
Syntax:- connection_object.is_connected()

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

close() – This method is used to close the connection.


Syntax:- connection_object.close()

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

connect() – This method is used to open or establish a new connection.


It returns an object representing the connection.
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’, database=‘pdb’, port=3306) database=‘pdb’, port=3306)

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

Insert Multiple Row

# Insert Multiple 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 = 'INSERT INTO student1(name, roll, fees)
VALUES("Jai", 104, 40000.50), ("Veeru", 105, 50000.50),
("Basanti", 106, 60000.50)'
myc = mydb.cursor()
try:
myc.execute(sql)
mydb.commit() # Committing the change
print(myc.rowcount, 'Row Inserted')
# Number of Row Inserted
127
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

Retrieve All Rows

# Retrieve All Rows


import mysql.connector
mydb = mysql.connector.connect(

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

Python Mail Sending Program


Simple Mail Transfer Protocol (SMTP) is a protocol, which handles sending
e-mail and routing e-mail between mail servers.
Python provides smtplib module, which defines an SMTP client session object
that can be used to send mail to any Internet machine with an SMTP or ESMTP
listener daemon.
Here is a simple syntax to create one SMTP object, which can later be used to
send an e-mail –
Ex:-
import smtplib
rec_email = "Your_Email"
sender_email = "Sender Mail"
password = input(str("please enter your password "))

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

Data science is an inter-disciplinary field that uses scientific methods, processes,


algorithms and systems to extract knowledge and insights from many structural
and unstructured data. Data science is related to data mining, machine learning
and big data.

Important libraries for Data Science


I. NumPy
II. Pandas
III. Matplotlib

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

Machine learning is an application of artificial intelligence (AI) that


provides systems the ability to automatically learn and improve from
experience without being explicitly programmed. Machine learning
focuses on the development of computer programs that can access data
and use it to learn for themselves.
The process of learning begins with observations or data, such as examples,
direct experience, or instruction, in order to look for patterns in data and make
better decisions in the future based on the examples that we provide. The primary
aim is to allow the computers learn automatically without human intervention or
assistance and adjust actions accordingly.

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

What Is Artificial Intelligence (AI)?


Artificial intelligence (AI) refers to the simulation of human intelligence
134
in machines that are programmed to think like humans and mimic their
actions. The term may also be applied to any machine that exhibits traits
associated with a human mind such as learning and problem-solving.

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

You might also like