Data Science - Python Programme Tutorial
Data Science - Python Programme Tutorial
PYTHON (Simplified)
SRINIVAS GARAPATI
Manyavar Building 3rd Floor, MIG 221 Road No.2, KPHB Phase-1 Colony, Kukatpally Hyderabad Telangana 500085
[Link] Contact – 98859 46789
Contents
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 [Link]
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.
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.
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.
>>> 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
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
Arithmetic operators:
Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication etc.
Operators are +, - , * , / , % , // , **
Practice worksheet
a=10; a a=5; a
a=20; a=a+1;
a=30; a=a+1;
a=40; a=a+1;
a=50; a=a+1;
print(a); print(a);
a=5; a a=15; a
a=a+1; a=a+5;
a=a+2; a=a+4;
a=a+3; a=a+3;
a=a+4; a=a+4;
print(a); print(a);
a=5, x=1; a a=5, b=5; a
a=a+x; a=a+b;
x = x+1; b = b-1;
a=a+x; a=a+b;
x = x+1; x b= b-1; b
a=a+x; a=a+b;
x = x+1; b = b-1;
a=a+x; a=a+b;
print(a, x); print(a,b);
n=2; n s n=2; n c
s=n*n; c=n*n*n;
print(s); print(c);
n=234; n d n=234; n d
d=n%10; d=n//10;
print(d); print(d);
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)
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}")
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)
>>> 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
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
>>> chr(65)
'A'
>>> chr(50)
'2'
>>> ord('a')
97
>>> ord('$')
36
>>> ord('1')
49
Adding 2 numbers:
swapping:")
print("num1 =", num1)
print("num2 =", num2)
Condition to check the sum of last digits of given two numbers is equals to 10
Condition to check the sum of First 2 numbers equals to last digit of 3 rd num
12. Condition to check any 2 numbers equal or not among the 3 numbers
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")
# Calculatethediscount(15%ofthebill)
discount = 0.15 * bill
# Applythediscounttothebill
bill -=discount
# Printthefinalbillamount
print("Pay :", bill)
#Calculatethediscount(15%ofthe bill)
discount = 0.15 * bill
# Apply the discount to the bill
bill -= discount
avg=(m1+m2+m3)/3
if avg >= 60:
print("Grade-A")
elif avg >= 50:
print("Grade-B")
else:
print("Grade-C")
else:
print("Student failed")
#Checkifthemonthnumberiswithinavalidrange (1 to 12)
if 1 <= n <= 12:
if n == 2:
print("28 days / 29 days")
elif n in (4, 6, 9, 11):
print("30 days")
else:
print("31 days")
else:
print("Invalid month number")
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
Note: Block executes only once whereas Loop executes until condition become False
Python Supports 3 types of Loops:
1. For Loop
2. While Loop
3. While - else Loop
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
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.
FindSumofEvenNumbers:
n=int(input("Enterapositive integer: "))
sum_even = 0
for i in range(1, n + 1):
ifi%2==0:
sum_even += i
print("Sumofevennumbers from 1 to", n, "is:", sum_even)
print("Sumoffactorsof",n,"is:", sum_factors)
ifn%i==0:
is_prime = False
break
if is_prime:
print(n,"isaprimenumber")
else:
print(n,"isnotaprimenumber")
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 firsttwo)isthesum of the two preceding ones.
The Fibonaccisequencestarts with 0 and 1 as its first two terms:
0, 1, 1, 2,3,5,8,13,21,34, ...
Fibonaccisequenceisdefined by the recurrence relation:
F(n) = F(n-1) + F(n-2)
while(condition):
statements;
print("Exiting program.")
print("Exiting program.")
print("Exiting program.")
print("SumofEvendigitsare:", sum)
r=n%10
for i in range(1, 11):
print(f"{r} * {i} = {r * i}")
n=n//10
print(f"Factorialof{r}is:{fact}")
n=n//10
r=n%10
count= 0
foriinrange(1,r+1):
ifr%i==0:
count+= 1
if count==2:
print(f"{r}isprime")
n=n//10
whilen>0:
r=n%10
if r < small:
small = r
n=n//10
print("Smallestdigit:",small)
if r > large:
large = r
n=n//10
print("Largestdigit:",large)
r = n % 10
if r > large:
large = r
if r < small:
small = r
n = n // 10
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
print("Sum of First & Last Digits:", sum)
print("ReverseNumberis:",rev)
Palindrome Number: The number become same when we reverse is called Palindrome number
Examples: 121, 1001, 123321
n =int(input("EnterNum:"))
rev = 0
temp = n
whilen>0:
r=n%10
rev=rev*10+r
n=n//10
if temp == rev:
print("PalindromeNumber")
else:
print("NotPalindromeNumber")
n =int(input("EnterNum:"))
temp = n
sum=0
num_digits = len(str(n))
whilen>0:
r=n%10
sum += r ** num_digits
n//= 10
if temp == sum:
print("ArmstrongNumber")
else:
print("NotanArmstrongNumber")
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")
sum = 0
while num != 0:
dig = num % 10
sum += dig
num //= 10
print(sum, end="->")
num = sum
import math
ifrev2 == num:
print(num, " is an Adam number")
else:
print(num, " is not an Adam number")
break:Abranching statement that terminates the execution flow of a Loop or Switch case.
foriinrange(1, 11):
if i == 5:
break
print(i,end=" ")
Output: 1234
while True:
n=int(input("Enter table number: "))
foriinrange(1, 11):
print(f"{n} * {i} = {n * i}")
print("Exiting program.")
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}")
Finding PrimeNumbers
num = 10
is_prime = True
whilenum>1:
foriinrange(2, num):
ifnum%i== 0:
is_prime= False
break
else:
print(f"{num} is a prime number")
num-= 1
Factorials from 2 to 8:
for n in range(2, 9):
factorial=1
foriinrange(1,n+ 1):
factorial *= i
print(f"Factorialof{n}is{factorial}")
if factors == 2:
print(n, "is prime")
if n == sum:
print(n, "is perfect")
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
print()
22222
11111
Pattern Logic
11111 for i in range(1, 6):
00000 for j in range(1, 6):
11111 print(i % 2, end="")
00000
print()
11111
Pattern Logic
Pattern Logic
EEEEE forxinrange(ord('E'), ord('A') - 1, -1):
DDDDD foryinrange(ord('E'), ord('A') - 1, -1):
CCCCC print(chr(x), end="")
BBBBB
print()
AAAAA
Pattern Logic
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
print(k % 10, end="")
78912
34567 k += 1
print()
Pattern Logic
for i in range(1, 6):
for j in range(1, 6):
11111 if i % 2 == 0:
12345
print(j, end="")
33333
12345 else:
55555 print(i, end="")
print()
Pattern Logic
55555 for i in range(1, 6):
54321 for j in range(1, 6):
33333 if i % 2 == 0:
54321
11111 print(j, end="")
else:
print(i, end="")
print()
Pattern Logic
foriinrange(1, 8):
+++++++ forjinrange(1, 8):
+++ +++ ifiin(1, 4, 7) or j in (1, 4, 7):
+++++++
print("+", end="")
+++ +++
+++++++ else:
print(" ", end="")
print()
Pattern Logic
foriinrange(1, 8):
+ forjinrange(1, 8):
+ ifi==j:
+
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()
Pattern Logic
for i in range(1, 8):
+ forjinrange(1,6):
++ ifj==4-iorj==3ori== 7:
+ +
print("+", end="")
+
+ else:
+ print(" ", end="")
+++++++ print()
Pattern Logic
for i in range(1, 8):
+ + + + + forjinrange(1,6):
+ ifi==1ori==4ori==7or (j == 5 and i <= 4) or (j ==
+ 1 andi>=4):
+ + + + + print("+", end="")
+
+ else:
+ + + + + print(" ", end="")
print()
+ + + + + foriinrange(1, 8):
+ forjinrange(1, 6):
+
ifi== 1 or i == 4 or i == 7 or j == 5:
+ + + + +
+ print("+", end="")
+ else:
+ + + + + print(" ", end="")
print()
Pattern Logic
+
+ + foriinrange(1, 8):
+ + forjinrange(1, 8):
+ +
ifj==5 or i == 5 or j == 6 - i:
+ + + + + + + +
+ print("+", end="")
+ else:
print(" ", end="")
print()
Pattern Logic
foriinrange(1, 8):
+ + + + + forjinrange(1, 6):
+ ifi==1 or i == 4 or i == 7 or (j == 1 and i <= 4) or (j
+
==5andi>= 4):
+ + + + +
+ print("*", end="")
+ else:
+ + + + + print(" ", end="")
print()
Pattern Logic
foriinrange(1, 8):
+ + + + + forjinrange(1, 6):
+ + + + + ifi==1 or j == 1 or i == 4 or i == 7 or (j == 5 and i
+ +
>= 4):
+ + print("*", end="")
+ + else:
+ + + + + print(" ", end="")
print()
foriinrange(1, 8):
+ + + + + + forjinrange(1, 6):
+
ifi== 1 or j == 7 - i:
+
+ print("*", end="")
+ else:
+ print(" ", end="")
print()
Pattern Logic
+ + + +
+ + + foriinrange(1, 8):
+ + forjinrange(1, 6):
+ + + +
ifi== 1 or i == 4 or i == 7 or j == 1 or j == 5:
+ + +
+ + print("*", end="")
+ + + + else:
+ print(" ", end="")
print()
Pattern Logic
+ + + + + foriinrange(1, 8):
+ + forjinrange(1, 6):
+ + ifi== 1 or i == 4 or i == 7 or (j == 1 and i <= 4)
+ + + + +
orj== 5:
+
+ print("*", end="")
+ + + + + else:
print(" ", end="")
print()
Pattern Logic
+ + + + for i in range(1, 8):
+ + + + forjinrange(1,8):
+ if(i==1andj>1)or(j==1andi> 1 and i < 7) or (i ==
7 and j > 1):
print("+", end="")
+ + + + else:
print(" ", end="")
print()
Pattern Logic
Pattern Logic
Pattern Logic
foriinrange(1, 8):
+ + + + + forjinrange(1, 8):
+ + + + + ifi== 1 or j == 4 or i == j + 3:
print("+", end="")
+
else:
+ print(" ", end="")
print()
Pattern Logic
foriinrange(1, 8):
forjinrange(1, 8):
+ + + + + ifj== 1 or i == 7:
+++++
print("+", end="")
else:
print(" ", end="")
print()
Pattern Logic
foriinrange(1, 8):
forjinrange(1, 8):
+ + ifj==1 or j == 7 or (i == j and j <= 4) or (j == 8 - i
+ + + + andj> 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()
+ +
Pattern Logic
1 for i in range(1, 6):
12 for j in range(1, i + 1):
123 print(j, end="")
1234
print()
12345
Pattern Logic
1 for i in range(1, 6):
21 for j in range(i, 0, -1):
321 print(j, end="")
4321 print()
54321
Pattern Logic
12345 foriinrange(5, 0, -1):
1234 forjin range(1, i + 1):
123 print(j, end="")
12 print()
1
Pattern Logic
12345 foriinrange(1, 6):
2345 forjin range(i, 6):
345 print(j, end="")
45
print()
5
Pattern Logic
5 foriinrange(5, 0, -1):
54 forjin range(5, i - 1, -1):
543 print(j, end="")
5432
print()
54321
Pattern Logic
5 foriinrange(5, 0, -1):
45 forjin range(i, 6):
345 print(j, end="")
2345
print()
12345
Pattern Logic
54321 foriinrange(1, 6):
5432 forjin range(5, i - 1, -1):
543 print(j, end="")
54
print()
5
Pattern Logic
foriinrange(5, 0, -1):
forjinrange(i, 5):
12345 print(" ", end="")
1234 forkinrange(1, i + 1):
123
print(k, end="")
12
1 print()
Pattern Logic
foriinrange(1, 6):
12345 forjinrange(1, i):
2345 print(" ", end="")
345
forkinrange(i, 6):
45
print(k, end="")
5 print()
Pattern Logic
foriinrange(5, 0, -1):
forjinrange(1, i):
5 print(" ", end="")
45
forkinrange(i, 6):
345
2345 print(k, end="")
12345 print()
Pattern Logic
foriinrange(5, 0, -1):
forjinrange(1, i):
5 print(" ", end="")
54
forkinrange(5, i - 1, -1):
543
5432 print(k, end="")
54321 print()
Pattern Logic
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
print()
ABCDE
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
print()
E
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
print()
A
Pattern Logic
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
foriinrange(1, 10):
ifi<= 5:
* forjinrange(1, i + 1):
**
print("*", end="")
***
**** print()
***** else:
**** forkinrange(i, 10):
*** print("*", end="")
** print()
*
Pattern Logic
foriinrange(1, 10):
ifi<= 5:
forxinrange(i, 6):
print(" ", end="")
* forjinrange(1, i + 1):
print("*", end="")
**
*** print()
**** else:
***** forxinrange(i, 5, -1):
**** print(" ", end="")
***
forkinrange(i, 10):
**
* 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
print(k % 2, end="")
010
10 k += 1
1 print()
Pattern Logic
1 for i in range(1, 6):
00 for j in range(1, i + 1):
111 print(i % 2, end="")
0000
print()
11111
Pattern Logic
11111 for i in range(5, 0, -1):
0000 for j in range(1, i + 1):
111 print(i % 2, end="")
00
print()
1
Pattern Logic
n=7
******** foriinrange(n, 0, -1):
* * forjinrange(1, i + 1):
* *
ifi== 1 or i == n or j == 1 or j == i:
* *
* * 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
foriinrange(1, n + 1):
* forjinrange(i, n):
*** print("", end="")
***** forkinrange(1, 2 * i):
*******
********* print("*", end="")
print()
Pattern Logic
n=7
foriinrange(1, n + 1):
forjinrange(i, n):
*
print("", end="")
* * forkinrange(1, 2 * i):
* *
* * ifi==1 or i == n or k == 1 or k == 2 * i - 1:
********* print("*", end="")
else:
print(" ", end="")
print()
Pattern Logic
n=7
for i in range(n, 0, -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()
Pattern Logic
n=7
for i in range(n, 0, -1):
555555555
for j in range(i, n):
4444444 print(" ", end="")
33333
for k in range(1, 2 * i):
222
1 print(i, end="")
print()
Pattern Logic
n=7
for i in range(n, 0, -1):
for j in range(i, n):
543212345
print(" ", end="")
4321234 for k in range(i, 0, -1):
32123
212 print(k, end="")
1 for l in range(2, i + 1):
print(l, end="")
print()
Pattern Logic
n=7
# Upper half of the diamond
for i in range(1, n + 1):
*
print(" " * (n - i) * 2, end="")
***
print("* " * (2 * i - 1))
*****
*******
********* # Lower half of the diamond (excluding the center row)
*********** for i in range(n - 1, 0, -1):
********* print(" " * (n - i) * 2, end="")
*******
***** print("* " * (2 * i - 1))
***
*
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)
deffun():
print("Hello...")
return
fun() # calling
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...")
greet() display_message()
import os
def clear_screen(): def print_pattern():
for i in range(1, 6):
print('*' * i)
[Link]('clear') # For Unix/Linux
print_pattern()
clear_screen()
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")
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
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()
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
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.
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)
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
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.
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.
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).
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.
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)
[Link]()
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")
[Link]()
[Link]()
return
[Link]()
[Link]()
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
classAccess:
a=20 #Static
defm1():
a=30 #Local
print("Inside m1")
print(a)
print(Access.a)
return
defm2():
print("Inside m2")
print(a)
print(Access.a)
return
defmain():
Access.m1()
Access.m2()
return
[Link]()
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.
classTest:
defm1():
#static method
return
defm2(self):
#dynamic method
return
def__init__(self):
#constructor
return
self:
• Itis used to define dynamic methods and constructor.
• Itis not a keyword but it is the most recommended variable to define dynamic
functionality.
• Itis 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 withpre-defined identity( __init__).
• It is a dynamic method(first argument is self)
• It invokes automaticallyin the process of Object creation.
class Test:
def __init__(self):
print("Constructor")
return
def main():
Test()#accessconstructor
return
[Link]()
def main():
foriinrange(10):
Test()
return
[Link]()
def main():
Test()
return
[Link]()
Test()
classTest:
def__init__(self):
print("Name :",type(self))
return
Test();
Test()
print("In main :", id(self))
defmain():
addr = Test()
print("In main :", id(addr))
return
[Link]()
defm2(self):
#dynamic method
return
class Test:
def main():
x = Test()
y = Test()
print("Addressofx : ", id(x))
print("Addressofy : ", id(y))
return
[Link]()
We can define the default constructor explicitly to understand the object creation process.
class Test:
def __init__(self):
print("ObjectCreated :", id(self))
return
def main():
x = Test()
y = Test()
print("Addressofx : ", id(x))
print("Addressofy : ", id(y))
return
[Link]()
def m1():
print("Staticmethod")
def m2(self):
print("Dynamic method")
return
[Link]()
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.
def main():
obj = Test()
print("x val :", obj.x)
print("y val :", obj.y)
return
[Link]()
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
[Link]()
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
[Link]()
• 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
def main():
obj = Test(10,20)
print("a val :", obj.a)
print("b val :", obj.b)
return
[Link]()
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)
[Link]()
return
[Link]()
defdetails(self):
print("Emp num is :", [Link])
print("Emp name is :", [Link])
return
def deposit(self,amt):
[Link]=[Link]+amt
print(amt,"deposited")
return
def withdraw(self,amt):
print("Withdrawing:",amt)
print("Availbal:",[Link])
if(amt<=[Link]):
print("Collectcash:",amt)
[Link]=[Link]-amt
else:
print("Error:Lowbalance")
return
class Bank:
def main():
amt=int(input("Enterinitial bal:"))
acc = Account(amt)
print("Balance is :",[Link])
amt=int(input("Enterwithdraw amt:"))
[Link](amt)
print("Final balance :",[Link])
return
[Link]()
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
[Link]()
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
[Link]()
class Second:
def main():
print("a val :", First.a)
print("b val :", First.__b)
return
[Link]()
def main():
obj = First(10,20)
print("a val : ", obj.a)
print("b val : ", obj.__b)
return
[Link]()
class Second:
def main():
obj = First(10,20)
print("a val : ", obj.a)
print("b val : ", obj.__b)
return
[Link]()
class First:
__a = 10
def getA():
return First.__a
class Second:
def main():
# print("a val : ", First.__a)
print("a val : ", [Link]())
return
[Link]()
def getA(self):
return self.__a
class Second:
def main():
obj = First(10)
# print("a val : ", obj.__a)
print("a val : ", [Link]())
return
[Link]()
Note: When we try set the value directly to private variable, the value will be omitted.
class Second:
def main():
print("aval:",[Link]())
First.__a=20
print("aval:",[Link]())
[Link](20)
print("aval:",[Link]())
return
[Link]()
class Second:
def main():
obj=First(10)
print("aval:",[Link]())
[Link](20)
print("aval:",[Link]())
return
[Link]()
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 :",[Link]())
return
[Link]()
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()
[Link]()
class Child(Parent):
def m2(self):
print("Child's m2")
return
class Inheritance:
def main():
c = Child()
c.m1()
c.m2()
[Link]()
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.
classParent:
deffun(self):
print("Parent's fun()")
return
classChild(Parent):
deffun(self): #override
print("Child's fun()")
return
classInheritance:
defmain():
obj = Child()
[Link]()
return
[Link]()
classGuru:
defcall(self):
print("Guru - Call")
return
defcamera(self):
print("Guru - Camera - 2MP")
return
classGalaxy(Guru):
defvideoCall(self):
print("Galaxy - Video Call")
return
defcamera(self):
print("Galaxy - Camera - 8MP")
return
classInheritance:
defmain():
g1 = Galaxy()
[Link]()# Access existing
[Link]()# new feature
[Link]() #updated
g2 = Guru()
[Link]()
[Link]()
[Link]() # error:
return
[Link]()
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()
[Link]()
return
[Link]()
• 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")
class Child(Parent):
def fun(self):
print("Child")
return
class Inheritance:
def main():
obj = Child()
[Link]()
super(Child, obj).fun()
super(Parent, obj).fun()
return
[Link]()
class A:
defm1(self):
print("A-m1")
return
defm3(self):
print("A-m3")
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
[Link]()
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
[Link]()
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
Compile
• time polymorphism:
• Itisalsocalled “Static binding”.
• Itis“Method Overloading” technique.
Definingmultiple methods with same name and different set of arguments is called
• “Overloading”.
Dependson input values, corresponding method executes.
class Calc:
def add(a,b):
res=a+b
print("Sumof 2 num's :", res)
return
class Overload:
def main():
[Link](10,20,30)
[Link](10,20) # error
return
[Link]()
class Overload:
def main():
[Link](10,20)
[Link](2.3,4.5)
[Link]("Python","Class")
return
[Link]()
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("Sumof",l,"elements :",sum)
return
class Overload:
def main():
[Link](10,20)
[Link](10,20,30)
[Link](10,20,30,40,50)
return
[Link]()
classGrand:
deffun(self):
print("Grand")
return
classParent(Grand):
deffun(self):
print("Parent")
return
classChild(Parent):
deffun(self):
print("Child")
return
classOverride:
defmain():
obj = Child()
[Link]()
super(Child,obj).fun()
super(Parent,obj).fun()
return
[Link]()
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.
exceptValueError:
print("Exception: Invalid input")
exceptZeroDivisionError:
print("Exception: Denominator should not be zero")
print("End")
exceptIndexError:
print("Exception: Index out of range.")
exceptValueError:
print("Exception: Invalid index input.")
print("End")
Exceptionclass:
• “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.
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
[Link]()
except Exception:
print("Except block")
finally:
print("Finally block")
return
[Link]()
exceptFileNotFoundError:
print("Exception:Nosuch file")
file=open("[Link]")
print("File opened...")
exceptFileNotFoundError:
print("Exception:Nosuch file")
finally:
if file is not None:
[Link]()
exceptFileNotFoundError:
print("Exception:Nosuch file")
finally:
if'file'inlocals()andnot [Link]:
[Link]()
[Link]()
exceptFileNotFoundError:
print("Exception : No such file")
finally:
[Link] != None:
[Link]()
print("File closed...")
return
[Link]()
Custom Exceptions:
• Pythonlibrary is providing number of exception classes.
• Asaprogrammer, we can define custom exceptions depends on application
requirement.
• Everycustom 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.
class RaiseException:
def main():
obj = CustomError("Error-Msg")
raise obj
return
[Link]()
class Test:
def fun():
obj = CustomError("Message")
raise obj
return
class Access:
def main():
try:
[Link]()
except CustomError as e:
print("Exception :",e)
return
[Link]()
class LowBalanceError(Exception):
def __init__(self,name):
[Link] = name
return
class Account:
def __init__(self,balance):
[Link] = balance
return
def withdraw(self,amount):
print("Trying to withdraw :",amount)
print("Avail bal :",[Link])
if amount <= [Link]:
print("Collect cash :",amount)
[Link]=[Link]-amount
else:
err=LowBalanceError("Low Balance")
raise err
return
class Bank:
def main():
amount = int(input("enter amount :"))
acc = Account(amount)
print("Balance is :",[Link])
[Link]()
Inner class: Defining a class inside another class. It is also called Nested class.
Syntax:
classOuter:
.....
logic
.....
class Inner:
.....
logic
.....
Accessingstatic functionality:
• Staticmembers we access using class name.
• Innerclass can be accessed using Outer class name.
class Outer:
def m1():
print("Outer-m1")
return
class Inner:
def m2():
print("Inner-m2")
return
class Access:
def main():
Outer.m1()
[Link].m2()
return
[Link]()
Accessingdynamic functionality:
• Wecanaccess dynamic member through object address.
• Wecreate object for inner class with the reference of outer class only.
class Inner:
def m2(self):
print("Inner-m2")
return
class Access:
def main():
obj1=Outer()
obj1.m1()
obj2=[Link]()
obj2.m2()
return
[Link]()
class Access:
def main():
#obj1=Outer()
#obj2=[Link]()
#[Link]()
Outer().Inner().fun()
return
[Link]()
class Outer:
def fun():
print("Outer-fun")
classLocal:
def fun():
print("Outer-Local-fun")
return
[Link]()
return
class Access:
def main():
[Link]()
return
[Link]()
def fun():
print("m1-Local-fun")
return
[Link]()
return
def m2():
print("Outer-m2")
classLocal:
def fun():
[Link]()
return
class Access:
def main():
Outer.m1()
Outer.m2()
return
[Link]()
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")
classLocal:
deffun(self):
print("Outer-Local-fun")
classInner:
deffun(self):
print("Outer-Local-Inner-fun")
return
Inner().fun()
return
Local().fun()
return
class Access:
def main():
Outer().fun()
return
[Link]()
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
[Link]:
defadd(a,b):
c=a+b
return c
defsubtract(a,b):
c=a-b
return c
defmultiply(a,b):
c=a*b
return c
res = [Link](a,b)
print("Add result :",res)
res = [Link](a,b)
print("Subtract result :",res)
res = [Link](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.
[Link]:
deff1():
print("one-f1()")
return
deff2():
print("one-f2()")
return
def f2():
print("two-f2()")
return
[Link]:
import one
import two
one.f1()
one.f2()
two.f1()
two.f2()
class XYZ:
def m2(self):
print("one-XYZ-m2()")
return
[Link]:
import one
class Access:
def main():
[Link].m1()
obj=[Link]()
obj.m2()
return
[Link]()
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
classXYZ:
defm2():
print("one-XYZ-m2()")
return
[Link]:
classABC:
defm1():
print("two-ABC-m1()")
return
classXYZ:
defm2():
print("two-XYZ-m2()")
return
[Link]:
importone
importtwo
classAccess:
defmain():
[Link].m1()
[Link].m2()
[Link]()
• When we import classes using ‘from’ keyword, we cannot work with duplicate classes
from different modules.
• Duplicate class replace the existing class as follows
Multi-tasking:
• We can implement multi-tasking in two ways.
o Program(process) based
o Sub program(thread) based.
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 [Link]
class and override the run() method.
#Example:
importthreading
classMyThread([Link]):
defrun(self):
#Code to be executed in the new thread
class Numbers:
def display(self):
for i in range(50):
print("i val :",i)
return
class Default:
def main():
print("Starts @ main")
obj = Numbers()
[Link]()
for j in range(50):
print("j val :",j)
print("Ends @ main")
return
[Link]()
class Default:
[Link]()
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.
def run(self):
for i in range(1,11):
print("custom : " + str(i))
[Link](1)
return
class Default:
def main():
obj = Custom()
[Link]()
for i in range(1,11):
print("default : " + str(i))
[Link](1)
return
[Link]()
class Default:
def main():
print("Starts at Default thread")
obj = Custom()
[Link]()
for i in range(1,11):
print("default : " + str(i))
[Link](0.3)
print("Default thread execution completed")
return
[Link]()
def run(self):
for i in range(1,11):
print("custom : " + str(i))
[Link](1)
return
class Default:
def main():
obj = Custom()
[Link]()
[Link]()
fromthreadingimportThread
import time
class Custom1(Thread):
def run(self):
for i in range(1,11):
print("custom1:"+str(i))
[Link](1)
return
class Custom2(Thread):
def run(self):
for i in range(50,71):
print("custom2:"+str(i))
[Link](1)
return
class Custom3(Thread):
def run(self):
foriinrange(100,90,-1):
print("custom3:"+str(i))
[Link](3)
return
classDefault:
def main():
c1 = Custom1()
[Link]()
c2 = Custom2()
[Link]()
c3 = Custom3()
[Link]()
return
[Link]()
def run(self):
for i in range(1,11):
print("custom : " + str(i))
[Link](1)
return
class Default:
def main():
print("Starts @ Default")
c = Custom()
[Link]()
[Link]()
print("Ends @ Default")
return
[Link]()
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 [Link]()
o [Link]()
import time
from threading import Thread, Lock
class Numbers:
x=0
lock=Lock()
def incrementX():
[Link]()
Numbers.x = Numbers.x+1
[Link]()
class Custom1(Thread):
def run(self):
foriinrange(100000):
[Link]()
return
class Custom2(Thread):
def run(self):
foriinrange(100000):
[Link]()
return
classDefault:
def main():
t1 = Custom1()
t2 = Custom2()
[Link]()
[Link]()
[Link]()
[Link]()
print("Finalxval:"+str(Numbers.x))
return
[Link]()
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():
my_thread=[Link](target=my_function)
my_thread.start()
thread1 = [Link](target=print_numbers)
thread2 = [Link](target=print_numbers)
[Link]()
[Link]()
[Link]()
[Link]()
print("End of program")
for _ in range(times):
print(message)
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[: :])
s = "python"
print("String is :",s)
print("s[Link]-1] :", s[Link]-1])
print("s[-1:-5:-1] :", s[-1:-5:-1])
s1 = "abc"
print(s1,"is alpha :", [Link]())
print(s1,"is alpha numeric :", [Link]())
print(s1,"is digit :", [Link]())
s1 = "1234"
print(s1,"is alpha :", [Link]())
print(s1,"is alpha numeric :", [Link]())
print(s1,"is digit :", [Link]())
s1 = "abc123"
print(s1,"is alpha :", [Link]())
print(s1,"is alpha numeric :", [Link]())
print(s1,"is digit :", [Link]())
s1 = "abc123$#"
print(s1,"is alpha numeric :", [Link]())
print(s1,"is lower :", [Link]())
#Escape characters
# \n = new line
# \t = tab space
# \\ = \
# \' = '
# \" = "
# Output : This is "Python" session
line = "This is \"Python\" session"
print(line)
String representation:
name = input("Enter your name : ")
print("Hello" , name)
print("Hello " + name)
print("Hello %s" %name)
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:
Note: Immutable objects nothing but constants. We can’t modify once we have created
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))
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))
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.
List 1.
Tuple2.
Set 3.
4. Dictionary
As Python doesn’t supportArrays, we use third party modules (Numpy & Pandas) to
process elements like arrays.
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)])
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]
Start index default value is 0
• Stop index default value is length-1
• Step value modified by 1
•
• When we don’t specify the values of start, stop and step, it will consider default values
and process all elements of List.
• Start index is includes where as stop index value excludes.
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[Link] :", l[Link])
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[Link] : [10, 30, 50]
l[-5:-2] : [10, 20, 30]
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)
[Link](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
l = [10,20,10,40]
print("List :", l)
print("insert 50 @ index : 2 :")
[Link](2,50)
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)
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: [Link](x): x not in list
Code:
l = [10,20,30,40,50]
print("List is :", l)
print("append(20) :")
[Link](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
Code:
l1 = [10, 20, 30]
print("L1 is :", l1)
l2 = [23.45, 56.78]
print("L2 is :", l2)
print("l1 extends l2 :")
[Link](l2)
print("L1 after extend :", l1)
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 = [Link]()
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.
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 :")
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)
[Link]()
print("Sorted a1 list is :", a1)
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
arr = list()
print("List is :", arr)
print("Length :", len(arr))
print("Any :", any(arr))
Output:
List is : []
Length : 0
Any : False
Output:
Initially : []
Enter5elements :
10
23.42
g
abc
10
Later:['10','23.42', 'g', 'abc', '10']
Sumoflistelements:
print("Sumof list elements")
arr = list()
n=int(input("Enter size : "))
print("Enter%d elements :" %n)
foriinrange(n):
ele=int(input())
[Link](ele)
Output:
Sum of list elements
Enter size : 5
Enter 5 elements :
6
4
2
8
3
Sumis: 23
>>>List=[6,3,8,2,9]
>>> min(List)
2
>>> max(List)
9
>>> sum(List)
28
>>> sorted(List)
[2,3, 6,8, 9]
>>> print(List)
[6,3, 8,2, 9]
a = [10,20,30,[40,50,60]]
print("List is :", a)
# access using indexing
print("a[1] :",a[1])
print("a[3] :",a[3])
# 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)
# access sub list
print("a[3][0] :", a[3][0])
print("a[-1][0] :", a[-1][0])
print("a[3][-3] :", a[3][-3])
print("a[-1][-3] :", a[-1][-3])
# 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])
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)
# sub list slicing
print("a[-1][:] :", a[-1][:])
print("a[-1][1:3] :", a[-1][1:3])
print("a[len(a)-1][0:len(a[-1])] :", a[len(a)-1][0:len(a[-1])])
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]))
a = [10, 20]
print("List is :",a)
print("Address :",id(a))
[Link](30)
print("After append, List is :",a)
print("Address :",id(a))
[Link]()
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]))
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
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)
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)
[Link](40) #modifying list
print("List is :",a)
[Link](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]
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
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)
[Link](60)
print("Set after adding :",s)
[Link](20)
[Link](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}
s = {10,20,30}
print("Set :", s)
print("Address :", id(s))
[Link](40)
[Link](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)
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}
#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'>
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)
[Link]()
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'
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.
accounts ={101:"harin", 102:"kiritin", 103:"ramya", 104:"annie"}
print("Accounts :", accounts)
#list of keys will be returned
print("Keys :", [Link]())
#returns list of values
print("Values :", [Link]())
[Link](102)
print("After removal of 102 :", accounts)
[Link]()
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 = [Link](accno)
print(name)
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.
• Iffile is present, it opens and removes existing content.
• Iffile 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.
Code:
try:
src = open(file="[Link]", mode="r")
print("File is present")
except FileNotFoundError:
print("Exception : No such file")
try:
src=open(file="d:/[Link]", mode="r")
print("File is present")
data=[Link]()
print(data)
exceptFileNotFoundError:
print("Exception : No such file")
exceptFileNotFoundError:
print("Exception : No such file")
try:
src=open(file="d:/[Link]",mode="r")
print("File is present")
data = [Link]()
for ch in data:
print(ch)
except FileNotFoundError:
print("Exception : No such file")
try:
src=open(file="d:/[Link]",mode="r")
print("File is present")
data = [Link]()
count=0
for ch in data:
count=count+1
except FileNotFoundError:
print("Exception : No such file")
src = None
try:
src = open(file="d:/[Link]", mode="r")
except FileNotFoundError:
print("Exception : No such file")
finally:
if(src != None):
[Link]()
print("File closed")
src = None
try:
src=open(file="d:/[Link]", mode="r")
print("Fileis opened")
#data=[Link]()
forlineinsrc:
print(line)
exceptFileNotFoundError:
print("Exception : No such file")
finally:
if(src!=None):
[Link]()
print("File closed")
count=0
forlineinsrc:
print(line)
count=count+1
except FileNotFoundError:
print("Exception : No such file")
finally:
if(src != None):
[Link]()
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:
print("Datacopied")
exceptFileNotFoundError:
print("Exception:No such file")
finally:
if(src != None):
[Link]()
print("srcFileclosed")
if(dest != None):
[Link]()
print("destFileclosed")
tell():Methodbelongs to File object. It returns the current position (value) on the file.
seek():Methodbelongs to File object. It is used to sets the cursor position to specific location.
class Source:
file = None
def main():
try:
[Link]=open("./[Link]" , "r")
data=[Link]()
print(data)
print("Cursorat : ",[Link]())
[Link](0)
print("Cursorat : ",[Link]())
data=[Link]()
print(data)
finally:
[Link]!= None:
[Link]()
return
[Link]()
finally:
[Link] != None:
[Link]()
return
[Link]()
csv module
Creating [Link]:
• Open notepad file.
• Write records information by separating with comma
101,amar,5000
102,annie,8000
103,hareen,7500
103,satya,6500
• Save the file with .csv extension
• Close the file and re-open the file.
• File will be opened with MS-Excel software by default.
import csv
class ReadCSV:
file = None
def main():
try:
[Link]=open("./[Link]" , "r")
print("File opened")
table=[Link]([Link])
print("Records are :")
for record in table:
print(record)
except Exception as e:
print("Exception :", e)
finally:
if [Link] != None:
[Link]()
return
[Link]()
[Link] file:
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 : ", [Link])
print("Balance :", [Link])
except Exception as e :
print("Exception :", e)
ch=input("Doyouwanttocheckanotherrecord(y/n) : ")
if ch=='n':
break
return
class CSVtoDict:
file = None
def main():
try:
[Link] = open("./[Link]" , "r")
print("File opened")
table = [Link]([Link])
for record in table:
num = int(record[0])
name = record[1]
balance = int(record[2])
except Exception as e:
print("Exception :", e)
finally:
if [Link] != None:
[Link]()
print("File closed")
return
[Link]()
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
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.
[Link]:
class Employee :
def __init__(self, num, name, salary):
[Link] = num
[Link] = name
[Link] = salary
return
[Link]:
import pickle
from emp import Employee
class Serialization:
file = None
def main():
try :
[Link] = open("./[Link]", mode="wb")
print("File is ready")
except Exception as e:
print("Exception :", e)
finally:
if [Link] != None:
[Link]()
print("File closed")
return
[Link]()
[Link]:
import pickle
from emp import Employee
class DeSerialization:
file = None
def main():
try :
[Link] = open("./[Link]", mode="rb")
print("File is ready")
obj = [Link]([Link])
print("Object is De-serialized successfully")
print("Employee details are :")
print("Emp num :", [Link])
print("Emp name :", [Link])
print("Emp salary :", [Link])
except Exception as e:
print("Exception :", e)
finally:
if [Link] != None:
[Link]()
print("File closed")
return
[Link]()
Run [Link]:
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")
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))
numbers = [1, 2, 3, 4, 5]
result = list(map(double_and_add_ten, numbers))
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
[Link]()
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.
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.
[Link]:
• ‘sys’ is a pre-defined module
• ‘argv’ is a list belongs to ‘sys’ module.
• ‘argv’ holds command line arguments implicitly.
Memory allocation:
Code:
importsys
classCmdLine:
defmain():
count = len([Link])
print("Arguments count :",count)
return
[Link]()
Run:
[Link]()
Run:
except IndexError :
print("Exception : Insufficient values")
except ValueError :
print("Exception : Invalid Input")
except ZeroDivisionError :
print("Exception : Division by zero")
return
[Link]()
return
[Link]()
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
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
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);
[Link]:
• 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.
• On success,returnsconnection object
• On failure,raisesasexception
Connecting to Database:
import [Link]
classDB:
con = None
def main():
try:
[Link]=[Link](user='root', password='root',
host='[Link]', database='student')
print("Connectedtodatabase")
finally:
if [Link] != None:
[Link]()
print("Database released")
return
[Link]()
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 [Link]
class DB:
con = None
def main():
try :
[Link] = [Link](user='root', password='root',
host='[Link]', database='student')
print("Connected to database")
cur = [Link]()
query = "create table account(no int, name varchar(20), balance int)"
[Link](query)
print("Table created successfully")
finally:
if [Link] != None:
[Link]()
print("Database released")
return
[Link]()
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 [Link]
class DB:
con = None
def main():
try :
[Link] = [Link](user='root', password='root',
host='[Link]', database='student')
print("Connected to database")
cur = [Link]()
query = "insert into account values(101, 'amar', 7000)"
finally:
if [Link] != None:
[Link]()
print("Database released")
return
[Link]()
Output:
In database:
import [Link]
classDB:
con = None
def main():
try:
[Link]=[Link](user='root', password='root',
host='[Link]', database='student')
print("Connectedtodatabase")
cur = [Link]()
query="select*fromaccount"
[Link](query)
record = [Link]()
print("Firstrecorddetails : ", record)
finally:
if [Link] != None:
[Link]()
print("Databasereleased")
return
[Link]()
record = [Link]()
print("102 record details : ")
print("Account Number :", record[0])
print("Name :", record[1])
print("Balance :", record[2])
finally:
if [Link] != None:
[Link]()
print("Database released")
return
[Link]()
Output:
Connected to database
102 record details :
Account Number : 102
Name : annie
Balance : 6000
Database released
import [Link]
class DB:
con = None
def main():
try :
[Link] = [Link](user='root', password='root',
host='[Link]', database='student')
print("Connected to database")
cur = [Link]()
table = [Link]()
print("Table details :")
for record in table:
print(record)
finally:
if [Link] != None:
[Link]()
print("Database released")
return
[Link]()
Output:
Connected to database
Table details :
(101, 'amar', 7000)
(102, 'annie', 6000)
(103, 'hareen', 9000)
Database released
import [Link]
classDB:
con = None
def main():
try:
[Link]=[Link](user='root', password='root',
host='[Link]', database='student')
print("Connectedtodatabase")
cur = [Link]()
query="updateaccountset balance = balance+1500 where no=102"
[Link](query)
[Link]()
print("Record updated")
finally:
if [Link] != None:
[Link]()
print("Databasereleased")
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)
finally:
if [Link] != None:
[Link]()
print("Databasereleased")
return
[Link]()
Output:
[Link]()
print("Record updated")
finally:
if [Link] != None:
[Link]()
print("Database released")
return
[Link]()
Output:
Connected to database
Enter account number : 101
Enter deposit amount : 1200
Record updated
Database released
[Link](query)
print("Record inserted....")
[Link]()
print("Transactioncommitted")
finally:
if [Link] != None:
[Link]()
print("Databasereleased")
return
[Link]()
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
[Link]()
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()
[Link]("GUI")
b = Button(root, text="Click Me")
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”)
def display():
print("Button clicked")
return
root = Tk()
[Link]("GUI")
[Link]("500x300")
def display():
print("Button clicked")
return
root = Tk()
[Link]("GUI")
[Link]("500x300")
name = [Link]()
print("Hello %s, welcome" %name)
return
root = Tk()
[Link]("GUI")
[Link]("500x300")
print("Button clicked")
return
root = Tk()
[Link]("GUI")
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 = [Link]()
loc = [Link]()
print("%s live in %s" %(name,loc))
return
root = Tk()
[Link]("GUI")
l1 = Label(root, text="Enter Name :", font="Times 20")
l2 = Label(root, text="Enter Loc :", font="Times 20")
e1 = Entry(root, font="Times 20")
e2 = Entry(root, font="Times 20")
b1 = Button(root, text="details", font="Times 15", command=details)
b2 = Button(root, text="exit", font="Times 15", command=quit)
[Link](row=0, column=0)
[Link](row=0, column=1)
[Link](row=1, column=0)
[Link](row=1, column=1)
[Link](row=2, column=0)
[Link](row=2, column=1)
Output:
window = Tk()
[Link]("Grid Layout")
l = Label(window, text="Enter Name :", font="Times 25")
[Link](row=0, column=0)
e = Entry(window, font="Times 25", fg="red")
[Link](row=0, column=1)
b = Button(window, text="Click", font="Times 20", command=func)
[Link](row=0, column=2)
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.
window = Tk()
msg = StringVar()
[Link]("Dynamic Text")
[Link]("750x300")
l = Label(window, text="Enter Name :", font="Times 20")
[Link](x=50, y=50)
e = Entry(window, font="Times 20", fg="red")
[Link](x=250, y=50)
b = Button(window, text="Click", font="Times 15", command=func)
[Link](x=600, y=50)
res = Label(window, textvariable=msg, font="Times 20", fg="blue")
[Link](x=150, y=175)
Output:
Simplecalculator program:
s1 = [Link]()
s2 = [Link]()
if len(s1)==0 or len(s2)==0 :
[Link]("Error : Empty input")
else:
try :
x = int(s1)
y = int(s2)
z = x+y
[Link]("")
[Link](str(z))
except ValueError :
[Link]("Error : Invalid Input")
return
window = Tk()
[Link]("Calculator")
err = StringVar()
res = StringVar()
l1 = Label(window, text="Enter Input :", font="Times 15")
[Link](row=0, column=0)
e1 = Entry(window, font="Times 15")
[Link](row=0, column=1)
l2 = Label(window, text=" + ", font="Times 15")
[Link](row=0, column=2)
e2 = Entry(window, font="Times 15")
[Link](row=0, column=3)
l3 = Label(window, text=" = ", font="Times 15")
[Link](row=0, column=4)
e3 = Entry(window, font="Times 15", textvariable=res)
Output:
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 = [Link](r'Java' , line)
print("Success : ",res)
res = [Link](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 = [Link](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.
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 = [Link](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 = [Link](r' ' , line)
print("Tokens :" , tokens)
print("Count :" , len(tokens))
print("Index of Python :" , [Link]('Python'))
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 = [Link](r'Python' , line)
if found:
print("String starts with specified pattern")
else:
print("String not starts with Python")
import re
line = "Python and R"
res = [Link](r'.' , line)
print(res)
res = [Link](r'\w' , line)
print(res)
Date extraction :
import re
data = "ab12-04-1987 23-ab09-2003 31-03-2005ab"
res = [Link](r'\d{2}-\d{2}-\d{4}' , data)
print(res)
Rename a file:
import os
old_file_path = "/path/to/old/file"
new_file_path = "/path/to/new/file"
[Link](old_file_path, new_file_path)
print(f"Renamed file from {old_file_path} to {new_file_path}")
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".
print(ele)
Transpose a Matrix:
import numpy as np
matrix = [Link]([[1, 2, 3], [4, 5, 6]])
transposed = [Link](matrix)
print(transposed)
Code:
importnumpy as np
arr = [Link](shape=(5))
print("Size :",[Link])
print("Datatype :",[Link])
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 = [Link](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 = [Link](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)
forjin range(3):
print(my_array[i,j], end=' ')
print()
Matrixaddition program:
importnumpy as np
#Define two matrices
a= [Link]([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
b= [Link]([[9, 8, 7], [6, 5, 4], [3, 2, 1]])
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 = [Link]()
print(s)
importpandas as pd
importnumpy as np
arr=[Link](['a', 'b', 'c', 'd', 'e'])
s=[Link](arr)
print(s)
Output:
0 a
1 b
2 c
3 d
4 e
dtype:object
dtypes:
• Ifwe store integers, the dtype become int
• Ifwe store integers and floats, the dtype become float
• Ifwe store integers, floats, Strings…, the dtype become ‘Object’
Output:
0 10
1 20
2 30
3 40
4 50
dtype: int32
import pandas as pd
import numpy as np
arr = [Link]([10, 23.45, 30, "python"])
s = [Link](arr)
print(s)
Output:
0 10
1 23.45
2 30
3 python
dtype: object
import pandas as pd
import numpy as np
arr = [Link](['a', 'b', 'c', 'd', 'e'])
s = [Link](arr, index=[1,2,3,4,5])
print(s)
Output:
1 a
2 b
3 c
4 d
5 e
dtype: object
importpandas as pd
importnumpy as np
arr=[Link](['a', 'b', 'c', 'd', 'e'])
s=[Link](arr, index=[10,23.45,'g',"key",20])
print(s)
Output:
10 a
23.45 b
g c
key d
20 e
dtype:object
Keyscanbe duplicated. We can see the accessibility of elements using duplicate keys
later.
importpandas as pd
importnumpy as np
arr = [Link](['a', 'b', 'c', 'd', 'e'])
s = [Link](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 = [Link](dictionary)
print(s)
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 = [Link](List)
series = [Link](arr)
Output:
Series object elements :
10
20
30
40
50
import pandas as pd
import numpy as np
arr = [Link]([10,20,30,40,50])
series = [Link](arr)
print("Series elements through indexing :")
print(series[2])
print(series[4])
import pandas as pd
import numpy as np
arr = [Link]([10,20,30,40,50])
series = [Link](arr)
print("Series elements through slicing :")
print(series[:])
print()
print(series[1:4])
print()
import pandas as pd
import numpy as np
arr = [Link]([10,20,30,40,50])
series = [Link](arr, index=['a', 'b', 'c', 'd', 'e'])
print(series['a'])
print(series['d'])
Output: 10 40
import pandas as pd
import numpy as np
arr = [Link](['a', 'b', 'c', 'd', 'e'])
series = [Link](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
Output:
0 1
010 abc
1 20 xyz
230 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 = [Link](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 = [Link](data, columns=['Age', 'Name'])
print(frame)
Output:
Age Name
0 21 amar
1 19 annie
2 22 hareen
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 = [Link](data)
print(frame)
Output:
Age Name
021 Syam
1 19 Ricky
2 23 Raksha
3 21 Kiritin
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
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
B : Blue marker
GarbageCollection:
• Python is fully Object Oriented Programming Language.
• InOOP application, data stores in the form of Objects.
• Weaccess the objects information using references.
• Garbage collection is the mechanism of deleting unreferenced objects.
• Anobject is said to be eligible for Garbage Collection when no pointer is pointing to that
object.
• Inpython garbage collection mechanism is much faster compare to other languages.
classGCDemo:
defmain():
x=Test()
y=Test()
z=Test()
return
[Link]()
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
classGCDemo:
defmain():
Test()
Test()
Test()
return
[Link]()
class Test:
def fun():
x = []
[Link](10)
print("Address of x :", id(x))
return
class GCDemo:
def main():
[Link]()
[Link]()
[Link]()
return
[Link]()
class Test:
def fun():
x = []
[Link](x)
print("Address of x :", id(x))
return
class GCDemo:
def main():
[Link]()
[Link]()
[Link]()
return
[Link]()
[Link]()
Nested Function:
o Anestedfunctionisa function defined inside another function.
o Thenestedfunctionhas access to the variables in the outer function's scope.
outer_function()
ReturningaNestedFunction:
def outer_function(x):
def inner_function(y):
return x + y
return inner_function
closure=outer_function(10)
result = closure(5)
print(result)
square = exponentiate(2)
cube = exponentiate(3)
print(square(3))
print(cube(2))
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.
defmy_decorator(func):
defwrapper():
print("Before the function is called.")
func()
print("After the function is called.")
return wrapper
@my_decorator
defsay_hello():
print("Hello!")
say_hello()