Python - Book
Python - Book
(Simplified)
SRINIVAS GARAPATI
AMEERPET TECHNOLOGIES, NEAR SATYAM THEATRE, OPPOSITE HDFC BANK, Ameerpet, Hyderbad-500016.
Contact – 9119556789 / 7306021113
Contents
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 1
Introduction to Python
Introduction:
• Using Programming languages and technologies we develop applications.
• Applications are used to store data and perform operations on data.
Types of applications:
Standalone apps:
• The application runs from single machine.
• Internet connection is not required to run the application.
• Application needs to be installed on machine.
• Examples: VLC, MS-office, Anti-virus, Browser, Programming languages.
Web apps:
• The application runs from multiple machines in a network.
• Internet connection is required to run the application.
• Application installed in server and run from the clients.
• Examples: Gmail, YouTube, IRCTC, Flip Kart etc.
Download python:
• Python is an Open-Source Technology.
• We can download and install Python software from official website www.python.org
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 2
Translators:
• Programmer can define only source code.
• We need to convert the source code into binary code before run.
• We use 2 translators to convert Source code into byte code.
o Compiler
o Interpreter
Compiler:
• Compiler checks the source code syntactically correct or not.
• If we define the code correctly, it converts source code into byte code.
• Compiler shows error message with line number if there is a syntax error.
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 3
Interpreter:
• Line by line translation of source code into binary code.
• Python uses interpreter for program execution.
Output: a val : 10
b val : 20
NameError: name 'c' is not defined
Program:
• A set of instructions.
• Program runs alone.
Script:
• Script is a set of Instructions
• Scripts is a program that always execute from another program.
• JavaScript is the best example of Scritping language.
• JavaScript code always run with HTML program.
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 4
Python is Dynamic:
• Every programming language is used to develop applications
• Application is used to store and process the data.
• Generally we allocate memory to variables in 2 ways
1. Static memory allocation
2. Dynamic memory allocation
Static memory:
• Static means “fixed memory”
• The languages which are supporting primitive types allowed allocating static memory.
• Primitive variable size and type are fixed.
• Primitive variable stores data directly.
• Compiler raises error when data limit or type is deviated from specified.
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 5
Dynamic memory:
• Python is dynamic.
• Dynamic memory means type and size of data can vary.
• Python can store information in Object format.
• Dynamic variables cannot store the data directly.
• Dynamic variables store the reference of Object which holds data.
• In Python, object location changes every time when we modify the data.
>>> a=10
>>> print(a)
10
>>> print("Address :",id(a))
Address : 1628169120
>>> a=a+15
>>> print(a)
25
>>> print("Address :",id(a))
Address : 1628169360
>>> a="python"
>>> print(a)
python
>>> print("Address :",id(a))
Address : 48576832
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 6
Edit and Run python program:
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 7
Python Variables
Variable: Variable is an identity of memory location. Variable is used to store data of program.
You can assign any value to a variable using the "=" operator.
x = 10
Variables can be of different types in Python, such as integer, float, string, boolean, etc.
age = 25
height = 5.7
name = "Amar"
is_student = True
You can assign the same value to multiple variables at once using the "=" operator.
x=y=z=0
Python variables are case-sensitive, which means "a" and "A" are different variables.
a = 10
A = 20
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 8
Print a value using f-string:
a = 10
print(f"a value = {a}")
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 9
Operators and Control Statements
Operator:
• Operator is a symbol that performs operation on one or more operands.
• The member on which operator operates is called the operand.
• In the expression a = 5+9,
a, 5,9 are operands
=, + are operators
Arithmetic operators:
Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication etc.
Operators are +, - , * , / , % , // , **
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 10
Floor division (//): Returns floor value after divide.
Exponent (**): returns the power value of specified base.
>>> 10/3 >>> 2**2
3.3333333333333335 4
>>> 10//3 >>> 2**4
3 16
>>> 10/4 >>> 3**3
2.5 27
>>> 10//4
2
n=2; n s n=2; n c
s=n*n; c=n*n*n;
print(s); print(c);
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 11
n=2; s c bal=5000; bal amt
s=n*n; amt=3500;
c=n*n*n; bal = bal + amt;
print(s+c); print(bal);
n=234; n d n=234; n d
d=n%10; d=n//10;
print(d); print(d);
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 12
n=2345, sum=0; n=2345, rev=0;
sum=sum+n%10; rev=rev*10+n%10;
n=n//10; n=n//10;
sum=sum+n%10; rev=rev*10+n%10;
n=n//10; n=n//10;
sum=sum+n%10; rev=rev*10+n%10;
n=n//10; n=n//10;
sum=sum+n%10; rev=rev*10+n%10;
n=n//10; n=n//10;
Adding 2 numbers:
a=10
b=20
print("Sum = ", a+b)
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 13
Display Last digit of given number:
num = 356
last = num%10
print(f"Last Digit of {num} is {last}")
Average of 4 numbers:
a,b,c,d=5,2,8,6
sum=a+b+c+d
avg=sum/4
print(f"Given nums : {a},{b},{c},{d}")
print(f"Sum = {sum}")
print(f"Average = {avg}")
Swapping 2 numbers:
a,b = 5, 3
print(f"Before swap : {a},{b}")
a,b = b,a
print(f"After swap : {a},{b}")
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 14
Python Input()
We need to convert the string type input values into corresponding type to perform
operations.
int( ) :
• It is pre-defined function
• It can convert input value into integer type.
• On success, it returns integer value
• On failure(if the input is not valid, raised error)
Adding 2 numbers
print("Enter 2 numbers :")
a = input()
b = input()
c = int(a)+int(b)
print("Sum :",c)
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 15
Data Conversion Functions
int( ) :
• It is pre-defined function
• It can convert input value into integer type.
• On success, it returns integer value
• On failure(if the input is not valid, raised error)
>>> int(10)
10
>>> int(23.45)
23
>>> int(True)
1
>>> int(False)
0
>>> int("45")
45
>>> int("python") # Error : Invalid input
Adding 2 numbers:
print("Enter 2 numbers :")
a = input()
b = input()
c = int(a)+int(b)
print("Sum :",c)
float() :
• converts the input value into float type.
• Raise error if the input is not valid.
>>> float(2.3)
2.3
>>> float(5)
5.0
>>> float(True)
1.0
>>> float("3.4")
3.4
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 16
>>> float("abc")
ValueError: could not convert string to float: 'abc'
bool():
• Returns a boolean value depends on input value.
• boolean values are pre-defiend (True , False)
>>> bool(True)
True
>>> bool(-13)
True
>>> bool(0.0013)
True
>>> bool(0)
False
>>> bool("abc")
True
>>> bool(" ")
True
>>> bool("")
False
>>> bool(False)
False
>>> bool("False")
True
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 17
Character System:
• File is a collection of bytes.
• Every symbol occupies 1 byte memory in File.
• Every symbol stores into memory in binary format.
• Symbol converts into binary based on its ASCII value.
• Character system is the representation of all symbols of a language using constant
integer values.
• Examples are ASCII and UNICODE.
>>> chr(65)
'A'
>>> chr(50)
'2'
>>> ord('a')
97
>>> ord('$')
36
>>> ord('1')
49
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 18
Programs On Arithmetic Operators
Adding 2 numbers:
print("After swapping:")
print("num1 =", num1)
print("num2 =", num2)
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 19
Relational operators:
• Operators are > , < , >= , <= , == , !=
• These operators validate the relation among operands and return a boolean value.
• If relation is valid returns True else False
Condition to check the multiplication of first 2 numbers equal to square of 3rd number
T
Condition to check the sum of First 2 numbers equals to last digit of 3rd num E
C
H
Condition to check average of 3 numbers equals to first number N
O
L
O
Condition to check the given quantity of fruits exactly in dozens G
I
E
S
Condition to check the given quantity of fruits exactly in dozens
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 21
If-else Conditional Statement:
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 22
Check the person eligible for vote or not
age = int(input("Enter age : "))
if(age>=18):
print("Eligible for vote")
else:
print("Not eligible for vote")
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 23
Logical operators: These operators returns True or False be validating more than one
expression
A
4. Condition to check the number is 3 digits number M
E
E
5. Condition to check the student passed in all 5 subjects R
P
E
6. Condition to check the character is Vowel T
T
E
7. Condition to check the character is Upper case alphabet C
H
N
O
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 24
L
O
G
I
8. Condition to check the character is digit
12. Condition to check any 2 numbers equal or not among the 3 numbers
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 25
Check the Character is Lower case Alphabet or Not:
ch = input("enter character : ")
if ch>='a' and ch<='z':
print("Lower case Alphabet")
else:
print("Not")
Check the Student passed in all 3 subjects or not with minimum 35 marks:
subj1 = int(input("Enter subj1 score: "))
subj2 = int(input("Enter subj2 score: "))
subj3 = int(input("Enter subj3 score: "))
if subj1 >= 35 and subj2 >= 35 and subj3 >= 35:
print("Pass")
else:
print("Fail")
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 26
If-block: Execute a block of instructions only if the given condition if true
Program to give 20% discount to customer if the bill amount is > 5000
# Get the bill amount from the user
bill = float(input("Enter bill : "))
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 27
if-elif-else: if-elif-else is a control flow structure in programming that allows a program to
execute different blocks of code based on one or more conditions.
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 28
Program to find Biggest of Three Numbers:
# Get the input values for a, b, and c from the user
a = int(input("Enter a value : "))
b = int(input("Enter b value : "))
c = int(input("Enter c value : "))
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 29
Nested-If: Writing if block inside another if block
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 30
# Check if a is not equal to b
if a != b:
if a > b:
print("a is big")
else:
print("b is big")
else:
print("a and b are equal")
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 31
Bitwise operators:
• Bitwise operators act on operands as if they were string of binary digits. It operates bit
by bit, hence the name.
• For example, 2 is 10 in binary and 7 is 111.
• In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
Shift operators:
• These are used to move the bits in the memory either to right side or to left side.
• Moving binary bits in the memory change the value of variable.
• These operators return the result in decimal format only.
• Operators are Right shift (>>) and Left shift (<<)
>>> x=8 Right shift: n/2^s → 8/2^2 → 8/4 → 2
>>> x>>2 Left shift : n*2^s → 8*2^2 → 8*4 → 32
2
>>> x<<2
32
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 32
Introduction to Loops
Note: Block executes only once whereas Loop executes until condition become False
For Loop: We use for loop only when we know the number of repetitions. For example,
• Print 1 to 10 numbers
• Print String elements
• Print Multiplication table
• Print String character by character in reverse order
While loop: We use while loop when we don’t know the number of repetitions.
• Display contents of File
• Display records of Database table
While – else : while-else loop is a type of loop that combines a while loop with an else
statement that is executed after the loop has completed. The else block is executed only if the
while loop completed normally
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 33
For Loop
for loop:
• "for" is a keyword.
• for loop executes a block repeatedly as long as the condition is valid.
• for loop uses range() function for loop repetition.
range():
• The range() function in Python generates a sequence of numbers within a given range.
• It takes up to three arguments: start (optional), stop (required), and step (optional).
• The sequence generated by the range() function is commonly used in for loops.
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 34
Print the even numbers from 10 to 0:
for i in range(10, -1, -2):
print(i)
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 35
Multiplication table program:
n = int(input("Enter a positive integer: "))
for i in range(1, 11):
product = i * n
print(n, "x", i, "=", product)
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 36
Count Factors of given numbers:
n = int(input("Enter a positive integer: "))
count_factors = 0
if is_prime:
print(n, "is a prime number")
else:
print(n, "is not a prime number")
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 37
Perfect number program: A perfect number is a positive integer that is equal to the sum of its
proper divisors (excluding itself).
if sum == n:
print(n, "is a perfect number")
else:
print(n, "is not a perfect number")
Fibonacci Series program: Fibonacci series, is a sequence of numbers in which each number
(after the first two) is the sum of the two preceding ones.
The Fibonacci sequence starts with 0 and 1 as its first two terms:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 38
While Loop
While loop: Execute a block of instructions repeatedly until the condition is false. We use while
loop only when don’t know the number of iterations to do.
while(condition):
statements;
print("Exiting program.")
print("Exiting program.")
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 39
Check the Number is Prime or Not until user exits:
while True:
n = int(input("Enter a number: "))
count = 0
for i in range(1, n + 1):
if n % i == 0:
count += 1
if count == 2:
print(n, "is Prime")
else:
print(n, "is not Prime")
print("Exiting program.")
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 40
Digit Based Programs
Program to Display Last Digit of given number
• When we divide any number with 10 then last digit will be the remainder.
• 1234%10 -> 4
• 1005%10 -> 5
• 200%10 -> 0
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 41
Program to display the sum of even digits:
n = int(input("Enter Num: "))
sum = 0
while n > 0:
r = n % 10
if r % 2 == 0:
sum = sum + r
n = n // 10
while n > 0:
r = n % 10
for i in range(1, 11):
print(f"{r} * {i} = {r * i}")
n = n // 10
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 42
Program to display prime number digits in the given number:
n = int(input("Enter Num: "))
while n > 0:
r = n % 10
count = 0
if count == 2:
print(f"{r} is prime")
n = n // 10
while n > 0:
r = n % 10
if r < small:
small = r
n = n // 10
if r > large:
large = r
n = n // 10
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 43
Program to find the sum of Largest and Smallest Digit in the given number:
n = int(input("Enter Num: "))
large = 0
small = 9
while n > 0:
r = n % 10
if r > large:
large = r
if r < small:
small = r
n = n // 10
print("First Digit:", n)
Program to Find the Sum of First and Last digits of given number
n = int(input("Enter Num: "))
first = n % 10
last = n % 10
sum = first + last
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 44
while n > 0:
r = n % 10
rev = rev * 10 + r
n = n // 10
Palindrome Number: The number become same when we reverse is called Palindrome number
Examples: 121, 1001, 123321
n = int(input("Enter Num: "))
rev = 0
temp = n
while n > 0:
r = n % 10
rev = rev * 10 + r
n = n // 10
if temp == rev:
print("Palindrome Number")
else:
print("Not Palindrome Number")
while n > 0:
r = n % 10
sum += r ** num_digits
n //= 10
if temp == sum:
print("Armstrong Number")
else:
print("Not an Armstrong Number")
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 45
Program to check the given number is Armstrong number or not:
Armstrong Number: Sum of its own digits raised to power number of digits
Examples : 153 = 1^3 + 5^3 + 3^3 = 153
1634 = 1^4 + 6^4 + 3^4 + 4^4 = 1634
while n > 0:
n = n // 10
c += 1
n = temp
while n > 0:
r = n % 10
s=1
for i in range(1, c + 1):
s *= r
sum += s
n = n // 10
if temp == sum:
print("Armstrong Number")
else:
print("Not an Armstrong Number")
while num // 10 != 0:
sum = 0
while num != 0:
dig = num % 10
sum += dig
num //= 10
print(sum, end="->")
num = sum
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 46
ADAM Number: Take a number then square it then reverse it then find its square root then
reverse. If the given number equals to the final number then it is called ADAM.
• Take the number (12)
• Square the number (144)
• Reverse the number(441)
• Square root of number (21)
• Reverse the number(12)
import math
if rev2 == num:
print(num, " is an Adam number")
else:
print(num, " is not an Adam number")
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 47
Break and Continue
break: A branching statement that terminates the execution flow of a Loop or Switch case.
for i in range(1, 11):
if i == 5:
break
print(i, end=" ")
Output: 1 2 3 4
Continue: A branching statement that terminates the current iteration of loop execution.
for i in range(1, 11):
if i == 5:
continue
print(i, end=" ")
Output: 1 2 3 4 5 6 7 8 9 10
print("Exiting program.")
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 48
While – Else Loop
while-else:
• In Python, the while loop can be combined with an else block.
• The else block is executed when the while loop condition becomes False or when the
loop is exhausted, but not when the loop is exited using a break statement.
• This can be useful in situations where you want to perform some actions after the loop
has finished executing normally.
Password Validation:
password = input("Enter a password: ")
while len(password) < 8:
print("Password must be at least 8 characters long.")
password = input("Enter a valid password: ")
else:
print("Password is valid.")
Sum of Digits:
num = 12345
sum_of_digits = 0
while num > 0:
digit = num % 10
sum_of_digits += digit
num //= 10
else:
print(f"The sum of digits is {sum_of_digits}")
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 49
Range Based Programs
Print Evens numbers from 1 to 10:
for n in range(1, 11):
if n % 2 == 0:
print(n)
Factorials from 2 to 8:
for n in range(2, 9):
factorial = 1
for i in range(1, n + 1):
factorial *= i
print(f"Factorial of {n} is {factorial}")
if factors == 2:
print(n, "is prime")
if n == sum:
print(n, "is perfect")
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 50
Pattern Programs
Pattern:
• Representation of data in two-dimensional format (rows and columns)
• We use nested loops to print patterns.
• We can print patterns with numbers, characters, starts, symbols
• Patterns can be in different shapes like triangle, rectangle, half triangle, pyramid and so
on.
Pattern Logic
11111 for i in range(1, 6):
22222 for j in range(1, 6):
33333
print(i, end="")
44444
55555 print()
Pattern Logic
***** for i in range(1, 6):
***** for j in range(1, 6):
*****
print('*', end="")
*****
***** print()
Pattern Logic
54321 for i in range(5, 0, -1):
54321 for j in range(5, 0, -1):
54321
print(j, end="")
54321
54321 print()
Pattern Logic
for i in range(5, 0, -1):
55555 for j in range(5, 0, -1):
44444
print(i, end="")
33333
22222 print()
11111
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 51
Pattern Logic
10101 for i in range(1, 6):
10101 for j in range(1, 6):
10101
print(j % 2, end="")
10101
10101 print()
Pattern Logic
11111 for i in range(1, 6):
00000 for j in range(1, 6):
11111
print(i % 2, end="")
00000
11111 print()
Pattern Logic
Pattern Logic
EEEEE for x in range(ord('E'), ord('A') - 1, -1):
DDDDD for y in range(ord('E'), ord('A') - 1, -1):
CCCCC
print(chr(x), end="")
BBBBB
AAAAA print()
Pattern Logic
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 52
Basic Patterns with Conditions
Pattern Logic
for i in range(1, 6):
for j in range(1, 6):
$$$$$
if i % 2 == 0:
#####
$$$$$ print("#", end="")
##### else:
$$$$$ print("$", end="")
print()
Pattern Logic
for i in range(1, 6):
for j in range(1, 6):
$#$#$
if j % 2 == 0:
$#$#$
$#$#$ print("#", end="")
$#$#$ else:
$#$#$ print("$", end="")
print()
Pattern Logic
k=1
12345 for i in range(1, 6):
67891
for j in range(1, 6):
23456
78912 print(k % 10, end="")
34567 k += 1
print()
Pattern Logic
for i in range(1, 6):
for j in range(1, 6):
11111
if i % 2 == 0:
12345
33333 print(j, end="")
12345 else:
55555 print(i, end="")
print()
Pattern Logic
for i in range(1, 6):
55555 for j in range(1, 6):
54321
if i % 2 == 0:
33333
54321 print(j, end="")
11111 else:
print(i, end="")
print()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 53
Patterns Plus Cross Swastika
Pattern Logic
+++++++
+++++++ for i in range(1, 8):
+++++++
for j in range(1, 8):
+++++++
+++++++ print("+", end="")
+++++++ print()
+++++++
Pattern Logic
for i in range(1, 8):
+++++++ for j in range(1, 8):
+ +
if i == 1 or i == 7 or j == 1 or j == 7:
+ +
+ + print("+", end="")
+ + else:
+ + print(" ", end="")
+++++++ print()
Pattern Logic
for i in range(1, 8):
+ for j in range(1, 8):
+
if i == 4 or j == 4:
+
+++++++ print("+", end="")
+ else:
+ print(" ", end="")
+ print()
Pattern Logic
for i in range(1, 8):
+++++++ for j in range(1, 8):
+ + +
if i in (1, 4, 7) or j in (1, 4, 7):
+ + +
+++++++ print("+", end="")
+ + + else:
+ + + print(" ", end="")
+++++++ print()
Pattern Logic
for i in range(1, 8):
+ for j in range(1, 8):
+
if i == j:
+
+ print("+", end="")
+ else:
+ print(" ", end="")
+ print()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 54
Pattern Logic
+ for i in range(1, 8):
+ for j in range(1, 8):
+
if j == 8 - i:
+
+ print("+", end="")
+ else:
+ print(" ", end="")
print()
Pattern Logic
for i in range(1, 8):
+ + for j in range(1, 8):
+ +
if i == j or j == 8 - i:
+ +
+ print("+", end="")
+ + else:
+ + print(" ", end="")
+ + print()
Pattern Logic
for i in range(1, 8):
+ + + + + + + for j in range(1, 8):
+ + + +
if i == 1 or i == 7 or j == 1 or j == 7 or i == j or j
+ + + +
+ + + == 8 - i:
+ + + + print("+", end="")
+ + + + else:
+ + + + + + + print(" ", end="")
print()
Pattern Logic
for i in range(1, 8):
++++ for j in range(1, 8):
+
if (i == 1 and j <= 4) or j == 4 or (i == 7 and j >= 4):
+
+ print("+", end="")
+ else:
+ print(" ", end="")
++++ print()
Pattern Logic
+ for i in range(1, 8):
+ for j in range(1, 8):
+
if i == 4 or (j == 1 and i >= 4) or (j == 7 and i <= 4):
+++++++
+ print("+", end="")
+ else:
+ print(" ", end="")
print()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 55
Pattern Logic
++++ + for i in range(1, 8):
+ + for j in range(1, 8):
+ +
if i == 4 or (j == 1 and i >= 4) or (j == 7 and i <= 4) or
+++++++
+ + (i == 1 and j <= 4) or j == 4 or (i == 7 and j >= 4):
+ + print("+", end="")
+ ++++ else:
print(" ", end="")
print()
Pattern Logic
for i in range(1, 8):
+ for j in range(1, 6):
+ +
if j == 4 - i or j == 3 or i == 7:
+ +
+ print("+", end="")
+ else:
+ print(" ", end="")
+ + + + + + + print()
Pattern Logic
for i in range(1, 8):
+ + + + + for j in range(1, 6):
+
if i == 1 or i == 4 or i == 7 or (j == 5 and i <= 4) or (j ==
+
+ + + + + 1 and i >= 4):
+ print("+", end="")
+ else:
+ + + + + print(" ", end="")
print()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 56
Pattern Logic
Pattern Logic
+
+ + for i in range(1, 8):
+ +
for j in range(1, 8):
+ +
+ + + + + + + + if j == 5 or i == 5 or j == 6 - i:
+ print("+", end="")
+ else:
print(" ", end="")
print()
Pattern Logic
for i in range(1, 8):
+ + + + + for j in range(1, 6):
+
if i == 1 or i == 4 or i == 7 or (j == 1 and i <= 4) or (j
+
+ + + + + == 5 and i >= 4):
+ print("*", end="")
+ else:
+ + + + + print(" ", end="")
print()
Pattern Logic
for i in range(1, 8):
+ + + + + for j in range(1, 6):
+
if i == 1 or j == 1 or i == 4 or i == 7 or (j == 5 and i
+
+ + + + + >= 4):
+ + print("*", end="")
+ + else:
+ + + + + print(" ", end="")
print()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 57
Pattern Logic
Pattern Logic
+ + + + +
+ + for i in range(1, 8):
+ +
for j in range(1, 6):
+ + + + +
+ + if i == 1 or i == 4 or i == 7 or j == 1 or j == 5:
+ + print("*", end="")
+ + + + + else:
print(" ", end="")
print()
Pattern Logic
+ + + + + for i in range(1, 8):
+ + for j in range(1, 6):
+ +
if i == 1 or i == 4 or i == 7 or (j == 1 and i <= 4)
+ + + + +
+ or j == 5:
+ print("*", end="")
+ + + + + else:
print(" ", end="")
print()
T
E
C
Pattern Logic
+ + + + for i in range(1, 8):
+ + for j in range(1, 8):
+ +
if j == 1 or (i == 1 and j <= 6) or (i == 4 and j <= 6) or (i
+ + + +
+ + == 7 and j <= 6) or ((j == 7) and (i > 1 and i < 4)) or ((j == 7)
+ + and (i > 4 and i < 7)):
+ + + + print("+", end="")
else:
print(" ", end="")
print()
Pattern Logic
+ + + + for i in range(1, 8):
+ for j in range(1, 8):
+
if (i == 1 and j > 1) or (j == 1 and i > 1 and i < 7) or (i ==
+
+ 7 and j > 1):
+ print("+", end="")
+ + + + else:
print(" ", end="")
print()
Pattern Logic
Pattern Logic
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 59
Pattern Logic
+ + + + + for i in range(1, 8):
+ for j in range(1, 8):
+
if j == 1 or i == 1 or i == 4:
+ + + + +
+ print("+", end="")
+ else:
+ print(" ", end="")
print()
Pattern Logic
+ + + + + for i in range(1, 8):
+ for j in range(1, 8):
+
if j == 1 or i == 1 or i == 7 or (j == 7 and i >= 4) or (i ==
+ + +
+ + 4 and j >= 4):
+ + print("+", end="")
+ + + + + else:
print(" ", end="")
print()
Pattern Logic
for i in range(1, 8):
+ + for j in range(1, 8):
+ +
if j == 1 or i == 4 or j == 7:
+ +
+ + + + + print("+", end="")
+ + else:
+ + print(" ", end="")
+ + print()
Pattern Logic
for i in range(1, 8):
+ + + + + for j in range(1, 8):
+
if i == 1 or j == 4 or i == 7:
+
+ print("+", end="")
+ else:
+ print(" ", end="")
+ + + + + print()
Pattern Logic
for i in range(1, 8):
+ + + + + for j in range(1, 8):
+
if i == 1 or j == 4 or i == j + 3:
+
+ + print("+", end="")
+ + else:
+ print(" ", end="")
print()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 60
Pattern Logic
for i in range(1, 8):
+ + for j in range(1, 8):
+ +
if j == 1 or (j == 6 - i) or (i == j + 2):
+ +
+ print("+", end="")
+ + else:
+ + print(" ", end="")
+ + print()
Pattern Logic
for i in range(1, 8):
for j in range(1, 8):
+
if j == 1 or i == 7:
+
+ print("+", end="")
+ else:
+ print(" ", end="")
+ + + + + print()
Pattern Logic
for i in range(1, 8):
for j in range(1, 8):
+ +
if j == 1 or j == 7 or (i == j and j <= 4) or (j == 8 - i
+ + + +
+ + + + and j > 4):
+ + + print("+", end="")
+ + else:
+ + print(" ", end="")
+ + print()
Pattern Logic
for i in range(1, 8):
for j in range(1, 8):
+ +
if j == 1 or j == 7 or (i == j):
+ + +
+ + + print("+", end="")
+ + + else:
+ + + print(" ", end="")
+ + + print()
+ +
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 61
Numbers Triangle Patterns
Pattern Logic
1 for i in range(1, 6):
12 for j in range(1, i + 1):
123
print(j, end="")
1234
12345 print()
Pattern Logic
1 for i in range(1, 6):
21 for j in range(i, 0, -1):
321
print(j, end="")
4321
54321 print()
Pattern Logic
12345 for i in range(5, 0, -1):
1234 for j in range(1, i + 1):
123
print(j, end="")
12
1 print()
Pattern Logic
12345 for i in range(1, 6):
2345 for j in range(i, 6):
345
print(j, end="")
45
5 print()
Pattern Logic
5 for i in range(5, 0, -1):
54 for j in range(5, i - 1, -1):
543
print(j, end="")
5432
54321 print()
Pattern Logic
5 for i in range(5, 0, -1):
45 for j in range(i, 6):
345
print(j, end="")
2345
12345 print()
Pattern Logic
54321 for i in range(1, 6):
5432 for j in range(5, i - 1, -1):
543
print(j, end="")
54
5 print()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 62
Pattern Logic
54321 for i in range(5, 0, -1):
4321 for j in range(i, 0, -1):
321
print(j, end="")
21
1 print()
1 for i in range(1, 6):
22 for j in range(1, i + 1):
333
print(i, end="")
4444
55555 print()
11111 for i in range(1, 6):
2222 for j in range(i, 6):
333
print(i, end="")
44
5 print()
5 for i in range(5, 0, -1):
44 for j in range(i, 6):
333
print(i, end="")
2222
11111 print()
Pattern Logic
55555 for i in range(5, 0, -1):
4444 for j in range(1, i + 1):
333
print(i, end="")
22
1 print()
Pattern Logic
k=1
for i in range(1, 6):
1
for j in range(1, i + 1):
23
456 print(k, end="")
7891 k += 1
23456 if k > 9:
k=1
print()
Pattern Logic
k=1
for i in range(5, 0, -1):
12345
for j in range(1, i + 1):
6789
123 print(k, end="")
45 k += 1
6 if k > 9:
k=1
print()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 63
Pattern Logic
for i in range(1, 6):
for j in range(i, 5):
1
print(" ", end="")
21
321 for k in range(i, 0, -1):
4321 print(k, end="")
54321 print()
Pattern Logic
for i in range(5, 0, -1):
for j in range(i, 5):
12345
print(" ", end="")
1234
123 for k in range(1, i + 1):
12 print(k, end="")
1 print()
Pattern Logic
for i in range(1, 6):
for j in range(1, i):
12345
print(" ", end="")
2345
345 for k in range(i, 6):
45 print(k, end="")
5 print()
Pattern Logic
for i in range(5, 0, -1):
for j in range(1, i):
5
print(" ", end="")
45
345 for k in range(i, 6):
2345 print(k, end="")
12345 print()
Pattern Logic
for i in range(5, 0, -1):
for j in range(1, i):
5
print(" ", end="")
54
543 for k in range(5, i - 1, -1):
5432 print(k, end="")
54321 print()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 64
Pattern Logic
for i in range(5, 0, -1):
for j in range(i, 4):
54321
print(" ", end="")
4321
321 for k in range(i, 0, -1):
21 print(k, end="")
1 print()
Pattern Logic
for i in range(1, 6):
for j in range(1, i):
54321
print(" ", end="")
5432
543 for k in range(5, i - 1, -1):
54 print(k, end="")
5 print()
Pattern Logic
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 65
Pattern Logic
E for i in range(ord('E'), ord('A') - 1, -1):
ED for j in range(ord('E'), i - 1, -1):
EDC
print(chr(j), end="")
EDCB
EDCBA print()
Pattern Logic
E for i in range(ord('E'), ord('A') - 1, -1):
DE for j in range(ord('E'), i - 1, -1):
CDE
print(chr(j), end="")
BCDE
ABCDE print()
Pattern Logic
EDCBA for i in range(ord('A'), ord('F')):
EDCB for j in range(ord('E'), i - 1, -1):
EDC
print(chr(j), end="")
ED
E print()
Pattern Logic
EDCBA for i in range(ord('E'), ord('A') - 1, -1):
DCBA for j in range(i, ord('A') - 1, -1):
CBA
print(chr(j), end="")
BA
A print()
Pattern Logic
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 66
Pattern Logic
for i in range(1, 6):
for j in range(i, 5):
*
print(" ", end="")
**
*** for k in range(1, i + 1):
**** print("*", end="")
***** print()
Pattern Logic
for i in range(1, 6):
for j in range(1, i):
*****
print(" ", end="")
****
*** for k in range(i, 6):
** print("*", end="")
* print()
Pattern Logic
for i in range(1, 10):
if i <= 5:
*
for j in range(1, i + 1):
**
*** print("*", end="")
**** print()
***** else:
**** for k in range(i, 10):
*** print("*", end="")
**
print()
*
Pattern Logic
for i in range(1, 10):
if i <= 5:
for x in range(i, 6):
print(" ", end="")
* for j in range(1, i + 1):
** print("*", end="")
*** print()
**** else:
***** for x in range(i, 5, -1):
****
*** print(" ", end="")
** for k in range(i, 10):
* print("*", end="")
print()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 67
Pattern Logic
for i in range(1, 10):
***** if i <= 5:
****
for j in range(i, 6):
***
** print("*", end="")
* print()
** else:
*** for k in range(5, i + 1):
**** print("*", end="")
*****
print()
Pattern Logic
for i in range(1, 10):
if i <= 5:
for x in range(1, i + 1):
print(" ", end="")
for j in range(i, 6):
***** print("*", end="")
**** print()
*** else:
**
for x in range(i, 10):
*
** print(" ", end="")
*** for k in range(5, i + 1):
**** print("*", end="")
***** print()
Pattern Logic
k=1
for i in range(1, 6):
10101
for j in range(1, i + 1):
0101
010 print(k % 2, end="")
10 k += 1
1 print()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 68
Pattern Logic
1 for i in range(1, 6):
10 for j in range(1, i + 1):
101
print(j % 2, end="")
1010
10101 print()
Pattern Logic
1 for i in range(1, 6):
00 for j in range(1, i + 1):
111
print(i % 2, end="")
0000
11111 print()
Pattern Logic
11111 for i in range(5, 0, -1):
0000 for j in range(1, i + 1):
111
print(i % 2, end="")
00
1 print()
Pattern Logic
n=7
******** for i in range(n, 0, -1):
* *
for j in range(1, i + 1):
* *
* * if i == 1 or i == n or j == 1 or j == i:
* * print("*", end="")
* * else:
** print(" ", end="")
* print()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 69
Pattern Logic
for i in range(1, 8):
for j in range(1, i):
********
print(" ", end="")
* *
* * for k in range(i, 8):
* * if i == 1 or i == 7 or k == i or k == 7:
* * print("*", end="")
* * else:
** print(" ", end="")
*
print()
Pattern Logic
for i in range(1, 8):
for j in range(i, 7):
*
print(" ", end="")
**
* * for k in range(1, i + 1):
* * if i == 1 or i == 7 or k == 1 or k == i:
* * print("*", end="")
* * else:
* * print(" ", end="")
********
print()
Pyramid Patterns
Pattern Logic
n=7
for i in range(1, n + 1):
*
for j in range(i, n):
***
***** print(" ", end="")
******* for k in range(1, 2 * i):
********* print("*", end="")
print()
Pattern Logic
n=7
for i in range(1, n + 1):
for j in range(i, n):
*
* * print(" ", end="")
* * for k in range(1, 2 * i):
* * if i == 1 or i == n or k == 1 or k == 2 * i - 1:
********* print("*", end="")
else:
print(" ", end="")
print()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 70
Pattern Logic
1 n=7
222 for i in range(1, n + 1):
33333
for j in range(i, n):
4444444
555555555 print(" ", end="")
for k in range(1, 2 * i):
print(i, end="")
print()
A
M
Reverse Pyramid Patterns E
Pattern Logic E
n=7 R
for i in range(n, 0, -1): P
********* for j in range(i, n): E
*******
print(" ", end="") T
*****
*** for k in range(1, 2 * i):
T
* print("*", end="")
E
print()
C
H
N
Pattern Logic
O
n=7
L
for i in range(n, 0, -1):
O
for j in range(i, n): G
*********
* * print(" ", end="") I
* * for k in range(1, 2 * i): E
* * if i == 1 or i == n or k == 1 or k == 2 * i - 1: S
* print("*", end="")
else:
print(" ", end="")
print()
Pattern Logic
n=7
for i in range(n, 0, -1):
555555555
4444444 for j in range(i, n):
33333 print(" ", end="")
222 for k in range(1, 2 * i):
1 print(i, end="")
print()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 71
Pattern Logic
r=6
for i in range(r):
c=1
1
1 1 for s in range(r - i):
1 2 1 print(" ", end=" ")
1 3 3 1 for j in range(i + 1):
1 4 6 4 1 if j == 0 or i == 0:
1 5 10 10 5 1 c=1
else:
c = c * (i - j + 1) // j
print(f"{c:4d}", end=" ")
print()
for i in range(5, 0, -1):
for j in range(5 - i, 0, -1):
123454321
print(" ", end="")
1234321
12321 for j in range(1, i + 1):
121 print(j, end="")
1 for j in range(i - 1, 0, -1):
print(j, end="")
print()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 72
Pattern Logic
n=7
for i in range(1, n + 1):
for j in range(i, n):
print(" ", end="")
1 for k in range(i, 0, -1):
212 print(k, end="")
32123 for l in range(2, i + 1):
4321234 print(l, end="")
543212345
print()
Pattern Logic
n=7
for i in range(n, 0, -1):
for j in range(i, n):
543212345
4321234 print(" ", end="")
32123 for k in range(i, 0, -1):
212 print(k, end="")
1 for l in range(2, i + 1):
print(l, end="")
print()
Pattern Logic
n=7
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 73
Functions in Python
Functions:
• A block of instructions that performs a task.
• Function takes input, process the input and returns the output.
• “def” is a keyword is used to define functions in python programming.
Syntax:
def identity(arguments) :
……
Logic
……
Ex:
def add(a, b):
c=a+b
return c
Definition:
def add(a, b):
c=a+b
return c
Call:
res = add(10,20)
def fun():
print("Hello...")
return
fun() # calling
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 74
Note : We cannot call a function before it has defined.
fun() # error :
def fun():
print("Hello...")
return
The main advantage of functions is code re-usability. We can call the function many times
once we defined.
def test():
print("logic..")
return
test()
test()
test()
One source file(.py file) can have more than one function definition. Functions get
executed in the order we invoke.
def m1():
print("m1.....")
return
def m2():
print("m2.....")
return
m2()
m1()
def m2():
print("control in m2...")
m1() #calling
print("control back to m2 from m1...")
return
print("Program starts...")
m2() #calling
print("Program ends...")
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 75
Classification of functions: The way of passing input and returning output, functions classified
into
1. No arguments and No return values
2. With arguments and No return values
3. With arguments and With return values
4. No arguments and With return value
5. Recursion
greet() display_message()
import os def print_pattern():
for i in range(1, 6):
def clear_screen(): print('*' * i)
os.system('clear') # For Unix/Linux
print_pattern()
clear_screen()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 76
With arguments and with return values:
• Defining a function with arguments and return values
• The value returned by function need to collect into variable.
• Function returned value back to the calling function.
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 77
No arguments and with return values:
• Defining a function with no arguments
• Function returns a value from its definition.
def getPI(): def get_user_name():
PI = 3.142 return input("Enter your name: ")
return PI
user_name = get_user_name()
print("PI value :",getPI()) print("Hello, " + user_name + "!")
Recursion:
• Function calling itself is called recursion.
• Calling the function from the definition of same function.
• Function executes from the allocated memory called STACK.
• While executing the program, if the stack memory is full, the program execution
terminates abnormally.
Recursion codes:
def factorial(n):
def tutorials(): if n == 0:
print("Keep reading...") return 1
tutorials() else:
return return n * factorial(n - 1)
number = 12345
count = count_digits(number)
print(f"The number {number} has {count} digits")
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 78
Argument type functions: Depends on the way of passing input and taking input, functions in
python classified into
1. Default arguments function
2. Required arguments function
3. Keyword arguments function
4. Variable arguments function
def default(a,b=20):
print("a val :",a)
print("b val :",b)
return
default(10)
default(50,100)
default(10,"abc")
def default(a=10,b):
print("a val :",a)
print("b val :",b)
return
def required(a,b):
print("a val :",a)
print("b val :",b)
return
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 79
Keyword arguments function:
• Calling the function by passing values using keys.
• We use arguments names as keys.
keyword("Annie",21)
keyword(23,"Amar")
We can change the order of arguments while passing values using keys.
def keyword(name, age):
print("Name is :",name)
print("Age is :",age)
return
keyword(age=23,name="Amar")
default()
# I want to change value of b=50
default(10,50,30)
# It is easy to use keyword arguments
default(b=50)
variable()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 80
We can pass different types of data elements also
def variable(*arr):
print("Elements :",arr)
return
variable(10,20,30,40,50)
variable(10,2.3,"abc")
variable(10,20,30,40,50)
def test():
a=10 #local
print("Inside :",a)
return
test()
print("Outside :",a) #error :
Arguments(parameters):
• Variables used to store input of the function.
• Arguments are working like local variables.
• Arguments can access within that function only.
test(10,20)
print("Outside :",a) #error
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 81
Global variables:
• Defining a variable outside to all the functions.
• We can access the variable directly.
• It is available throughout the application.
a=10 #global
def m1():
print("Inside m1 :",a)
return
def m2():
print("Inside m2 :",a)
return
m1()
m2()
print("Outside :",a)
• We can define local & global variables with the same name.
• We access both the variables directly using its identity.
• When we access a variable inside the function, it gives the first priority to local variable.
• If local is not present, then it is looking for Global variable.
a=10 #global
def m1():
a=20 #local
print("Inside m1 :",a)
return
def m2():
print("Inside m2 :",a)
return
m1()
m2()
print("Outside :",a)
global:
• It is a keyword.
• It is used to define, access, modify & delete global variables from the function.
• global statement must be placed inside the function before the use of that variable.
Note: We can access global variable inside the function. We cannot modify the global variable
from function directly.
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 82
a=10
def test():
print("a val :",a)
a=a+20 #error :
print("a val :",a)
return
test()
We can use global keyword to modify the global variable from the function:
a=10
def test():
global a
print("a val :",a)
a=a+20
print("a val :",a)
a=a+30
return
test()
print("a val :",a)
test()
print("Outside :",a)
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 83
Introduction to OOPS
Application:
• Programming Languages and Technologies are used to develop applications.
• Application is a collection of Programs.
• We need to design and understand a single program before developing an application.
1. Identity:
o Identity of a program is unique.
o Programs, Classes, Variables and Methods having identities
o Identities are used to access these members.
2. Variable:
o Variable is an identity given to memory location.
or
o Named Memory Location
o Variables are used to store information of program(class/object)
Syntax Examples
3. Method:
• Method is a block of instructions with an identity
• Method performs operations on data(variables)
• Method takes input data, perform operations on data and returns results.
Syntax Example
identity(arguments): add(int a, int b):
body c = a+b
return c
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 84
Object Oriented Programming:
• Python is Object Oriented.
• Python is Fully Object Oriented because it doesn't support primitive data types.
• Languages which are supporting primitive types are called, Partial Object oriented
programming languages.
• for example C++, Java, .Net...
Note: Primitive types such as int, float, char occupies fixed memory size and stores specific type
of data.
Python is Dynamic:
• Python is dynamic
• Python variable stores address instead of data directly.
• Python stores information in the form of Objects.
• Depends on the data, the size of memory grows and shrinks dynamically.
• A python variable accepts any type of data assignment.
a=a+5
print("Val :",a)
print("Addr :",id(a))
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 85
Object Oriented Programming features are:
1. Encapsulation
2. Inheritance
3. Polymorphism
4. Abstraction
Class: Class contains variables and methods. Java application is a collection of classes
Syntax Example
class Account:
num;
class ClassName: balance;
Variables ; withdraw():
& logic;
Methods ;
deposit():
logic;
Object: Object is an instance of class. Instance (non static) variables of class get memory inside
the Object.
Note: Class is a Model from which we can define multiple objects of same type
Encapsulation:
• The concept of protecting the data with in the class itself.
• Implementation rules:
o Class is Public (to make visible to other classes).
o Variables are Private (other objects cannot access the data directly).
o Methods are public (to send and receive the data).
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 86
Inheritance:
• Defining a new class by re-using the members of other class.
• We can implement inheritance using “extends” keyword.
• Terminology:
o Parent/Super class: The class from which members are re-used.
o Child/Sub class: The class which is using the members
Abstraction:
• Abstraction is a concept of hiding implementations and shows functionality.
• Abstraction describes "What an object can do instead how it does it?".
Polymorphism:
• Polymorphism is the concept where object behaves differently in different situations.
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 87
Class Members or Static members:
• Defining variable or method inside the class.
• We can access these members using class name.
Note: Generally, we access the variables and functions directly after definition.
a=10
def test():
print("test")
return
print("a val :",a)
test()
• In Object Oriented application, variables and methods must be defined inside the class.
• “class” is a keyword.
• Defining variable and method inside the class called “static members”
• We need to access static members using identity of class.
class Test:
a=10 # static
def fun():
print("static fun")
return
print("a val :",Test.a)
Test.fun()
Connect classes:
• One python file allowed to define any number of classes
• We can access the members of these classes using “class names”
class First:
def fun():
print("First class fun")
return
class Second:
def fun():
print("Second class fun")
return
class Access:
def main():
print("starts @ main")
First.fun()
Second.fun()
return
Access.main()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 88
Local and Static variables:
• Defining a variable inside method is called local variable
• We access local variables directly but only from the same block in which it has defined.
• Defining a variable inside the class and outside to all methods is called static variable.
• We can access static variable using class name.
class Access:
a=10 #static
def main():
a=20 #local
print("local a :", a)
print("static a :", Access.a)
return
Access.main()
Global variables:
• Defining variables outside to all classes.
• We access global variables directly.
• When we access variable inside the method, it is looking for local variable first. If the
local variable is not present, it accesses the global variable.
a=10 #Global
class Access:
a=20 #Static
def m1():
a=30 #Local
print("Inside m1")
print(a)
print(Access.a)
return
def m2():
print("Inside m2")
print(a)
print(Access.a)
return
def main():
Access.m1()
Access.m2()
return
Access.main()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 89
Dynamic members
Dynamic Members:
• The specific functionality of Object must be defined as dynamic.
• We access dynamic members using object.
• We can create object for a class from static context.
Dynamic method:
• Defining a method inside the class by writing “self” variable as first argument.
• “self” is not a keyword.
• “self” is a recommended variable to define Dynamic methods.
• Definition of dynamic method as follows.
class Test:
def m1():
# static method
return
def m2(self):
# dynamic method
return
def __init__(self):
# constructor
return
self:
• It is used to define dynamic methods and constructor.
• It is not a keyword but it is the most recommended variable to define dynamic
functionality.
• It is an argument(local variable of that function)
• We can access “self” only from the same function or constructor.
• “self” variable holds object address.
Constructor:
• A special method with pre-defined identity( __init__).
• It is a dynamic method(first argument is self)
• It invokes automatically in the process of Object creation.
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 90
Creating object in main():
• Application execution starts from static context(main).
• We can access non static members using object address.
• We create object(take permission) in static context(main)
class Test:
def __init__(self):
print("Constructor")
return
def main():
Test() #access constructor
return
Test.main()
def main():
for i in range(10):
Test()
return
Test.main()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 91
Program that display address of object created:
class Test:
def __init__(self):
print("Address :",self)
return
def main():
Test()
return
Test.main()
Test()
class Test:
def __init__(self):
print("Name :",type(self))
return
Test();
Test()
print("In main :", id(self))
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 92
Object reference variable:
• Constructor returns address of Object after creation.
• We can collect the address assigning to any variable.
• The variable stores object address is called “Object reference variable”
def main():
addr = Test()
print("In main :", id(addr))
return
Test.main()
def m2(self):
# dynamic method
return
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 93
Default constructor:
• In object creation process, constructor executes implicitly.
• When we don’t define any constructor, a default constructor will be added to the source
code.
• Default constructor has empty definition – no logic.
class Test:
def main():
x = Test()
y = Test()
print("Address of x : ", id(x))
print("Address of y : ", id(y))
return
Test.main()
We can define the default constructor explicitly to understand the object creation process.
class Test:
def __init__(self):
print("Object Created :", id(self))
return
def main():
x = Test()
y = Test()
print("Address of x : ", id(x))
print("Address of y : ", id(y))
return
Test.main()
def m1():
print("Static method")
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 94
return
def m2(self):
print("Dynamic method")
return
Test.main()
Dynamic variables:
Static Variables Dynamic Variables
Static variables store common information of We create dynamic variables inside the object
Object. using ‘self’ variable.
Static variables get memory only once. Variables creation must be from constructor.
We can access static variables using class We can access the variables through object
Name address.
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 95
return
def main():
obj = Test()
print("x val :", obj.x)
print("y val :", obj.y)
return
Test.main()
Note: In the above program, if we assign values directly to dynamic variables, all objects
initializes with same set of values.
class Test:
def __init__(self):
self.a = 10
return
def main():
t1 = Test()
print("t1 a val :", t1.a)
t2 = Test()
print("t2 a val :", t2.a)
return
Test.main()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 96
Arguments constructor:
• Constructor taking input values to initialize dynamic variables in Object creation
process.
• Using arguments constructor, we can set different values to different object variables.
• Arguments are local variables and we can access directly.
class Test :
def __init__(self, a, b):
self.x = a
self.y = b
return
def main():
obj = Test(50,60)
print("x val :", obj.x)
print("y val :", obj.y)
return
Test.main()
• Local variables and dynamic variables can have the same identity.
• We access the local variable directly where as dynamic variable using object address.
class Test:
def __init__(self,a,b):
self.a = a
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 97
self.b = b
return
def main():
obj = Test(10,20)
print("a val :", obj.a)
print("b val :", obj.b)
return
Test.main()
def details(self):
print("a val :", self.a)
print("b val :", self.b)
return
def main():
print("Enter a, b values :")
a = input()
b = input()
obj = Test(a,b)
obj.details()
return
Test.main()
def details(self):
print("Emp num is :", self.num)
print("Emp name is :", self.name)
return
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 98
print("Enter emp details :")
num = int(input())
name = input()
obj = Emp(num, name)
obj.details()
def deposit(self,amt):
self.balance=self.balance+amt
print(amt,"deposited")
return
def withdraw(self,amt):
print("Withdrawing :",amt)
print("Avail bal :",self.balance)
if(amt<=self.balance):
print("Collect cash :",amt)
self.balance=self.balance-amt
else:
print("Error : Low balance")
return
class Bank:
def main():
amt = int(input("Enter initial bal : "))
acc = Account(amt)
print("Balance is :",acc.balance)
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 99
Access Modifiers
Access Modifiers:
• Access modifiers are used to set permissions to access the data.
• Python supports 3 access modifiers.
o private( _ _var)
o protected ( _var)
o public ( var)
public:
• We can access public members (variables or methods) directly.
• All programs discussed before contains public variables and methods.
class Test:
a=10
def __init__(self,b):
self.b = b
return
class Access:
def main():
obj = Test(20)
print("a val :", Test.a)
print("b val :", obj.b)
return
Access.main()
Private members:
• A member definition preceded by _ _ is called private member.
• One object(class) cannot access the private members of another object directly.
Note: A class itself can access the private members.
class First:
a = 10 #public
__b = 20 #private
def main():
print("a val :", First.a)
print("b val :", First.__b)
return
First.main()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 100
Accessing private members of another class results Error:
class First:
a = 10 #public
__b = 20 #private
class Second:
def main():
print("a val :", First.a)
print("b val :", First.__b)
return
Second.main()
def main():
obj = First(10,20)
print("a val : ", obj.a)
print("b val : ", obj.__b)
return
First.main()
class Second:
def main():
obj = First(10,20)
print("a val : ", obj.a)
print("b val : ", obj.__b)
return
Second.main()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 101
Accessing private variables from another class:
• One class cannot access the private information from another class directly.
• A class(object) is allowed to share(send or receive) the private data in communication.
• Communication between objects is possible using methods.
• Two standard methods get() and set() to share the information.
class First:
__a = 10
def getA():
return First.__a
class Second:
def main():
# print("a val : ", First.__a)
print("a val : ", First.getA())
return
Second.main()
def getA(self):
return self.__a
class Second:
def main():
obj = First(10)
# print("a val : ", obj.__a)
print("a val : ", obj.getA())
return
Second.main()
Note: When we try set the value directly to private variable, the value will be omitted.
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 102
class First:
__a=10
def getA():
return First.__a
def setA(a):
First.__a = a
return
class Second:
def main():
print("a val :", First.getA())
First.__a=20
print("a val :", First.getA())
First.setA(20)
print("a val :", First.getA())
return
Second.main()
class Second:
def main():
obj = First(10)
print("a val :", obj.getA())
obj.setA(20)
print("a val :", obj.getA())
return
Second.main()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 103
Encapsulation: The concept of protecting object information.
Rules:
1. Class is public – Object is visible to other objects in communication.
2. Variables are private – One object cannot access the information of other object
directly.
3. Communication between objects using get() and set() methods to share the
information.
class Emp:
def __init__(self,num,name,salary):
self.__num = num
self.__name = name
self.__salary = salary
return
def getNum(self):
return self.__num
def getName(self):
return self.__name
def getSalary(self):
return self.__salary
def setNum(self,num):
self.__num = num
return
def setName(self,name):
self.__name = name
return
def setSalary(self,salary):
self.__salary = salary
return
class Access:
def main():
print("Enter Emp details :")
num = int(input("Emp Num : "))
name = input("Emp Name : ")
salary = float(input("Emp Sal : "))
obj = Emp(num, name, salary)
print("Name :",obj.getName())
return
Access.main()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 104
Inheritance in Python
Inheritance:
• Defining an object by re-using the functionality of existing object.
• The main advantage of inheritance in code re-usability.
Terminology of inheritance :
• Parent – Child class
• Super – Sub class
• Base – Derived class
.
Types of Inheritance:
• Python supports all types of inheritance supported by Object Oriented Programming.
• The following diagram represents all types
Single Inheritance:
• In parent-child relation, we can access the functionality of Parent through child.
• We cannot access Child functionality using Parent.
• Accessing static members in Parent and Child as follows:
class Parent:
def m1():
print("Parent's m1")
return
class Child(Parent):
def m2():
print("Child's m2")
return
class Inheritance:
def main():
Child.m1()
Child.m2()
Inheritance.main()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 105
Accessing dynamic functionality in Parent-Child relation:
class Parent:
def m1(self):
print("Parent's m1")
return
class Child(Parent):
def m2(self):
print("Child's m2")
return
class Inheritance:
def main():
c = Child()
c.m1()
c.m2()
Inheritance.main()
Method overriding:
• Defining a method in the Child class with same name and same set of arguments of
Parent class method.
• When two methods in Parent and Child with the same identity, it gives the first priority to
Child object.
class Parent:
def fun(self):
print("Parent's fun()")
return
class Child(Parent):
def fun(self): #override
print("Child's fun()")
return
class Inheritance:
def main():
obj = Child()
obj.fun()
return
Inheritance.main()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 106
Advantage of overriding:
• Overriding is the concept of updating existing object functionality when it is not
sufficient to extended object.
• Re-writing the function logic with the same identity.
class Guru:
def call(self):
print("Guru - Call")
return
def camera(self):
print("Guru - Camera - 2MP")
return
class Galaxy(Guru):
def videoCall(self):
print("Galaxy - Video Call")
return
def camera(self):
print("Galaxy - Camera - 8MP")
return
class Inheritance:
def main():
g1 = Galaxy()
g1.call()# Access existing
g1.videoCall()# new feature
g1.camera() #updated
g2 = Guru()
g2.call()
g2.camera()
g2.videoCall() # error:
return
Inheritance.main()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 107
Accessing overridden functionality of Parent class:
super():
• It is pre-defined method.
• It is used to access Parent class functionality(super) from Child(sub).
class Grand:
def fun(self):
print("Grand")
return
class Parent(Grand):
def fun(self):
super().fun()
print("Parent")
return
class Child(Parent):
def fun(self):
super().fun()
print("Child")
return
class Inheritance:
def main():
obj = Child()
obj.fun()
return
Inheritance.main()
• We can access the functionality of all classes in the hierarchy from one place using
super() method.
• We need to specify the Class type along with object reference variable.
• If we specify the Child type, it access Parent functionality.
class Grand:
def fun(self):
print("Grand")
return
class Parent(Grand):
def fun(self):
print("Parent")
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 108
return
class Child(Parent):
def fun(self):
print("Child")
return
class Inheritance:
def main():
obj = Child()
obj.fun()
super(Child, obj).fun()
super(Parent, obj).fun()
return
Inheritance.main()
class A:
def m1(self):
print("A-m1")
return
def m3(self):
print("A-m3")
return
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 109
class B:
def m1(self):
print("B-m1")
return
def m2(self):
print("B-m2")
return
class C(A,B):
def m3(self):
print("C-m3")
return
class Multiple:
def main():
c = C()
c.m3()
c.m2()
c.m1()
return
Multiple.main()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 110
Accessing the complete functionality of all objects in multiple inheritance:
class A:
def m1(self):
print("A-m1")
return
def m3(self):
print("A-m3")
return
class B:
def m1(self):
print("B-m1")
return
def m2(self):
print("B-m2")
return
class C(A,B):
def m3(self):
print("C-m3")
return
class Multiple:
def main():
obj = C()
obj.m1()
obj.m2()
obj.m3()
super(C,obj).m1()
super(C,obj).m2()
A.m3(obj)
B.m1(obj)
return
Multiple.main()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 111
Hybrid inheritance:
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 112
Polymorphism in Python
Polymorphism:
• Defining an object(class) that shows different behavior(methods) with the same identity.
• Polymorphism is of 2 types
o Compile time polymorphism
o Runtime polymorphism
Note: Python doesn’t support method overloading. When we define a duplicate method,
existing method will be replaced.
class Calc:
def add(a,b):
res=a+b
print("Sum of 2 num's :", res)
return
class Overload:
def main():
Calc.add(10,20,30)
Calc.add(10,20) # error
return
Overload.main()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 113
class Calc:
def add(a,b):
res=a+b
print("Sum :", res)
return
class Overload:
def main():
Calc.add(10,20)
Calc.add(2.3,4.5)
Calc.add("Python","Class")
return
Overload.main()
Python supports variables arguments function. We can pass different length of arguments
to a single method.
class Calc:
def add(*arr):
l = len(arr)
sum = 0
for ele in arr:
sum = sum+ele
print("Sum of",l,"elements :",sum)
return
class Overload:
def main():
Calc.add(10,20)
Calc.add(10,20,30)
Calc.add(10,20,30,40,50)
return
Overload.main()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 114
Runtime Polymorphism:
• It is called “dynamic binding”.
• It is method “overriding technique”.
• Overriding is the concept of defining a method in Child class with the same name and
same set of arguments in Parent class method.
• A Child object can shows the functionality of Parent and Child. Hence it is called
Polymorphic
class Grand:
def fun(self):
print("Grand")
return
class Parent(Grand):
def fun(self):
print("Parent")
return
class Child(Parent):
def fun(self):
print("Child")
return
class Override:
def main():
obj = Child()
obj.fun()
super(Child,obj).fun()
super(Parent,obj).fun()
return
Override.main()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 115
Exception Handling in Python
Exception Handling:
• Exception is a Class
• Exception is a Runtime Error
• When exception rises, the flow of execution will be terminated with informal information
to the user.
Division by Zero: This program attempts to divide 10 by 0, which will raise a ZeroDivisionError
because division by zero is undefined.
result = 10 / 0
Accessing an Index Out of Range: This program tries to access an element at index 5 in a list
with only 3 elements. It will raise an IndexError because the index is out of range.
my_list = [1, 2, 3]
element = my_list[5]
Value Error (Type Conversion): Here, we attempt to convert the string "abc" to an integer
using int(). This will raise a ValueError because "abc" is not a valid integer.
value = int("abc")
Except:
• Except block is used to collect and handle the exception object which is raised in try
block.
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 116
Division by Zero Exception Handling:
try:
result = 5 / 0
except ZeroDivisionError as e:
print("Error:", e)
print("Division by zero is not allowed.")
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 117
try with multi except: One try block can have more than one except blocks to handle different
types of exceptions occur in different lines of code. Only one except block executes among we
defined.
try:
print("Enter 2 numbers:")
x = int(input())
y = int(input())
print("Result:", x / y)
except ValueError:
print("Exception: Invalid input")
except ZeroDivisionError:
print("Exception: Denominator should not be zero")
print("End")
except IndexError:
print("Exception: Index out of range.")
except ValueError:
print("Exception: Invalid index input.")
print("End")
Exception class:
• “Exception” is pre-defined class.
• “Exception” is the Parent class of all other exception classes.
• Instead of handling multiple exceptions with number of except blocks, we can specify
“Exception” type to handle all.
• We need to provide the common the error information to handle using “Exception” class.
Note: We can display the message of Exception object by collecting into variable in “except”
block.
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 118
try:
print("Enter 2 numbers:")
x = int(input())
y = int(input())
print("Result:", x / y)
except Exception:
print("Exception: Denominator should not be zero")
print("End")
Finally block: It is used to provide “Resource releasing logic”. All resources (connected to
program) must be closed from finally block.
Note: Finally block executes whether or not an exception has raised in the try block.
class Finally:
def main():
try:
x = 10/5
print("Try block")
except Exception:
print("Except block")
finally:
print("Finally block")
return
Finally.main()
except Exception:
print("Except block")
finally:
print("Finally block")
return
Finally.main()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 119
Open and Close the File using Finally block:
• open() is pre-defined and it is used to open the file in specified path.
• If the file is not present, it raises Exception.
except FileNotFoundError:
print("Exception: No such file")
try:
file = open("sample.txt")
print("File opened...")
except FileNotFoundError:
print("Exception: No such file")
finally:
if file is not None:
file.close()
except FileNotFoundError:
print("Exception: No such file")
finally:
if 'file' in locals() and not file.closed:
file.close()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 120
Opening a file using class:
class Finally:
def main():
try:
file = open("sample.txt")
print("File opened...")
except FileNotFoundError:
print("Exception: No such file")
Finally.main()
except FileNotFoundError:
print("Exception : No such file")
finally:
if Finally.file != None:
Finally.file.close()
print("File closed...")
return
Finally.main()
Custom Exceptions:
• Python library is providing number of exception classes.
• As a programmer, we can define custom exceptions depends on application
requirement.
• Every custom exception should extends the functionality of pre-defined Exception class.
raise:
• It is a keyword.
• It is used to raise Custom Exception explicitly by the programmer.
• Pre-defined exceptions will be raised automatically when problem occurs.
• If we don’t handle the exception, Default Exception Handler handles.
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 121
class CustomError(Exception):
def __init__(self,name):
self.name=name
return
class RaiseException:
def main():
obj = CustomError("Error-Msg")
raise obj
return
RaiseException.main()
class Test:
def fun():
obj = CustomError("Message")
raise obj
return
class Access:
def main():
try:
Test.fun()
except CustomError as e:
print("Exception :",e)
return
Access.main()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 122
The following example explains how to define Runtime Errors in Banking trasactions.
class LowBalanceError(Exception):
def __init__(self,name):
self.name = name
return
class Account:
def __init__(self,balance):
self.balance = balance
return
def withdraw(self,amount):
print("Trying to withdraw :",amount)
print("Avail bal :",self.balance)
if amount <= self.balance:
print("Collect cash :",amount)
self.balance=self.balance-amount
else:
err=LowBalanceError("Low Balance")
raise err
return
class Bank:
def main():
amount = int(input("enter amount :"))
acc = Account(amount)
print("Balance is :",acc.balance)
Bank.main()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 123
Inner classes
Inner class: Defining a class inside another class. It is also called Nested class.
Syntax:
class Outer:
.....
logic
.....
class Inner:
.....
logic
.....
class Outer:
def m1():
print("Outer-m1")
return
class Inner:
def m2():
print("Inner-m2")
return
class Access:
def main():
Outer.m1()
Outer.Inner.m2()
return
Access.main()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 124
class Outer:
def m1(self):
print("Outer-m1")
return
class Inner:
def m2(self):
print("Inner-m2")
return
class Access:
def main():
obj1 = Outer()
obj1.m1()
obj2 = obj1.Inner()
obj2.m2()
return
Access.main()
class Access:
def main():
#obj1 = Outer()
#obj2 = obj1.Inner()
#obj2.fun()
Outer().Inner().fun()
return
Access.main()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 125
Local inner classes:
• Defining a class inside the method.
• To access that class, first control should enter into that function.
• We invoke the functionality of local inner class from that function.
class Outer:
def fun():
print("Outer-fun")
class Local:
def fun():
print("Outer-Local-fun")
return
Local.fun()
return
class Access:
def main():
Outer.fun()
return
Access.main()
class Local:
def fun():
print("m1-Local-fun")
return
Local.fun()
return
def m2():
print("Outer-m2")
class Local:
def fun():
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 126
print("m2-Local-fun")
return
Local.fun()
return
class Access:
def main():
Outer.m1()
Outer.m2()
return
Access.main()
We can define a local inner class inside another local inner class. But it is complex to
access the functionality.
class Outer:
def fun(self):
print("Outer-fun")
class Local:
def fun(self):
print("Outer-Local-fun")
class Inner:
def fun(self):
print("Outer-Local-Inner-fun")
return
Inner().fun()
return
Local().fun()
return
class Access:
def main():
Outer().fun()
return
Access.main()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 127
Python Modules
Importance of Modularity:
• When people write large programs they tend to break their code into multiple different
files for ease of use, debugging and readability.
• In Python we use modules to achieve such goals.
• Modules are nothing but files with Python definitions and statements.
• The name of the file should be valid Python name (think about any variable name) and in
lowercase
Pre-defined modules:
• threading : To implement Parallel processing
• gc : For Garbage collection
• tkinter : To implement GUI programming
• time : To find system time and data and to display in different formats
• numpy : One, two and Multi dimensional
• re : Regular expressions
• mysql : Python – MySQL database connectivity
arithmetic.py:
def add(a,b):
c=a+b
return c
def subtract(a,b):
c=a-b
return c
def multiply(a,b):
c=a*b
return c
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 128
calc.py:
import arithmetic
res = arithmetic.add(a,b)
print("Add result :",res)
res = arithmetic.subtract(a,b)
print("Subtract result :",res)
res = arithmetic.multiply(a,b)
print("Multiply result :",res)
Why we need to call the function using module name after import?
• We can define members with same identity in different modules
• We access the duplicate members from different modules by using the identity of
module while accessing.
one.py:
def f1():
print("one-f1()")
return
def f2():
print("one-f2()")
return
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 129
two.py:
def f1():
print("two-f1()")
return
def f2():
print("two-f2()")
return
access.py:
import one
import two
one.f1()
one.f2()
two.f1()
two.f2()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 130
one.py:
class ABC:
def m1():
print("one-ABC-m1()")
return
class XYZ:
def m2(self):
print("one-XYZ-m2()")
return
access.py:
import one
class Access:
def main():
one.ABC.m1()
obj = one.XYZ()
obj.m2()
return
Access.main()
from:
• “from is a keyword used to access one or more classes from the specified module.
• Note that, no need to specify the module name along with class name if we import using
“from”
Syntax:
from module import class
Or
from module import *
Or
from module import class1, class2, class3
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 131
Accessing duplicate classes from different modules:
One.py:
class ABC:
def m1():
print("one-ABC-m1()")
return
class XYZ:
def m2():
print("one-XYZ-m2()")
return
two.py:
class ABC:
def m1():
print("two-ABC-m1()")
return
class XYZ:
def m2():
print("two-XYZ-m2()")
return
access.py:
import one
import two
class Access:
def main():
one.ABC.m1()
one.XYZ.m2()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 132
two.ABC.m1()
two.XYZ.m2()
return
Access.main()
• When we import classes using ‘from’ keyword, we cannot work with duplicate classes
from different modules.
• Duplicate class replace the existing class as follows
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 133
Multi threading
Multi-tasking:
• We can implement multi-tasking in two ways.
o Program(process) based
o Sub program(thread) based.
Multi threading:
• Task is a program( or process)
• Thread is a sub program ( or sub process)
• We can execute multiple threads from single process.
• Using multi-threading, we can reduce the stress on processor.
Creating Thread:
• Python provides a threading module that allows you to create and manage threads in
your program.
• To create a new thread, you can define a new class that extends the threading.Thread
class and override the run() method.
# Example:
import threading
class MyThread(threading.Thread):
def run(self):
# Code to be executed in the new thread
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 134
You can start a new thread by creating an instance of the class and calling its start()
method.
# Example:
my_thread = MyThread()
my_thread.start()
class Numbers:
def display(self):
for i in range(50):
print("i val :",i)
return
class Default:
def main():
print("Starts @ main")
obj = Numbers()
obj.display()
for j in range(50):
print("j val :",j)
print("Ends @ main")
return
Default.main()
class Default:
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 135
def main():
obj = Custom()
obj.start()
for j in range(50):
print("Default :" + str(j))
return
Default.main()
sleep():
• A pre-defined method belongs to “time” module.
• Sleep() method is used to stop the current thread execution for specified number of
seconds.
• The following example explains clearly about sleep() method.
class Custom(Thread):
def run(self):
for i in range(1,11):
print("custom : " + str(i))
time.sleep(1)
return
class Default:
def main():
obj = Custom()
obj.start()
for i in range(1,11):
print("default : " + str(i))
time.sleep(1)
return
Default.main()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 136
from threading import Thread
import time
class Custom(Thread):
def run(self):
for i in range(1,11):
print("custom : " + str(i))
time.sleep(1)
print("Custom thread execution completed")
return
class Default:
def main():
print("Starts at Default thread")
obj = Custom()
obj.start()
for i in range(1,11):
print("default : " + str(i))
time.sleep(0.3)
print("Default thread execution completed")
return
Default.main()
class Custom(Thread):
def run(self):
for i in range(1,11):
print("custom : " + str(i))
time.sleep(1)
return
class Default:
def main():
obj = Custom()
obj.run()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 137
for i in range(1,11):
print("default : " + str(i))
time.sleep(1)
return
Default.main()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 138
How to execute different logics from different threads?
class Custom1(Thread):
def run(self):
for i in range(1,11):
print("custom1 :" + str(i))
time.sleep(1)
return
class Custom2(Thread):
def run(self):
for i in range(50,71):
print("custom2 :" + str(i))
time.sleep(1)
return
class Custom3(Thread):
def run(self):
for i in range(100,90,-1):
print("custom3 :"+str(i))
time.sleep(3)
return
class Default:
def main():
c1 = Custom1()
c1.start()
c2 = Custom2()
c2.start()
c3 = Custom3()
c3.start()
return
Default.main()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 139
join() method:
• It is a dynamic method belongs the Thread class.
• It is used to stop current thread execution until joined thread moved to dead state.
class Custom(Thread):
def run(self):
for i in range(1,11):
print("custom : " + str(i))
time.sleep(1)
return
class Default:
def main():
print("Starts @ Default")
c = Custom()
c.start()
c.join()
print("Ends @ Default")
return
Default.main()
Thread synchronization:
• The concept of allowing threads sequentially when these threads trying to access same
resource parallel.
• “threading” module is providing “Lock” class to implement thread synchronization.
• Lock class is providing dynamic methods to lock specific logic in the function.
o obj = Lock()
o obj.acquire()
o obj.release()
import time
from threading import Thread, Lock
class Numbers:
x=0
lock=Lock()
def incrementX():
Numbers.lock.acquire()
Numbers.x = Numbers.x+1
Numbers.lock.release()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 140
return
class Custom1(Thread):
def run(self):
for i in range(100000):
Numbers.incrementX()
return
class Custom2(Thread):
def run(self):
for i in range(100000):
Numbers.incrementX()
return
class Default:
def main():
t1 = Custom1()
t2 = Custom2()
t1.start()
t2.start()
t1.join()
t2.join()
print("Final x val : "+str(Numbers.x))
return
Default.main()
You can also create a thread using the threading.Thread() constructor and passing in a
target function as an argument.
# Example:
import threading
def my_function():
# Code to be executed in the new thread
my_thread = threading.Thread(target=my_function)
my_thread.start()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 141
This program creates two threads that run concurrently and print numbers from 1 to 5.
import threading
def print_numbers():
for i in range(1, 6):
print(f"Number {i}")
thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_numbers)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print("End of program")
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print("End of program")
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 142
Strings
String: String is a sequence of characters. We can specify strings using single, double or triple
quotes.
Accessing strings: We can access the strings using indexing and slicing
Indexing:
• String array elements index starts with 0
• Using indexing, we can process each character.
• Python supports negative indexing from the end.
• Negative indexing starts with -1 from the end.
s = "python"
print("s[2] :", s[2])
print("s[-3] :", s[-3])
s = "python"
print("String is :",s)
print("s[:] :", s[:])
print("s[: :] :", s[: :])
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 143
print("s[0:6:1] :", s[0:6:1])
print("s[0:len(s)] :", s[0:len(s)])
s = "python"
print("String is :",s)
print("s[2:5] :", s[2:5])
print("s[-5:-2] :", s[-5:-2])
print("s[2:-2] :", s[2:-2])
s = "python"
print("String is :",s)
print("s[5:2:-1] :", s[5:2:-1])
print("s[-1:-5:-1] :", s[-1:-5:-1])
s1 = "abc"
print(s1,"is alpha :", s1.isalpha())
print(s1,"is alpha numeric :", s1.isalnum())
print(s1,"is digit :", s1.isdigit())
s1 = "1234"
print(s1,"is alpha :", s1.isalpha())
print(s1,"is alpha numeric :", s1.isalnum())
print(s1,"is digit :", s1.isdigit())
s1 = "abc123"
print(s1,"is alpha :", s1.isalpha())
print(s1,"is alpha numeric :", s1.isalnum())
print(s1,"is digit :", s1.isdigit())
s1 = "abc123$#"
print(s1,"is alpha numeric :", s1.isalnum())
print(s1,"is lower :", s1.islower())
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 144
Displaying Strings with Quotes: Generally a string can be represented in python using single
or double quotes.
#Escape characters
# \n = new line
# \t = tab space
# \\ = \
# \' = '
# \" = "
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 145
Python Comments:
1. Single line comments
2. Multi line comments - Not supported
String representation:
name = input("Enter your name : ")
print("Hello" , name)
print("Hello " + name)
print("Hello %s" %name)
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 146
Read and print employee details
print("Enter Emp details : ")
no = int(input())
name = input()
salary = float(input())
print(name + " with id : " + str(no) + " is taking salary : " + str(salary))
print("%s with id : %d is taking salary : %f" %(name, no, salary))
Float representation:
val = 34.567
print("Value is :", val)
print("Value is : %f" %val)
print("Value is : %.3f" %val)
print("Value is : %.2f" %val)
Immutability:
• Python is Object oriented programming language.
• Any information(Number, String or Collection) stores in Object format only.
Note: Immutable objects nothing but constants. We can’t modify once we have created
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 147
Numbers:
• Integers and Float values comes under Number type Objects.
• Once we assign any number to a variable that cannot be modified.
• If we try to modify the value, a new object will be creating with modified content.
Code:
a=10
print("a val :", a)
print("Loc :", id(a))
a=a+5
print("Modified a val :", a)
print("Loc :", id(a))
String Immutability:
s1="Hello"
s2="World"
print("s1 val :",s1)
print("s1 loc :",id(s1))
print("s2 val :",s2)
print("s2 loc :",id(s2))
s1=s1+s2
print("Modified s1 val :",s1)
print("s1 loc :",id(s1))
print("s2 val :",s2)
print("s2 loc :",id(s2))
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 148
Output:
s1 val : Hello
s1 loc : 59401472
s2 val : World
s2 loc : 59401376
Modified s1 val : HelloWorld
s1 loc : 59410896
s2 val : World
s2 loc : 59401376
When we try to create multiple String objects with the same content, duplicate objects will not
be created. The address of object will be shared.
s1="Hello"
s2="Hello"
print("s1 val :",s1)
print("s1 loc :",id(s1))
print("s2 val :",s2)
print("s2 loc :",id(s2))
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 149
Does s2 effects when we modify s1 content in the above code?
• No, String object is Immutable. When the contents are same then only locations are
same. When we modify the content, a new object will be created in another location.
s1="Hello"
s2="Hello"
print("s1 val :",s1)
print("s1 loc :",id(s1))
print("s2 val :",s2)
print("s2 loc :",id(s2))
s1 = s1+'$'
print("s1 val :",s1)
print("s1 loc :",id(s1))
print("s2 val :",s2)
print("s2 loc :",id(s2))
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 150
Collection data types
Introduction:
• We use programming languages to develop applications.
• Applications are used to store and process the information.
• In the application, when we use set of elements, it is recommended to use collection
type.
• If we can structure the data while storing, can access more effectively while processing.
• Basic data structure that store elements in consecutive locations is called array.
Note: The complete functionality of all data structures and algorithms given as 4 simple
collection objects.
1. List
2. Tuple
3. Set
4. Dictionary
As Python doesn’t support Arrays, we use third party modules (Numpy & Pandas) to
process elements like arrays.
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 151
List Collection
List:
• List is a linear data structure.
• List is an Object contains multiple data items (elements).
• Square brackets are used to enclose the elements of List.
• The elements in List are separated with comma (,) operator.
• List can accept heterogeneous data elements.
• List is allowed to store duplicate elements.
Code:
l1 = [10,20,30,40,50]
print("L1 list :",l1)
l2 = [10,20,10,"abc",34.56]
print("L2 list :",l2)
Accessing Elements: We can access elements of List in 2 ways such as Indexing & Slicing.
Indexing:
• Python index starts from 0 to size-1.
• We can access only one element through indexing.
• Python supports negative indexing also
• Some of the examples as follow.
Code:
l = [10,20,30,40,50]
print("List is :", l)
print("Length :", len(l))
print("l[2] :", l[2])
print("l[-2] :", l[-2])
print("l[len(l)-2] :", l[len(l)-2])
print("l[-(len(l)-3)] :", l[-(len(l)-3)])
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 152
Output:
List is : [10, 20, 30, 40, 50]
Length : 5
l[2] : 30
l[-2] : 40
l[len(l)-2] : 40
l[-(len(l)-3)] : 40
Slicing:
• To access more than one element at a time from the collection.
• Slicing representation is as same as range() object
Syntax:
[start-index : stop-index : step]
Code:
l = [10,20,30,40,50]
print("List is :", l)
print("Length :", len(l))
print("l[:] :", l[:])
print("l[: :] :", l[: :])
print("l[0:len(l):1] :", l[0:len(l):1])
print("l[0:5:2] :", l[0:5:2])
print("l[-5:-2] :", l[-5:-2])
Output:
List is : [10, 20, 30, 40, 50]
Length : 5
l[:] : [10, 20, 30, 40, 50]
l[: :] : [10, 20, 30, 40, 50]
l[0:len(l):1] : [10, 20, 30, 40, 50]
l[0:5:2] : [10, 30, 50]
l[-5:-2] : [10, 20, 30]
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 153
List methods:
• List is a pre-defined Object (class).
• List class is providing set of pre-defined methods(dynamic), we access using list object
address.
• Using list functionality, we can process the list elements easily.
• The functionality is used to append, insert, remove, pop, sort, reverse and update the list
as follows.
append(): Function that adds an element at the end of the List and returns the complete list
with appended element.
l = [10,20,30]
print("List :", l)
l.append(40)
print("After append 40 :", l)
count(): Function that returns the specified element count in the List
index():
• Function that returns index value of specified element.
• List supports duplicate elements.
• If the specified element is duplicated, it return first occurrence of index.
• Raises an exception if the specified element is not present in the list.
Output:
List : [10, 20, 10, 40, 20, 50]
index of 40 : 3
index of 20 : 1
ValueError: 70 is not in list
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 154
Insert():
• Function that is used to insert element at specified index.
• After insertion, other elements in the list will shift to right.
• Element will be appended if the specified index is not present in that List.
l = [10,20,10,40]
print("List :", l)
Output:
List : [10, 20, 10, 40]
insert 50 @ index : 2 :
List : [10, 20, 50, 10, 40]
insert 70 @ index : -4 :
List : [10, 70, 20, 50, 10, 40]
insert 90 @ index : 12 :
List : [10, 70, 20, 50, 10, 40, 90]
Deleting elements:
• We can remove the elements of List in many ways.
• List object is providing different methods to remove elements.
pop([index]) :
• Removes the last element from the List when we don’t specify the index.
• Index argument is optional
• We can remove the element by specifying its index also
• Raises Exception if the specified index is not present.
Code:
l = [10, 20, 30, 40, 50]
print("List is :", l)
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 155
print("pop() :", l.pop())
print("List is :", l)
Output:
List is : [10, 20, 30, 40, 50]
pop() : 50
List is : [10, 20, 30, 40]
pop(1) : 20
List is : [10, 30, 40]
IndexError: pop index out of range
remove(element):
• Removes specified element from the List.
• List allows duplicates.
• Remove the first occurrence of element if the element is duplicated.
• Raises Exception if the specified element is not present in the list.
Output:
List is : [10, 20, 30, 40, 50, 20]
remove(30) :
List is : [10, 20, 40, 50, 20]
remove(20) :
List is : [10, 40, 50, 20]
remove(70) : ValueError: list.remove(x): x not in list
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 156
clear():
• Removes all elements of List.
• Return an empty List.
• The memory allocated to list will not be de-allocated.
Code:
l = [10,20,30,40,50]
print("List is :", l)
print("append(20) :")
l.append(20)
print("List is :", l)
Output:
List is : [10, 20, 30, 40, 50]
clear list :
List is : []
append(20) :
List is : [20]
del:
• It is a keyword.
• It is used to release the memory of Object(here list variable)
Code:
l = [10,20,30,40,50]
print("List is :", l)
Output:
List is : [10, 20, 30, 40, 50]
del list :
NameError: name 'l' is not defined
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 157
extend():
• It is used to merge lists.
• One list will be appended to another list
• List1 will be modified where as List2 remains same.
Code:
l1 = [10, 20, 30]
print("L1 is :", l1)
l2 = [23.45, 56.78]
print("L2 is :", l2)
copy():
• A function that is used to copy all elements of List to another list.
• Returns a duplicate copy of specified list.
• Copied list get different memory location.
• List is Mutable (we will discuss later). Hence the location must be different for duplicate
Lists.
Code:
src = [10,20,30]
print("Source list is :", src)
print("Source list location :", id(src))
cpy = src.copy()
print("Copied list is :", cpy)
print("Copied list location :", id(cpy))
Output:
Source list is : [10, 20, 30]
Source list location : 58932360
Copied list is : [10, 20, 30]
Copied list location : 14314432
Note: Only Lists get different memory locations with same set of elements. The duplicates in
both the Lists have same memory locations as follows.
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 158
Code:
src = [10,20,30]
print("Source list location :", id(src))
cpy = src.copy()
print("Copied list location :", id(cpy))
Code:
print("List operations using operators :")
a1 = [1,2,3]
a2 = [4,5,6]
print("a1 list :", a1)
print("a2 list :", a2)
print("a1=a1+a2 :")
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 159
a1=a1+a2
print("a1 list :", a1)
Output:
List operations using operators :
a1 list : [1, 2, 3]
a2 list : [4, 5, 6]
a1=a1+a2 :
a1 list : [1, 2, 3, 4, 5, 6]
a2 list : [4, 5, 6]
a2=a2*3 :
a2 list : [4, 5, 6, 4, 5, 6, 4, 5, 6]
a1 list : [1, 2, 3, 4, 5, 6]
5 is present : True
7 is present : False
20 is not present : True
6 is not present : False
sort():
• sort all elements in the specified list
• All elements in the list should be of same type
• Heterogeneous elements list cannot sort.
Code:
a1 = [10, 40, 20, 50, 30]
print("a1 List is :",a1)
a1.sort()
print("Sorted a1 list is :", a1)
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 160
print("a2 List is :",a2)
a2.sort() # sorting possible only on homogenous data elements
print("Sorted a2 list is :", a2)
Output:
a1 List is : [10, 40, 20, 50, 30]
Sorted a1 list is : [10, 20, 30, 40, 50]
a2 List is : [34.56, 23, 'abc']
TypeError: '<' not supported between instances of 'str' and 'int'
any() : Return True if any one of List element is True. Returns False if the List is empty.
>>> arr = [1,2,0]
>>> any(arr)
True
>>> arr = [1,2,3]
>>> any(arr)
True
>>> arr = []
>>> any(arr)
False
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 161
list():
• List is a class.
• list() is a constructor
• list() is used to construct any empty list object.
arr = list()
print("List is :", arr)
print("Length :", len(arr))
print("Any :", any(arr))
Output:
List is : []
Length : 0
Any : False
Output:
Initially : []
Enter 5 elements :
10
23.42
g
abc
10
Later : ['10', '23.42', 'g', 'abc', '10']
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 162
#logic
res=0
for ele in arr:
res=res+ele
print("Sum is :", res)
Output:
Sum of list elements
Enter size : 5
Enter 5 elements :
6
4
2
8
3
Sum is : 23
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 163
Nested Lists:
• Defining a List as an element inside another list.
• List is an object; hence we connect the nested list by storing the address.
a = [10,20,30,[40,50,60]]
print("List is :", a)
# negative indexing
print("a[-2] :", a[-2])
print("a[-1] :", a[-1])
# using len()
print("len(a) :", len(a))
print("a[len(a)-1] :", a[len(a)-1])
a = [10,20,30,[40,50,60]]
print("List is :", a)
# using len()
print("len(a[-1]) :", len(a[-1]))
print("a[len(a)-1] :", a[len(a)-1])
print("a[len(a)-1][len(a[-1])-1]) :",a[len(a)-1][len(a[-1])-1])
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 164
• Using index, we can access only one element at a time.
• Through slicing, we can access multiple elements either from list or sub list.
a = [10,20,30,[40,50,60]]
print("List is :", a)
# list slicing
print("a[:] :", a[:])
print("a[: :] :", a[: :])
print("a[0:len(a):1] :", a[0:len(a):1])
print("a[2:len(a)] :", a[2:len(a)])
a = [10,20,30,[40,50,60]]
print("List is :", a)
a = [10,20,[30,40]]
print(id(a))
print(id(a[0]))
print(id(a[1]))
print(id(a[2]))
print(id(a[2][0]))
print(id(a[2][1]))
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 165
List Mutability:
• List is Mutable
• Mutable object can be modified.
• Address remains same after modification of Mutable object
a = [10, 20]
print("List is :",a)
print("Address :",id(a))
a.append(30)
print("After append, List is :",a)
print("Address :",id(a))
a.pop()
print("After pop, List is :",a)
print("Address :",id(a))
a = [10,20]
print("List is :", a)
print("Address of a :",id(a))
print("a[0] :", a[0])
print("a[0] address :", id(a[0]))
a[0]=a[0]+5
print("List is :", a)
print("Address of a :",id(a))
print("a[0] :", a[0])
print("a[0] address :", id(a[0]))
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 166
Output:
List is : [10, 20]
Address of a : 54494008
a[0] : 10
a[0] address : 1647965392
List is : [15, 20]
Address of a : 54494008
a[0] : 15
a[0] address : 1647965472
a[2]=a[2]+10
print("id(a[1]) :",a[2])
print("id(a[2]) :",id(a[2]))
Output:
List is : [10, 20, 10]
id(a[0]) : 1647965392
id(a[1]) : 1647965552
id(a[2]) : 1647965392
id(a[1]) : 20
id(a[2]) : 1647965552
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 167
• List is Mutable - We can modify the List
• List elements either Mutable or Immutable
LIST = [10, "abc" , [20,30,40] , 23.45]
tuple:
• It is an ordered collection
• It allows duplicates
• It allows heterogeneous elements
• tuple can be represented using ( )
Output:
(10, 20, 30, 40, 50)
(10, 20, 10, 'abc', 23.45)
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 168
print("Length :", len(t))
print("t[0:len(t):2] :", t[0:len(t):2])
Output:
Tuple : (10, 20, 30, 40, 50)
t[2] : 30
t[-4] : 20
Length : 5
t[0:len(t):2] : (10, 30, 50)
Note: Tuple is Immutable object. Once the object has been created, cannot be modified.
We can modify the List as well as List elements as follows: List object is providing modification
methods such as append(), pop(), remove(), reverse(), sort()…..
a = [10, 20, 30]
print("List is :",a)
a.append(40) #modifying list
print("List is :",a)
a.remove(20)
print("List is :",a)
a[0]=a[0]+5 #modifying list element
print("List is :",a)
Output:
List is : [10, 20, 30]
List is : [10, 20, 30, 40]
List is : [10, 30, 40]
List is : [15, 30, 40]
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 169
• Tuple elements either Mutable or Immutable.
• Hence we can store a List(Mutable) inside the Tuple.
• We can modify the List(Mutable) which inside the Tuple.
Code:
t = (10,20,[30,40])
print("t[2] :", t[2])
t[2].append(50)
print("After append :", t)
t[2].remove(30)
print("After removal :", t)
print("t[2][1] :", t[2][1])
t[2][1]=t[2][1]+5
print("After modify list element :", t)
Output:
t[2] : [30, 40]
After append : (10, 20, [30, 40, 50])
After removal : (10, 20, [40, 50])
t[2][1] : 50
After modify list element: (10, 20, [40, 55])
List Tuple
List is Mutable Tuple is Immutable
List elements either Mutable or Immutable Tuple elements either Mutable or Immutable
List is ordered and allow duplicates Tuple is ordered and allow duplicates
List allow heterogeneous elements Tuple allow heterogeneous elements
List elements can access using Indexing and Tuple elements can access using indexing and
slicing slicing
Modification methods are present – append(), Modification methods not present – only
pop(), remove()…. index() and count() are given
List and List element can modify Tuple and Tuple elements cannot modify
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 170
Set:
• Set is not an ordered collection
• Set element will be processed randomly on access.
• Set can be represented by { }
Set elements are unique. Duplicates will be removed automatically at the time of creation.
s = {10, 20, 10, 20, 30}
print(s)
{10, 20, 30}
s = {10,20,30}
print(s[1])
TypeError: 'set' object does not support indexing
Set functionality:
• 'set' is a class.
• 'set' object providing pre-defined functions to process the elements
s = {10,20,30,40,50}
print("Set :",s)
s.add(60)
print("Set after adding :",s)
s.discard(20)
s.discard(40)
print("Set after deleting :",s)
Output:
Set : {40, 10, 50, 20, 30}
Set after adding : {40, 10, 50, 20, 60, 30}
Set after deleting : {10, 50, 60, 30}
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 171
• Set is Mutable. Hence it is allowed to modify the set after creation.
• add() & discard() function in the above example explains how to modify the set after
creation.
s = {10,20,30}
print("Set :", s)
print("Address :", id(s))
s.add(40)
s.discard(10)
print("Set after modify :",s)
print("Address after modify :", id(s))
Output:
Set : {10, 20, 30}
Address : 54403960
Set after modify : {40, 20, 30}
Address after modify : 54403960
s1 = {1,2,3,4}
s2 = {3,4,5,6}
print("s1 :",s1)
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 172
print("s2 :",s2)
Output:
s1 : {1, 2, 3, 4}
s2 : {3, 4, 5, 6}
Union : {1, 2, 3, 4, 5, 6}
Union : {1, 2, 3, 4, 5, 6}
Intersection : {3, 4}
Intersection : {3, 4}
Difference : {1, 2}
Difference : {1, 2}
Symmetric difference : {1, 2, 5, 6}
Symmetric difference : {1, 2, 5, 6}
Output:
List is : [10, 20, 30, 20, 10]
Set is : {10, 20, 30}
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 173
type():
• A pre-defined function that returns identity of class if we specify an Object.
• We can create collection object in 2 ways.
#List construction:
#1. Initializing with empty list
l1 = [ ]
print(type(l1))
output:
<class 'list'>
output:
<class 'list'>
#Tuple construction:
#1. Initializing with empty list
t1 = ()
print(type(t1))
<class 'tuple'>
Set construction:
• Empty set can be constructed only through constructor.
• Direct assignment of empty set becomes dictionary.
• We represent the elements of Dictionary using { }
s = set()
print(type(s))
s={}
print(type(s))
Output:
<class 'set'>
<class 'dict'>
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 174
When we remove all elements from List or Tuple it will show the empty collection using
symbols
l = [10, 20, 30, 40]
print(l)
l.clear()
print(l)
Output:
[10, 20, 30, 40]
[]
But when we empty a set it will show the collection type using its identity.
s = {10, 20, 30, 40}
print(s)
s.clear()
print(s)
Output:
{40, 10, 20, 30}
set()
• Set is allowed to store only Immutable objects such as Numbers, Strings and Tuples.
• List should not be the element of Set because it is Mutable object.
s = {10,20,(30,40)}
print(s)
s = {10,20,[30,40]}
print(s)
Output:
{10, 20, (30, 40)}
TypeError: unhashable type: 'list'
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 175
Dictionary:
• Set of elements(key, value pairs) represents using { }
• Set stores the elements(only values) directly
o set = {ele1 , ele2 , ele3 ....}
• Dictionary stores the elements using keys.
o dict = {key : ele , key : ele , key : ele }
• Dictionary is an ordered collection.
Keys must be unique. When we store the data using duplicate key, existing data will be
replaced.
accounts ={101:"harin", 102:"kiritin", 102:"ramya"}
print(accounts)
Dictionary object is providing set of functions which are used process elements of that
dictionary.
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 176
print("After removal of last inserted element :", accounts)
print("Value at 103 :", accounts.get(103))
Output:
Accounts : {101: 'harin', 102: 'kiritin', 103: 'ramya', 104: 'annie'}
Keys : dict_keys([101, 102, 103, 104])
Values : dict_values(['harin', 'kiritin', 'ramya', 'annie'])
After removal of 102 : {101: 'harin', 103: 'ramya', 104: 'annie'}
After removal of last inserted element : {101: 'harin', 103: 'ramya'}
Value at 103 : ramya
We can iterate the dictionary using keys. For loop can iterate all keys of input dictionary.
accounts ={101:"harin", 102:"kiritin", 103:"ramya", 104:"annie"}
print("Account numbers are :")
for accno in accounts:
print(accno)
print("Account holder names are :")
for accno in accounts:
name = accounts.get(accno)
print(name)
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 177
File Handling in Python
Files:
• We can store the information of application in 2 ways permanently
o File System
o Database management system
• Database is structured and object oriented; hence we can store and process the data
more effectively.
• File system is the basic data storage option.
• Some of the files(CSV) are used to store the information in more structured format like
database.
• Files are named locations on disk to store information. Files store in Secondary memory
(Hard disk) and Processed from Primary memory (RAM).
Basic modes: It is a string type value represents the operation to be performed on file data.
Read mode(“r”):
• Opens file in read mode.
• If file is present; it opens and return pointer to that file.
• If file is not present, raises Exception : FileNotFoundError.
Writer mode(“w”):
• Opens file in write mode.
• If file is present, it opens and removes existing content.
• If file is not present, it creates the new file with specified name.
Append mode(“a”) :
• Opens file in append mode.
• If file is present, it will place the cursor at the end of existing data to add new contents.
• If file is not present, it creates new file.
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 178
Opening a file in read mode:
• After working with any resource(file, database, server…) from the application must be
released manually(closing statements)
• Improper shutdown of resources results loss of data.
Code:
try:
src = open(file="Input.txt", mode="r")
print("File is present")
except FileNotFoundError:
print("Exception : No such file")
try:
src = open(file="d:/input.txt", mode="r")
print("File is present")
data = src.read()
print(data)
except FileNotFoundError:
print("Exception : No such file")
data = src.read()
n = len(data)
print(n)
except FileNotFoundError:
print("Exception : No such file")
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 179
Read file character by character:
• Read() function return the complete data as object.
• We can process the data object character by character using for loop.
• We can easily iterate the file using pre-defined for loop.
try:
src = open(file="d:/input.txt", mode="r")
print("File is present")
data = src.read()
for ch in data:
print(ch)
except FileNotFoundError:
print("Exception : No such file")
try:
src = open(file="d:/input.txt", mode="r")
print("File is present")
data = src.read()
count=0
for ch in data:
count=count+1
except FileNotFoundError:
print("Exception : No such file")
src = None
try:
src = open(file="d:/inp.txt", mode="r")
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 180
print("File is opened")
except FileNotFoundError:
print("Exception : No such file")
finally:
if(src != None):
src.close()
print("File closed")
src = None
try:
src = open(file="d:/input.txt", mode="r")
print("File is opened")
# data = src.read()
except FileNotFoundError:
print("Exception : No such file")
finally:
if(src != None):
src.close()
print("File closed")
count=0
for line in src:
print(line)
count=count+1
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 181
print("Num of lines : ", count)
except FileNotFoundError:
print("Exception : No such file")
finally:
if(src != None):
src.close()
print("File closed")
Writing to Files:
• File object is providing write() method to write contents into file.
• We use either write mode or append mode to write the information.
• If we open the file in write mode and the file is not present ; It creates the new file with
specified name.
Output:
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 182
for line in src:
dest.write(line)
print("Data copied")
except FileNotFoundError:
print("Exception : No such file")
finally:
if(src != None):
src.close()
print("src File closed")
if(dest != None):
dest.close()
print("dest File closed")
tell() : Method belongs to File object. It returns the current position (value) on the file.
seek(): Method belongs to File object. It is used to sets the cursor position to specific location.
class Source:
file = None
def main():
try:
Source.file = open("./script.py" , "r")
data = Source.file.read()
print(data)
print("Cursor at : ",Source.file.tell())
Source.file.seek(0)
print("Cursor at : ",Source.file.tell())
data = Source.file.read()
print(data)
finally:
if Source.file != None:
Source.file.close()
return
Source.main()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 183
readLine(): A pre-defined method belongs to file object. It will read the current line and returns
as a String object.
class Source:
file = None
def main():
try:
Source.file = open("./script.py" , "r")
line = Source.file.readline()
print("First line is : %s" %line)
Source.file.seek(0,0)
line = Source.file.readline()
print("Line is : %s" %line)
finally:
if Source.file != None:
Source.file.close()
return
Source.main()
csv module
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 184
data.csv file:
import csv
class ReadCSV:
file = None
def main():
try:
ReadCSV.file = open("./data.csv" , "r")
print("File opened")
table = csv.reader(ReadCSV.file)
print("Records are :")
for record in table:
print(record)
except Exception as e:
print("Exception :", e)
finally:
if ReadCSV.file != None:
ReadCSV.file.close()
return
ReadCSV.main()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 185
Using nested for loop, we can split the record into fields also:
table = csv.reader(ReadCSV.file)
print("Records information :")
for record in table:
for field in record:
print(field)
accounts.csv file:
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 186
import csv
class Account:
def __init__(self, accno, name, balance):
self.accno = accno
self.name = name
self.balance = balance
return
class Bank:
accs_dict = dict()
def details():
while True:
num = int(input("Enter account number : "))
try:
record = Bank.accs_dict.get(num)
print("Details are :")
print("Name : ", record.name)
print("Balance :", record.balance)
except Exception as e :
print("Exception :", e)
class CSVtoDict:
file = None
def main():
try:
CSVtoDict.file = open("./accounts.csv" , "r")
print("File opened")
table = csv.reader(CSVtoDict.file)
for record in table:
num = int(record[0])
name = record[1]
balance = int(record[2])
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 187
Bank.details()
except Exception as e:
print("Exception :", e)
finally:
if CSVtoDict.file != None:
CSVtoDict.file.close()
print("File closed")
return
CSVtoDict.main()
Output:
File opened
['1001', 'amar', '5000'] updated to dictionary
['1002', 'annie', '8000'] updated to dictionary
['1003', 'hareen', '7500'] updated to dictionary
['1004', 'satya', '9000'] updated to dictionary
Enter account number : 1002
Details are :
Name : annie
Balance : 8000
Do you want to check another record(y/n) : y
Enter account number : 1004
Details are :
Name : satya
Balance : 9000
Do you want to check another record(y/n) : n
File closed
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 188
pickle module
Pickle:
o “pickle” is the pre-define module providing functionality to perform Serialization and De-
serialization
o “dump()” method is used to write the object information into file.
o “load()” method is used to read the object from the file
Notes:
o Serialized data will be in binary format.
o We need to open file in (write binary) mode to write the object data.
o We cannot open binary file directly(nothing can see). Data will in symbolic format.
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 189
Code: We use 3 files to implement
1. Emp.py file to specify Employee object
2. Serialize.py file
3. Deserialize.py file
emp.py:
class Employee :
def __init__(self, num, name, salary):
self.num = num
self.name = name
self.salary = salary
return
serialize.py:
import pickle
from emp import Employee
class Serialization:
file = None
def main():
try :
Serialization.file = open("./data.bin", mode="wb")
print("File is ready")
except Exception as e:
print("Exception :", e)
finally:
if Serialization.file != None:
Serialization.file.close()
print("File closed")
return
Serialization.main()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 190
Run serialize file:
deserialize.py:
import pickle
from emp import Employee
class DeSerialization:
file = None
def main():
try :
DeSerialization.file = open("./data.bin", mode="rb")
print("File is ready")
obj = pickle.load(DeSerialization.file)
print("Object is De-serialized successfully")
except Exception as e:
print("Exception :", e)
finally:
if DeSerialization.file != None:
DeSerialization.file.close()
print("File closed")
return
DeSerialization.main()
Run deserialize.py:
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 191
Lambda Expressions
Lambda expressions:
• Expression is a line of code.
• Expression is a collection of operands and operators.
• 'lambda' is a keyword.
• 'lambda' expressions are used to define a function with single line
display("Amar")
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 192
Lambda expression foe above code:
even = lambda num : num%2==0
print("4 is even : ", even(4))
print("7 is even : ", even(7))
print(big(10,30,20))
print(big(30,40,50))
Lambda expression:
big = lambda a,b,c : a if a>b and a>c else b if b>c else c
print(big(10,30,20))
print(big(30,40,50))
def leap(n):
if n%400==0:
return "leap"
elif n%4==0 and n%100!=0:
return "leap"
else:
return "not"
print("16 is :",leap(16))
print("31 is :",leap(31))
print("200 is :",leap(200))
print("2400 is :",leap(2400))
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 193
map() and filter() with lambda
Square each element in a list:
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
numbers = [1, 2, 3, 4, 5]
result = list(map(double_and_add_ten, numbers))
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 194
Filter even numbers from a list:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 195
Command Line arguments
Note: Passing input(arguments) from the command line while invoking the application is called
Command line arguments.
Code:
class CmdLine:
def main():
print("Manaul execution of Python script")
return
CmdLine.main()
Run:
• In other languages such as C, C++ and Java; Program execution starts from main()
method.
• Main() is responsible for collecting all these input arguments into a String type array.
• Arguments will be in String format.
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 196
Why command line arguments are String type?
• Only a String can able to store any kind of data (int, float, char, string..)
• We collect the input into String type and process by converting into corresponding type
using conversion methods.
Note: In python programming, main() method is optional. Main() is not responsible to collect
arguments. All command line arguments will store into “argv” list object automatically.
sys.argv:
• ‘sys’ is a pre-defined module
• ‘argv’ is a list belongs to ‘sys’ module.
• ‘argv’ holds command line arguments implicitly.
Memory allocation:
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 197
Python provides various ways to dealing with command line arguments.
The 3 command types are:
1. Using sys.argv
2. Using getopt module
3. Using argparse module
Code:
import sys
class CmdLine:
def main():
count = len(sys.argv)
print("Arguments count :",count)
return
CmdLine.main()
Run:
CmdLine.main()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 198
Run:
CmdLine.main()
Run:
x = int(s1)
y = int(s2)
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 199
z = x/y
print("Result :",z)
except IndexError :
print("Exception : Insufficient values")
except ValueError :
print("Exception : Invalid Input")
except ZeroDivisionError :
print("Exception : Division by zero")
return
Divide.main()
return
Divide.main()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 200
pip
pip:
• PIP is a package manager.
• It is also called Python Package Installer (PyPI)
• A pre-defined script that can install every third party module or package of Python into
system easily.
• We need to install pip first.
• Download get-pip.py file and run as script.
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 201
Run from command line as a Script – Maintain data connection:
• get-pip.py program collect the required information from the internet in the process of
installation.
• At the time of installation, in case any old version exists will be un installed automatically.
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 202
Database Connectivity
Introduction:
• We use programming languages to develop applications
• Applications are used to store(maintain) information for processing.
• We can store information in 2 ways
o File System
o Database management systems
• Traditional file system is not secured and structured.
• DBMS is an application – It is object oriented, structured and secured.
To develop complete application, we use follow the architecture called 3-tier architecture:
DBMS:
• DBMS(for example, mysql) is an application software.
• Database Repository is a collection of Databases.
• Database is a collection of Tables & Table is a collection of records
• Record is a collection of fields.
• We need to maintain separate database to each application.
Python-MySQL connectivity:
• MySQL is simple and open source.
• Download and install the MySQL server
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 203
Python-MySQL-Connector:
• After installation of MySQL, we need to install connector from the same website.
• Connector installs a package which contains pre-defined programs to implement
Python-Database connection applications.
• MySQL connection programs are not directly available with Python installation.
• Connector installation provides mysql.connector package which contains pre-defined
programs for connection, to execute sql statements in communication.
Opening Client:
Executing SQL commands: Mainly we use 3 types of SQL statements to communicate with
database
1. DDL commands : Data Definition languages
a. Create or Drop tables
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 204
Query to show all databases:
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| banking |
| python |
+--------------------+
Inserting records:
mysql> insert into account values(101, 'amar', 5000);
mysql> insert into account values(102, 'annie', 9000);
mysql> insert into account values(103, 'hareen', 7000);
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 205
mysql> select name from account;
+--------+
| name |
+--------+
| amar |
| annie |
| hareen |
+--------+
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 206
mysql> delete from account;
mysql> select * from account;
Empty set (0.00 sec)
mysql.connector:
• connector is a sub module in mysql package.
• It is available only when we install python-mysql-connector.
• After installation, we are checking whether the module has installed or not by importing.
connect():
• It is belongs to connector module.
• It returns connection object if the specified input is valid.
• Input arguments are username, password, host address and database name.
Connecting to Database:
import mysql.connector
class DB:
con = None
def main():
try :
DB.con = mysql.connector.connect(user='root', password='root',
host='127.0.0.1', database='student')
print("Connected to database")
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 207
except Exception as msg:
print("Exception :",msg)
finally:
if DB.con != None:
DB.con.close()
print("Database released")
return
DB.main()
Output:
DDL commands:
Create:
• Once connection is ready, we need to get cursor object.
• Cursor() method belongs to connection object.
• On call, it returns cursor object.
execute():
• Pre-defined method belongs to cursor object.
• Using execute() method, we can execute any query in the database.
Code:
import mysql.connector
class DB:
con = None
def main():
try :
DB.con = mysql.connector.connect(user='root', password='root',
host='127.0.0.1', database='student')
print("Connected to database")
cur = DB.con.cursor()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 208
print("Exception :",msg)
finally:
if DB.con != None:
DB.con.close()
print("Database released")
return
DB.main()
Output:
In database:
Inserting records:
• ‘insert’ is DML command.
• DML commands such as insert, delete and update transactions need to commit after
execution.
• commit() method belongs to connection object.
• Without commit the DML transaction, the database will not be effected.
Code:
import mysql.connector
class DB:
con = None
def main():
try :
DB.con = mysql.connector.connect(user='root', password='root',
host='127.0.0.1', database='student')
print("Connected to database")
cur = DB.con.cursor()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 209
cur.execute(query)
print("Record inserted....")
DB.con.commit()
print("Transaction committed")
finally:
if DB.con != None:
DB.con.close()
print("Database released")
return
DB.main()
Output:
In database:
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 210
Fetching first record:
import mysql.connector
class DB:
con = None
def main():
try :
DB.con = mysql.connector.connect(user='root', password='root',
host='127.0.0.1', database='student')
print("Connected to database")
cur = DB.con.cursor()
query = "select * from account"
cur.execute(query)
record = cur.fetchone()
print("First record details : ", record)
finally:
if DB.con != None:
DB.con.close()
print("Database released")
return
DB.main()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 211
Output:
Connected to database
First record details : (101, 'amar', 7000)
Database released
record = cur.fetchone()
print("102 record details : ")
print("Account Number :", record[0])
print("Name :", record[1])
print("Balance :", record[2])
finally:
if DB.con != None:
DB.con.close()
print("Database released")
return
DB.main()
Output:
Connected to database
102 record details :
Account Number : 102
Name : annie
Balance : 6000
Database released
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 212
Fetching the complete table information:
• Table is in two dimensional format.
• A set of records will be returned as an object.
• Using for loop, we can access records
• Using nested for loop; we can process fields of each record.
import mysql.connector
class DB:
con = None
def main():
try :
DB.con = mysql.connector.connect(user='root', password='root',
host='127.0.0.1', database='student')
print("Connected to database")
cur = DB.con.cursor()
table = cur.fetchall()
print("Table details :")
for record in table:
print(record)
finally:
if DB.con != None:
DB.con.close()
print("Database released")
return
DB.main()
Output:
Connected to database
Table details :
(101, 'amar', 7000)
(102, 'annie', 6000)
(103, 'hareen', 9000)
Database released
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 213
Using nested loop, we can process each record elements as follows:
query = "select * from account"
cur.execute(query)
table = cur.fetchall()
print("Table details :")
for record in table:
for field in record:
print(field)
import mysql.connector
class DB:
con = None
def main():
try :
DB.con = mysql.connector.connect(user='root', password='root',
host='127.0.0.1', database='student')
print("Connected to database")
cur = DB.con.cursor()
finally:
if DB.con != None:
DB.con.close()
print("Database released")
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 214
return
DB.main()
Output:
Connected to database
Record updated
Database released
Static Queries:
1. ins_query = "insert into account values(101, 'amar', 5000)"
2. sel_query = "select * from account where no=102"
3. upd_query = "update account set balance=balance+3000 where no=103"
4. del_query = "delete from account where no=104"
Dynamic Queries:
Construct delete query by collecting record number as input:
num = int(input("Enter record num to delete : "))
del_query = "delete from account where no=" + str(num)
print(del_query)
# or
del_query = "delete from account where no=%d" %num
print(del_query)
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 215
Fetching specific record by reading the record number from end user:
import mysql.connector
class DB:
con = None
def main():
try :
DB.con = mysql.connector.connect(user='root', password='root',
host='127.0.0.1', database='student')
print("Connected to database")
cur = DB.con.cursor()
record = cur.fetchone()
print("Details are : ", record)
finally:
if DB.con != None:
DB.con.close()
print("Database released")
return
DB.main()
Output:
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 216
Update(change balance of) specific record by collecting record number and balance to set
from the end user:
import mysql.connector
class DB:
con = None
def main():
try :
DB.con = mysql.connector.connect(user='root', password='root',
host='127.0.0.1', database='student')
print("Connected to database")
cur = DB.con.cursor()
DB.con.commit()
print("Record updated")
finally:
if DB.con != None:
DB.con.close()
print("Database released")
return
DB.main()
Output:
Connected to database
Enter account number : 101
Enter deposit amount : 1200
Record updated
Database released
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 217
Insert(all details) record into table by collecting no, name and balance.
import mysql.connector
class DB:
con = None
def main():
try :
DB.con = mysql.connector.connect(user='root', password='root',
host='127.0.0.1', database='student')
print("Connected to database")
cur = DB.con.cursor()
cur.execute(query)
print("Record inserted....")
DB.con.commit()
print("Transaction committed")
finally:
if DB.con != None:
DB.con.close()
print("Database released")
return
DB.main()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 218
tkinter – GUI
tkinter:
• “tkinter” is a pre-defined module.
• “tkinter” providing set of classes to implement GUI programming.
• GUI programming is “Windows” based.
• “Tk” class belongs to “tkinter” module. Instantiation(Object Creation) of Tk class results a
Window(Frame)
Creating Frame:
from tkinter import Tk
root = Tk()
class Create:
def main():
obj = MyFrame()
return
Create.main()
Components:
• Components such as Buttons, Labels, Entry fields, Checkboxes provided as pre-defined
classes.
• Component classes belong to “tkinter” module only.
• Object creation of Component class results the Component.
• We need to arrange the component on the Frame using Layout structure.
Layout:
• The arrangement of components on window.
• Python library is pre-defined layout structures.
• Every Component class has dynamic functionality to layout that component.
Create Button:
from tkinter import Tk, Button
root = Tk()
root.title("GUI")
b = Button(root, text="Click Me")
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 219
Note: In the above application, Button is not displayed on Frame. After creation of Button, we
need to arrange that Button on Frame using Layout functionality.
geometry():
• A function is belongs to Tk class
• It is used to set Width & Height of Frame
• It is dynamic function; hence we need to call on object.
o geometry(“width x height”)
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 220
Events:
• Event is an Action which is performed on component
• For example,
o clicking a button.
o Select checkbox
o Select radiobutton
• When action performed on Button, it executes the function which is specified by
“command” argument of that Button.
def display():
print("Button clicked")
return
root = Tk()
root.title("GUI")
root.geometry("500x300")
def display():
print("Button clicked")
return
root = Tk()
root.title("GUI")
root.geometry("500x300")
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 221
Code:
from tkinter import Tk, Label, Entry, Button
def disp():
name = e.get()
print("Hello %s, welcome" %name)
return
root = Tk()
root.title("GUI")
root.geometry("500x300")
def fun():
print("Button clicked")
return
root = Tk()
root.title("GUI")
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 222
root.geometry("500x300")
b = Button(root, text="click", font="Times 20", command=fun)
b.place(x=200, y=100)
grid():
• Layout method belongs to component object.
• grid() method arrange the components in table(rows and columns) format.
• We need to specify row value and column value of component
Code:
from tkinter import *
def details():
name = e1.get()
loc = e2.get()
print("%s live in %s" %(name,loc))
return
root = Tk()
root.title("GUI")
l1.grid(row=0, column=0)
e1.grid(row=0, column=1)
l2.grid(row=1, column=0)
e2.grid(row=1, column=1)
b1.grid(row=2, column=0)
b2.grid(row=2, column=1)
Output:
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 223
Code:
from tkinter import Tk, Label, Button, Entry
def func():
name = e.get()
print("Hello " + name + ", welcome to GUI")
return
window = Tk()
window.title("Grid Layout")
StringVar class:
• It is belongs to tkinter module
• It is used to set dynamic text(values) to components
• To assign StringVar object we use “textvariable” argument of that component instead of
“text” argument.
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 224
from tkinter import Tk, Label, Button, Entry, StringVar
def func():
name = e.get()
msg.set("Hello " + name + ", Welcome")
return
window = Tk()
msg = StringVar()
window.title("Dynamic Text")
window.geometry("750x300")
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 225
Code:
from tkinter import *
def add():
s1 = e1.get()
s2 = e2.get()
if len(s1)==0 or len(s2)==0 :
err.set("Error : Empty input")
else:
try :
x = int(s1)
y = int(s2)
z = x+y
err.set("")
res.set(str(z))
except ValueError :
err.set("Error : Invalid Input")
return
window = Tk()
window.title("Calculator")
err = StringVar()
res = StringVar()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 226
e3.grid(row=0, column=5)
Output:
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 227
Python - Regular expressions
Regular Expression:
• Regular expression is a set of characters or set of operators and special symbols.
• Regular expressions are used to process Strings.
• Regular expressions are used to filter required information.
match( ) :
• It is used to test whether the input string starts with given "pattern" or not.
• On success, it returns match object.
• On failure, it returns None
import re
line = "Java and Python gives Jython"
res = re.match(r'Java' , line)
print("Success : ",res)
res = re.match(r'Python' , line)
print("Failure : ",res)
search() :
• It is used to find specified pattern in the input string.
• On success, it returns match object.
• On failure, it returns None
import re
line = "Java and Python gives Jython"
res = re.search(r'hon' , line)
print("Success : ",res)
start() and end() : search object providing pre-defined functionality to get start index and end
index of specified pattern.
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 228
import re
line = "Java and Python gives Jython"
found = re.search(r'Python' , line)
if found :
print("Pattern found")
print("Pattern starts @ :",found.start())
print("Pattern ends @ :",found.end())
else :
print("Pattern not found")
findall():
• It returns a list of duplicates patterns available in the given input string.
• It returns a list.
• On failure, it returns empty list.
import re
line = "Java and Python gives Jython"
l = re.findall(r'on' , line)
print("List :" , l)
print("Count :", len(l))
split() :
• It is used to split the string into tokens(words).
• It returns a list of tokens.
• We can process the list using its functionality.
import re
line = "Java and Python gives Jython"
tokens = re.split(r' ' , line)
print("Tokens :" , tokens)
print("Count :" , len(tokens))
print("Index of Python :" , tokens.index('Python'))
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 229
Note : We can use any "delimeter" to split the input string.
import re
line = "RAMAYANA"
a1 = re.split(r'A' , line)
print("List : " , a1)
a2 = re.split(r'A' , line , 2)
print("List : " , a2)
compile() :
• We can construct a pattern object with a specified pattern.
• Pattern object can be used to perform all the other operations easily.
• Instead of specifying the same pattern everywhere, we just call 're' functionality on
pattern object.
import re
line = "Java and Python gives JavaPython"
found = re.match(r'Python' , line)
if found:
print("String starts with specified pattern")
else:
print("String not starts with Python")
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 230
found = pattern.search(line)
if found:
print("Pattern found @ index : " , found.start())
else:
print("Search failed")
duplicates = pattern.findall(line)
if duplicates :
print("Duplicates present for Python")
Note : It is possible to construct a regular expression with operators and special symbols also.
Date extraction :
import re
data = "ab12-04-1987 23-ab09-2003 31-03-2005ab"
res = re.findall(r'\d{2}-\d{2}-\d{4}' , data)
print(res)
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 231
Datetime and Calendar Modules
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 232
Convert a time object to a string:
import datetime
time = datetime.datetime.now().time()
time_str = time.strftime("%H:%M:%S")
print("Time as string:")
print(time_str)
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 233
OS Module
Rename a file:
import os
old_file_path = "/path/to/old/file"
new_file_path = "/path/to/new/file"
os.rename(old_file_path, new_file_path)
print(f"Renamed file from {old_file_path} to {new_file_path}")
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 234
Python Numpy Tutorial
Introduction to Numpy:
• Python is a great general-purpose programming language.
• With the help of a few popular libraries (numpy, scipy, matplotlib) it becomes a powerful
environment for scientific computing.
• NumPy is a module for Python.
• The name is an acronym for "Numeric Python" or "Numerical Python".
• It is an extension module for Python, mostly written in C.
• This makes sure that the precompiled mathematical and numerical functions and
functionalities of Numpy guarantee great execution speed.
• NumPy enriches the programming language Python with powerful data structures,
implementing multi-dimensional arrays and matrices.
• The implementation is even aiming at huge matrices and arrays, better know under the
heading of "big data".
my_list = [0,1,2,3,4]
my_arr = np.array(my_list)
print(type(my_arr))
print(my_arr)
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 235
Display elements using for-loop :
import numpy as np
my_list = [0,1,2,3,4]
my_arr = np.array(my_list)
print("Elements : ")
for ele in my_arr :
print(ele)
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 236
Reshape a NumPy Array:
arr = np.array([1, 2, 3, 4, 5, 6])
reshaped = arr.reshape(2, 3)
print(reshaped)
Transpose a Matrix:
import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6]])
transposed = np.transpose(matrix)
print(transposed)
Code:
importnumpy as np
arr = np.ndarray(shape=(5))
print("Size :",arr.size)
print("Datatype :",arr.dtype)
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 237
You may also specify the data type by setting the dtype argument. Some of the most
commonly used numpy dtypes are: 'float', 'int', 'bool', 'str' and 'object'.
import numpy as np
my_list = [[1,2,3],[4,5,6],[7,8,9]]
my_array = np.array(my_list, dtype=float)
print(my_array)
The decimal point after each number is indicative of the float datatype. You can also
convert it to a different datatype using the astype method.
import numpy as np
my_list = [[1,2,3],[4,5,6],[7,8,9]]
float_array = np.array(my_list, dtype=float)
print(float_array)
int_array = float_array.astype(int)
print(int_array)
We can check the size, dimension and type of elements using pre-defined variables of
array object.
import numpy as np
my_list = [[1,2,3],[4,5,6],[7,8,9]]
my_array = np.array(my_list)
print(my_array)
print('Shape : ', my_array.shape)
print('Datatype : ', my_array.dtype)
print('Size : ', my_array.size)
print('Num Dimensions : ', my_array.ndim)
my_array = np.array(my_list)
print(my_array)
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 238
res = my_array[:2,:2]
print(res)
my_list = [[1,2,3],[4,5,6],[7,8,9]]
my_array = np.array(my_list)
print("Elements : ")
for i in range(3):
for j in range(3):
print(my_array[i,j], end=' ')
print()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 239
Python - Pandas
Introduction
• Pandas is a package/Module.
• Pandas is an open source
• Pandas is a collection (data structure).
• Pandas widely used in data analysis tools.
• Panda’s library uses most of the functionalities of Numpy library.
Creating Series object: By default the datatype of series object is float like numpy array.
import pandas
s = pandas.Series()
print(s)
import pandas as pd
import numpy as np
arr = np.array(['a', 'b', 'c', 'd', 'e'])
s = pd.Series(arr)
print(s)
Output:
0 a
1 b
2 c
3 d
4 e
dtype: object
dtypes:
• If we store integers, the dtype become int
• If we store integers and floats, the dtype become float
• If we store integers, floats, Strings…, the dtype become ‘Object’
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 240
import pandas as pd
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
s = pd.Series(arr)
print(s)
Output:
0 10
1 20
2 30
3 40
4 50
dtype: int32
import pandas as pd
import numpy as np
arr = np.array([10, 23.45, 30, "python"])
s = pd.Series(arr)
print(s)
Output:
0 10
1 23.45
2 30
3 python
dtype: object
import pandas as pd
import numpy as np
arr = np.array(['a', 'b', 'c', 'd', 'e'])
s = pd.Series(arr, index=[1,2,3,4,5])
print(s)
Output:
1 a
2 b
3 c
4 d
5 e
dtype: object
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 241
Keys can be heterogeneous. When we specify the key set explicitly, we can provide
different types of keys for different elements.
import pandas as pd
import numpy as np
arr = np.array(['a', 'b', 'c', 'd', 'e'])
s = pd.Series(arr, index=[10,23.45,'g',"key",20])
print(s)
Output:
10 a
23.45 b
g c
key d
20 e
dtype: object
Keys can be duplicated. We can see the accessibility of elements using duplicate keys
later.
import pandas as pd
import numpy as np
arr = np.array(['a', 'b', 'c', 'd', 'e'])
s = pd.Series(arr, index=[10, 20, 10, 20, 10])
print(s)
Output:
10 a
20 b
10 c
20 d
10 e
dtype: object
import pandas as pd
dictionary = {10:'A', 20:'B', 30:'C', 40:'D'}
s = pd.Series(dictionary)
print(s)
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 242
Output:
10 A
20 B
30 C
40 D
dtype: object
Output:
1 5
2 5
3 5
4 5
5 5
dtype: int64
import pandas as pd
import numpy as np
List = [10,20,30,40,50]
arr = np.array(List)
series = pd.Series(arr)
Output:
Series object elements :
10
20
30
40
50
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 243
Access elements using indexing:
import pandas as pd
import numpy as np
arr = np.array([10,20,30,40,50])
series = pd.Series(arr)
Output:
Series elements through indexing :
30
50
import pandas as pd
import numpy as np
arr = np.array([10,20,30,40,50])
series = pd.Series(arr)
print(series[1:4])
print()
import pandas as pd
import numpy as np
arr = np.array([10,20,30,40,50])
series = pd.Series(arr, index=['a', 'b', 'c', 'd', 'e'])
print(series['a'])
print(series['d'])
Output: 10 40
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 244
When we access elements with duplicate keys, it display all elements associated with
duplicate keys.
import pandas as pd
import numpy as np
arr = np.array(['a', 'b', 'c', 'd', 'e'])
series = pd.Series(arr, index=[10,20,10,20,10])
print(series[10])
print(series[20])
Output:
10 a
10 c
10 e
dtype: object
20 b
20 d
dtype: object
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 245
By default, indexing is applicable for both rows and columns:
• We create simple frame from 2 dimensional data.
• We use nested list to create the frame.
import pandas as pd
data = [[10,"abc"],[20,"xyz"],[30,"lmn"]]
frame = pd.DataFrame(data)
print(frame)
Output:
0 1
0 10 abc
1 20 xyz
2 30 lmn
When we specify one dimensional list to create the frame, each element consider as one
row.
import pandas as pd
data = [10,20,30,40,50]
frame = pd.DataFrame(data)
print(frame)
Output:
0
0 10
1 20
2 30
3 40
4 50
import pandas as pd
data = [[21,'amar'],[19,'annie'],[22,'hareen']]
frame = pd.DataFrame(data, columns=['Age', 'Name'])
print(frame)
Output:
Age Name
0 21 amar
1 19 annie
2 22 hareen
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 246
We can specify the datatype in the construction of Frame object.
import pandas as pd
data = [[21,'amar'],[19,'annie'],[22,'hareen']]
frame = pd.DataFrame(data, columns=['Age', 'Name'], dtype=float)
print(frame)
Output:
Age Name
0 21.0 amar
1 19.0 annie
2 22.0 hareen
import pandas as pd
data = {'Name':['Syam', 'Ricky', 'Raksha', 'Kiritin'], 'Age':[21, 19, 23, 21]}
frame = pd.DataFrame(data)
print(frame)
Output:
Age Name
0 21 Syam
1 19 Ricky
2 23 Raksha
3 21 Kiritin
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 247
Python - MatPlotLib
Matplotlib:
• Open source module(package)
• Need to install using PIP.
• Matplotlib providing functionality for data visualization
Visualization:
• Graphics provides an excellent approach for representing the data.
• The final results of anything are recommended to represent as a graph.
• With little knowledge of python pre-defined module called matplotlib, we can easily plot
graphs.
Pyplot:
• A module belongs to matplotlib package.
• Need to import from matplotlib
• Using plot() method of pyplot module, we can plot graphs
Plot():
• A method belongs to pyplot
• Plot() takes x-axis and y-axis values to plot.
• Show() method must be called to display the graph
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 248
• It is possible to set title to the Graph.
• We also give labels to x-axis and y-axis
Notes:
• If we give only one set of values to generate the graph, it plots the x-axis range
automatically.
• What we provided will assume as sequence of y-axis values.
• X axis range starts with 0
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 249
from matplotlib import pyplot as plt
data = [10, 20, 50, 70, 90]
plt.plot(data)
plt.ylabel("y-axis")
plt.xlabel("x-axis")
plt.show()
B : Blue marker
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 250
‘ro’ : Red circle
‘-g’ : Green solid line
‘_’ : dashed with default color
Colors:
G – green
R – red
C – cyan
M – magenta
Y – yellow
K – black
W – white
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 251
Garbage Collection
Garbage Collection:
• Python is fully Object Oriented Programming Language.
• In OOP application, data stores in the form of Objects.
• We access the objects information using references.
• Garbage collection is the mechanism of deleting unreferenced objects.
• An object is said to be eligible for Garbage Collection when no pointer is pointing to that
object.
• In python garbage collection mechanism is much faster compare to other languages.
class GCDemo:
def main():
x = Test()
y = Test()
z = Test()
return
GCDemo.main()
As soon the object is unused, GC will destroy that object. The same memory is allocated to
newly created object.
class Test:
def __init__(self):
print("Constructed :",id(self))
return
class GCDemo:
def main():
Test()
Test()
Test()
return
GCDemo.main()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 252
• Defining a variable inside the function is called Local variable.
• Local variable memory is not permanent
• Local variable will be deleted as soon as function execution completed.
• If the local variable is pointing to any object, then the object become unreferenced once
local variable memory will be released.
• The object pointing by local variables will be deleted as soon as function execution
completes.
class Test:
def fun():
x = []
x.append(10)
print("Address of x :", id(x))
return
class GCDemo:
def main():
Test.fun()
Test.fun()
Test.fun()
return
GCDemo.main()
class GCDemo:
def main():
Test.fun()
Test.fun()
Test.fun()
return
GCDemo.main()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 253
Manual Garbage collection:
• In the above application, self referenced objects will not be garbage collected as soon as
they are unreferenced.
• To destroy such type of object manual garbage collection is required.
• We can reuse the memory quickly by deleting the unused objects.
• 'gc' is a pre-defined module providing functionality to implement manual garbage
collection.
• collect() method of gc module is used to destroy objects
import time
class Test:
def fun():
x = []
x.append(x)
print("Address of x :", id(x))
return
class GCDemo:
def main():
for i in range(20):
Test.fun()
time.sleep(1)
return
GCDemo.main()
GCDemo.main()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 254
Nested Functions, Decorators and Closures
Nested Function:
o A nested function is a function defined inside another function.
o The nested function has access to the variables in the outer function's scope.
outer_function()
closure = outer_function(10)
result = closure(5)
print(result)
square = exponentiate(2)
cube = exponentiate(3)
print(square(3))
print(cube(2))
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 255
Closure:
• A closure is a function object that remembers values in the enclosing scope even if they
are not present in memory.
• It is a record that stores a function together with an environment
• A closure is created by returning a function object that accesses a variable in its
enclosing scope.
def outer(msg):
def inner():
print(msg)
return
return inner
print_msg = outer("Hello")
print_msg()
Decorator:
• A decorator is a special kind of function that takes another function and extends or
modifies its behavior without changing its source code.
• A decorator is defined using the @decorator_name syntax and is applied to a function by
placing it above the function definition.
• Decorators can be used to add logging, timing, validation, and other functionality to a
function without modifying the function's code directly.
def my_decorator(func):
def wrapper():
print("Before the function is called.")
func()
print("After the function is called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
Contact for Online Classes: +91 – 911 955 6789 / 7306021113 Page - 256