Python Basics 3
Python Basics 3
python --version
Python 3.12.7
In [2]: print("Kasi")
Kasi
Text highlighting
python is a programming language
for , while are used to loop
Data Types
1. integer
1,2,3
2. Float
2.05,-5
3. Boolean
True
False
4. String
"Hello","S"
5. Collections
Lists
Tuple
Set
Dictionary
Variables
must start with letter or underscore
shouldn't start with a number
A variable name should only contain alpha-numeric characters and underscore
It can't be a keyword
variables are case sensitive
Variables with more than one word can be difficult to
read.So,3 ways of writing a variable
1.camelCase
2.PascalCase
3.snake_case
assigning a variable
In [3]: price = 100
100
118.0
to check datatype
In [6]: #to check the data type
price = 100
GST = price*1.18
In [7]: type(price)
Out[7]: int
In [8]: type(GST)
Out[8]: float
input keyword
In [9]: #input keyword
name = input("Enter your name : ")
In [10]: print(name)
K KASI REDDY
60
In [12]: type(quantity)
Out[12]: int
In [14]: type(c)
Out[14]: int
60
240
Out[23]: 4.25
Out[24]: 4
Out[25]: 1
Out[26]: 68
Out[27]: 25
Out[28]: 3.7416573867739413
Out[29]: 3.742
In [30]: help(round) #if we forgot syntax then we get with the help or place cursor
Help on built-in function round in module builtins:
round(number, ndigits=None)
Round a number to a given precision in decimal digits.
Operators
1.Arithmetic operator
2.Assignment operator
3.Comparision operator
4.Logical operator
5.Identity operator
6.Membership operator
10
In [32]: y=10
y-=5
print(y)
In [33]: z=10
z*=5
print(z)
50
In [34]: Z=10
Z/=5
print(Z)
2.0
In [35]: z=12
z//=5
print(z)
In [36]: v=230
v%=34
print(v)
26
In [39]: x=5
x**=4
print(x)
625
Comparision operator
In [40]: 5==5
Out[40]: True
In [41]: 6!=7
Out[41]: True
In [42]: 5>6
Out[42]: False
In [43]: 7<6
Out[43]: False
In [44]: 7<=8
Out[44]: True
In [45]: 8>=9
Out[45]: False
Out[46]: False
Out[47]: False
Out[48]: True
in logical 'or' operations if one of the expression is
' true' then entire expression is 'true'
Out[49]: True
Out[50]: False
Out[51]: False
Out[52]: True
In [53]: a=256
b=256
a is b
Out[53]: True
In [54]: m=257
n=257
m is n # upto 256 value,value and reference are same
Out[54]: False
Out[55]: True
In [56]: id(x),id(y)
In [57]: id(a),id(b)
Out[57]: (140719882914200, 140719882914200)
In [58]: id(m),id(n)
f-format string
In [65]: boxes = 100
boxes+=20
print(f"Total no of boxes = {boxes}")
Apple price = 60
Banana price = 100.0
2
30
Total work time = 2 hours 30 minutes
150.0
Billing amount after discount= 850.0
In [70]: pencils=125
print(f"Total full boxes = {125//12} and {pencils%12} left out")
In [71]: 56!=100 and 45>=41 or not 67!=45 and not 32<10 or 89<=91
# T and T or not T and not F or T
# T and T or F and T or T
# T or F or T
# T or T
# T
Out[71]: True
Conditional statements
simple if-else statements
9 is odd number
In [ ]:
elif ladder
1.Number problem
(100 ->999) - three digit number
(10->99) - two digit number
(0 ->9) - one digit number
2 . Grading problem
(75 to 100) - A grade
(65 to 75) - B grade
(50 to 65) - C grade
(35 to 50) - D grade
<35 - Fail
82 belongs to A grade
3.BMI PROBLEM
In [92]: Weight = int(input("enter the weight :"))
height = float(input("enter the height :"))
bmi = Weight/(height **2) # check for operator
BMI = round(bmi,2)
if 0 <= BMI <= 18.5:
print(f"{BMI} is underweight")
elif 18.5 <= BMI <= 25:
print(f"{BMI} is healthy")
elif 25 <= BMI <= 30 :
print(f"{BMI} is over weight")
elif bmi >= 30 :
print(f"{BMI} is obesity")
else :
print(f"{BMI} value is invalid")
3.06 is underweight
Write a program which will accept a word and a number from the user.
Check if the word starts with a vowel and the number is even and write
appropriate conditions accordingly
cases
word is starting with vowel and num is even
word is starting with vowel and num is odd
word is not starting with vowel and num is even
word is not starting with vowel and num is odd
5.Write a program that takes the name of a day (e.g., "Monday") as input
and prints:
"Weekday" if it's Monday to Friday
"Weekend" if it's Saturday or Sunday
"Invalid day" for anything else
In [104… weekdays=['monday','tuesday','wednesday','thursday','friday']
weekends=['Saturday','Sunday']
day = input("Enter a day : ")
if day.lower() in weekdays :
print(f'{day} is a weekday')
elif day.capitalize() in weekends :
print(f'{day} is a weekend')
else :
print("Invalid input")
Monday is a weekday
Distinction
2.Problem:
You are building a simple electricity billing system. Based on the number of units
consumed, the rate per unit varies:
In [ ]:
Collections-List,Tuple,Set,Dictionary
list
list is an ordered collection of mutable type
created using [ ]
items in list are seperated by comma
ordered
indexable
allows duplicates
heterogeneous
mutable
Out[113… 'kasi'
In [114… print(L[3])
kasi
In [117… print(L)
In [121… print(fruits)
In [122… print(len(fruits))
In [123… print(fruits[len(fruits)-3])
Banana
In [124… fruits[3]="Avacado"
In [125… print(fruits)
In [126… print(len(fruits) - 1)
In [129… print(fruits[(len(fruits)-5)])
Apple
slicing
In [130… l=[3,4,5,"lion","true",42,"lion","true",3.125]
l[2:6:1]
In [131… l[1::2]
In [132… l[::3]
In [134… l[2:6:-2] # the output is blank because starting from and steps back
Out[134… []
In [135… l[8:2:-2]
In [137… fruits[2::2] #print every second element starting from 3rd item
In [141… fruits[::-1] #Print entire list in reverse direction and it's temporary re
Out[141… ['kiwi',
'Pomegranate',
'Water Melon',
'Pine Apple',
'Banana',
'Mango',
'Apple']
concatenation
In [142… e=["hello","Kasi",2,3,4]
f=["fruits","animals","birds"]
g=e+f
g
In [143… print(g)
nested list
In [146… c =[30,20,50,["Hello","good",10]]
c[3] #accessing list item
Out[147… 'good'
In [150… fruits
In [ ]:
3.Changing values
In [152… fruits=['Apple', 'Banana', 'Cherry', 'kiwi', 'Water melon', 'pine apple',
fruits
Out[152… ['Apple', 'Banana', 'Cherry', 'kiwi', 'Water melon', 'pine apple', 'oran
ge']
In [153… fruits[3]="pomegrante"
print(fruits)
['Apple', 'Banana', 'Cherry', 'pomegrante', 'Water melon', 'pine apple',
'orange']
In [154… fruits[-1]="grapes"
print(fruits)
In [155… fruits
Out[155… ['Apple',
'Banana',
'Cherry',
'pomegrante',
'Water melon',
'pine apple',
'grapes']
In [ ]:
In [158… fruits.pop(4)
fruits
In [159… fruits.pop(-3)
fruits
In [ ]:
--------------------------------------------------------------------------
-
ValueError Traceback (most recent call las
t)
Cell In[162], line 1
----> 1 fruits.remove("grapes")
In [ ]:
In [166… fruits
In [ ]:
In [168… len(fruits)
Out[168… 4
In [169… fruits.clear()
In [170… len(fruits)
Out[170… 0
In [ ]:
In [172… n.count(4)
Out[172… 3
In [173… n.count(1)
Out[173… 1
In [174… n.count(6)
Out[174… 2
In [175… len(n)
Out[175… 16
In [176… n.count("Apple")
Out[176… 2
In [ ]:
In [178… n
In [179… n.index(4)
Out[179… 3
In [180… n.index(10)
Out[180… 12
In [181… n.index(6)
Out[181… 6
In [182… n.index(4,6,10) #index(value we are searching for,start,stop)
Out[182… 7
In [183… n.index(6,8,11)
--------------------------------------------------------------------------
-
ValueError Traceback (most recent call las
t)
Cell In[183], line 1
----> 1 n.index(6,8,11)
In [184… n.index(6,8,12)
Out[184… 11
In [ ]:
10.reverse()
In [185… q=[23,10,-100,23,34,67,65,23,12,10]
In [186… q
Out[186… [23, 10, -100, 23, 34, 67, 65, 23, 12, 10]
Out[187… [10, 12, 23, 65, 67, 34, 23, -100, 10, 23]
In [188… q.reverse()
q
Out[188… [10, 12, 23, 65, 67, 34, 23, -100, 10, 23]
In [189… q
Out[189… [10, 12, 23, 65, 67, 34, 23, -100, 10, 23]
In [191… q
Out[191… [23, 10, -100, 23, 34, 67, 65, 23, 12, 10]
In [ ]:
11.sort()
In [192… q=[23, 10, -100, 23, 34, 67, 65, 23, 12, 10]
In [193… q
Out[193… [23, 10, -100, 23, 34, 67, 65, 23, 12, 10]
Out[194… [-100, 10, 10, 12, 23, 23, 23, 34, 65, 67]
In [195… q.sort(reverse=True)
q
Out[195… [67, 65, 34, 23, 23, 23, 12, 10, 10, -100]
In [197… fruits.sort()
fruits
In [198… fruits.sort(reverse=True)
fruits
In [199… fruits.sort(key=len)
fruits
In [200… fruits.sort(key=len,reverse=True)
fruits
In [ ]:
12.insert()
In [201… q=[23, 10, -100, 23, 34, 67, 65, 23, 12, 10]
q
Out[201… [23, 10, -100, 23, 34, 67, 65, 23, 12, 10]
In [202… q.insert(2,2000) #inserts object i.e item or value before the index
q
Out[202… [23, 10, 2000, -100, 23, 34, 67, 65, 23, 12, 10]
In [203… q.insert(-2,-150)
q
Out[203… [23, 10, 2000, -100, 23, 34, 67, 65, 23, -150, 12, 10]
In [ ]:
Cls Excercise
🏏 Initial List of Sports
sports = ['cricket', 'football', 'tennis', 'hockey',
'badminton']
In [204… sports=["cricket","football","tennis","hockey","badminton"]
Out[207… ['cricket',
'football',
'volleyball',
'tennis',
'hockey',
'badminton',
'basketball']
Out[209… ['cricket',
'football',
'volleyball',
'hockey',
'badminton',
'basketball',
'kabaddi',
'ruggy']
In [210… # Remove the last item from the list and store it in a variable
popped_item=sports.pop(-1)
popped_item
Out[210… 'ruggy'
In [211… # Remove the item at index 1 and print what was removed
popped_item_at_index_1=sports.pop(1)
popped_item_at_index_1
Out[211… 'football'
In [213… # Add 'cricket' again to the list and count how many times it appears
sports.append("cricket")
sports
Out[213… ['cricket',
'volleyball',
'hockey',
'badminton',
'basketball',
'kabaddi',
'cricket']
In [214… sports.count("cricket")
Out[214… 2
In [215… # Sort the list in alphabetical order
sports.sort()
sports
Out[215… ['badminton',
'basketball',
'cricket',
'cricket',
'hockey',
'kabaddi',
'volleyball']
Out[216… ['volleyball',
'kabaddi',
'hockey',
'cricket',
'cricket',
'basketball',
'badminton']
In [217… sports
Out[217… ['volleyball',
'kabaddi',
'hockey',
'cricket',
'cricket',
'basketball',
'badminton']
In [218… len(sports)
Out[218… 7
In [220… len(sports)
Out[220… 0
In [221… sports
Out[221… []
In [ ]:
tuple
Tuples are ordered collection of immutable type
created using ( )
items in tuple are seperated by comma
ordered
indexable
allows duplicates
heterogeneous
immutable(only count and index are possible,can't add,delete,modify)
In [222… t1=(100,'pencil',2.001,True)
print(t1)
Out[223… tuple
In [224… s1=("Python")
type(s1) # a single item considers as a string
Out[224… str
In [225… s1=("python",)
type(s1) # to make it tuple add ',' next to the item or element
Out[225… tuple
In [226… t1
Slicing
In [227… t1[2]=200 # as tuples are immutable,it gives an error
--------------------------------------------------------------------------
-
TypeError Traceback (most recent call las
t)
Cell In[227], line 1
----> 1 t1[2]=200
Out[228… True
In [230… t2[3]
In [232… t2[-1][1]
Out[232… 'python'
In [233… t2[2][0]
Out[233… 30
In [ ]:
concatenation
In [234… t1=(100,'pencil',2.001,True)
t2=(600,"Good morning",(30,-2,"Apple"),[0.001,"python",-10])
In [235… print(t1+t2)
(100, 'pencil', 2.001, True, 600, 'Good morning', (30, -2, 'Apple'), [0.00
1, 'python', -10])
In [236… t1
In [237… t2
Out[237… (600, 'Good morning', (30, -2, 'Apple'), [0.001, 'python', -10])
In [ ]:
tuple declaraation
count()
In [239… t3.count(100)
Out[239… 3
index()
In [240… t3.index(100,2,6) #finding index off 100 in between start and stop range
Out[240… 4
In [241… t3.index(100)
Out[241… 0
In [246… print(dir(list))
In [247… print(dir(list)[-15:])
In [248… print(dir(tuple))
In [249… print(dir(tuple)[-6:])
sorted
In [250… t=(3,4,7,9,1,0,-1,-100)
t
In [251… sorted(t) # directly we don't have method for sorting but we can do it wi
In [253… sorted_tu=sorted(t)
sorted_tu # we can assign it to variable and can make it permanent
sort by length
sorted(tuple_name,key=len)
In [257… x
Out[257… 100
In [258… y
Out[258… 'hello'
In [259… z
Out[259… 2.001
In [260… t1
In [261… a='welcome'
b=45
c=200
d=False
t1= a,b,c,d #packing
In [262… t1
In [263… a
Out[263… 'welcome'
In [264… b
Out[264… 45
In [265… c
Out[265… 200
In [266… d
Out[266… False
In [ ]:
Basic functions
In [267… t=(100,-1,2.001,2000,-0.111)
t
In [268… sum(t)
Out[268… 2100.8900000000003
In [269… round(sum(t),2)
Out[269… 2100.89
In [270… min(t)
Out[270… -1
In [271… max(t)
Out[271… 2000
In [272… len(t)
Out[272… 5
In [273… avg=sum(t)/len(t)
avg
Out[273… 420.17800000000005
In [ ]:
🔹 1. Basic Info
What is the type of data?
What is the length of data?
🔹 2. Indexing
What is data[0]?
What is data[-1]?
What is the output of data[4][0]?
🔹 3. Slicing
Slice first 3 elements of data
Get all elements except the last one
🔹 4. Immutability Test
Try modifying data[1] = 30
What happens?
🔹 1. Basic Info
What is the type of data?
What is the length of data?
In [275… type(data)
Out[275… tuple
In [276… len(data)
Out[276… 5
🔹 2. Indexing
What is data[0]?
What is data[-1]?
What is the output of data[4][0]?
In [277… data[0]
Out[277… 'John'
In [278… data[-1]
Out[278… ('Python', 'Java')
In [279… data[4][0]
Out[279… 'Python'
🔹 3. Slicing
Slice first 3 elements of data
Get all elements except the last one
In [280… data[0:3]
In [281… data[0:len(data)-1]
🔹 4. Immutability Test
Try modifying data[1] = 30
What happens?
--------------------------------------------------------------------------
-
TypeError Traceback (most recent call las
t)
Cell In[282], line 1
----> 1 data[0]=30
In [283… data[4][0]
Out[283… 'Python'
--------------------------------------------------------------------------
-
AttributeError Traceback (most recent call las
t)
Cell In[284], line 1
----> 1 data[4].append('new skill')
In [285… single=('John')
type(single)
Out[285… str
In [286… single=('John',)
type(single)
Out[286… tuple
In [ ]:
Loops
for loop
A for loop in Python is a control flow statement used to iterate over a sequence
(such as a list, tuple, string, or dictionary) or other iterable objects.
It allows you to execute a block of code for each item in the sequence.
In [288… l=[30,40,50,60,70]
for i in l:
print(i,end=" ")
30 40 50 60 70
I n n o m a t i c s
K a s i R e d d y
K,a,s,i, ,R,e,d,d,y,
In [293… len("")
Out[293… 0
Out[294… 1
apple
mango
banana
water melon
pine apple
kiwi
In [299… t_sort=[100,-0.01,-12,99,101]
t_sort
200
99.99
88
199
201
In [303… marks=[56,87,23,90,34,48]
grades=[]
for m in marks :
if m>=75 and m<=100:
grades.append('A')
elif 65<= m <=75:
grades.append('B')
elif 50<= m <=65:
grades.append('C')
elif 35<= m <=50:
grades.append('D')
elif 0<= m <=35:
grades.append('Failed')
else:
grades.append("Invalid input")
print(f'm : {m},grades : {grades}')
m : 56,grades : ['C']
m : 87,grades : ['C', 'A']
m : 23,grades : ['C', 'A', 'Failed']
m : 90,grades : ['C', 'A', 'Failed', 'A']
m : 34,grades : ['C', 'A', 'Failed', 'A', 'Failed']
m : 48,grades : ['C', 'A', 'Failed', 'A', 'Failed', 'D']
In [304… m=[30,11,66,73,43,55]
list=[]
for n in m :
if n%2==0:
list.append("Even")
else :
list.append("Odd")
print(f'n : {n},List={list}')
n : 30,List=['Even']
n : 11,List=['Even', 'Odd']
n : 66,List=['Even', 'Odd', 'Even']
n : 73,List=['Even', 'Odd', 'Even', 'Odd']
n : 43,List=['Even', 'Odd', 'Even', 'Odd', 'Odd']
n : 55,List=['Even', 'Odd', 'Even', 'Odd', 'Odd', 'Odd']
In [306… m=[30,11,66,73,43,55]
list=[]
for n in m :
if n%2==0:
list.append("Even")
else :
list.append("Odd")
print(f'{m},List={list}')
[30, 11, 66, 73, 43, 55],List=['Even', 'Odd', 'Even', 'Odd', 'Odd', 'Odd']
3.create and place them into two seperate list even num to even list and
odd num to odd list
In [307… m=[30,11,66,73,43,55]
Even=[]
Odd=[]
for n in m :
if n%2==0:
Even.append(n)
else :
Odd.append(n)
print(f'n : {n},Even = {Even},Odd={Odd}')
n : 30,Even = [30],Odd=[]
n : 11,Even = [30],Odd=[11]
n : 66,Even = [30, 66],Odd=[11]
n : 73,Even = [30, 66],Odd=[11, 73]
n : 43,Even = [30, 66],Odd=[11, 73, 43]
n : 55,Even = [30, 66],Odd=[11, 73, 43, 55]
In [308… m=[30,11,66,73,43,55]
Even=[]
Odd=[]
for n in m :
if n%2==0:
Even.append(n)
else :
Odd.append(n)
print(f'Even = {Even},Odd={Odd}')
In [309… marks=[56,87,23,90,34,48]
passed=[]
failed=[]
for m in marks:
if m >= 35:
passed.append(m)
else :
failed.append(m)
print(f'm : {m}, Passed : {passed},Failed : {failed}')
In [310… marks=[56,87,23,90,34,48]
passed=[]
failed=[]
for m in marks:
if m >= 35:
passed.append(m)
else :
failed.append(m)
print(f'Passed : {passed},Failed : {failed}')
In [312… squares=[ ]
for i in range(1,11):
squares.append(i**2)
print(f'Num = {i},Square of num = {squares}')
squares_num=[ ]
for i in range(1,11):
squares_num.append(i**2)
print(i,squares_num)
Num = 1,Square of num = [1]
Num = 2,Square of num = [1, 4]
Num = 3,Square of num = [1, 4, 9]
Num = 4,Square of num = [1, 4, 9, 16]
Num = 5,Square of num = [1, 4, 9, 16, 25]
Num = 6,Square of num = [1, 4, 9, 16, 25, 36]
Num = 7,Square of num = [1, 4, 9, 16, 25, 36, 49]
Num = 8,Square of num = [1, 4, 9, 16, 25, 36, 49, 64]
Num = 9,Square of num = [1, 4, 9, 16, 25, 36, 49, 64, 81]
Num = 10,Square of num = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
1 [1]
2 [1, 4]
3 [1, 4, 9]
4 [1, 4, 9, 16]
5 [1, 4, 9, 16, 25]
6 [1, 4, 9, 16, 25, 36]
7 [1, 4, 9, 16, 25, 36, 49]
8 [1, 4, 9, 16, 25, 36, 49, 64]
9 [1, 4, 9, 16, 25, 36, 49, 64, 81]
10 [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
In [313… nums=[39,59,24,55,42,76,1]
squares=[ ]
cubes=[ ]
for i in nums:
if i%2==0:
squares.append(i**2)
print(f'num = {i},squares={squares}')
else:
cubes.append(i**3)
print(f'num = {i},cubes={cubes}')
num = 39,cubes=[59319]
num = 59,cubes=[59319, 205379]
num = 24,squares=[576]
num = 55,cubes=[59319, 205379, 166375]
num = 42,squares=[576, 1764]
num = 76,squares=[576, 1764, 5776]
num = 1,cubes=[59319, 205379, 166375, 1]
In [314… nums=[39,59,24,55,42,76,1]
sq_cubes=[ ]
for i in nums:
if i%2==0:
sq_cubes.append(i**2)
else:
sq_cubes.append(i**3)
print(f'sq_cubes={sq_cubes}')
7.Take input list of words and print the reversed version of strings using
while loop
In [315… words=input("Enter list of words seperated by white space : ").split()
words
i=0
while i<len(words):
print(words[i][::-1],end=" ")
i=i+1
avaJ nohtyP
i=0,j=0
i=0,j=1
i=1,j=0
i=1,j=1
i=2,j=0
i=2,j=1
While loop
while loop is sensitive control loop
we don't known in prior for how many iterations loop will execute
In [1]: x=20
y=10 #iteration of looping variable
while(x>y): #terminating condition
print(f"x={x},y={y}")
y=y+1 #updatibg the loop variable
print("Loop completed")
x=20,y=10
x=20,y=11
x=20,y=12
x=20,y=13
x=20,y=14
x=20,y=15
x=20,y=16
x=20,y=17
x=20,y=18
x=20,y=19
Loop completed
In [2]: marks=[56,87,23,90,34,48]
grades=[]
i=0 #1.initialization of loop variable
while i<len(marks): #2.erminating condition
if 75<= marks[i] <=100:
grades.append("A")
elif 65<= marks[i] <=75:
grades.append('B')
elif 50<= marks[i] <=65:
grades.append('C')
elif 35<= marks[i] <=50:
grades.append('D')
elif 0<= marks[i] <=35:
grades.append('Failed')
else:
grades.append("Invalid input")
print(f'i:{i},marks[{i}] : {marks[i]},grades : {grades}')
i=i+1 #3.Updating loop variable
In [3]: m=[30,11,66,73,43,55]
i=0 #1.initialization of loop variable
even=[]
odd=[]
while i<len(m): #2.erminating condition
if m[i]%2==0:
even.append(m[i])
else:
odd.append(m[i])
print(f"m[{i}]={m[i]},Even={even},Odd={odd}")
i=i+1 #3.Updating loop variable
m[0]=30,Even=[30],Odd=[]
m[1]=11,Even=[30],Odd=[11]
m[2]=66,Even=[30, 66],Odd=[11]
m[3]=73,Even=[30, 66],Odd=[11, 73]
m[4]=43,Even=[30, 66],Odd=[11, 73, 43]
m[5]=55,Even=[30, 66],Odd=[11, 73, 43, 55]
In [5]: fruits=["Apple","Banana","Mango","Avacado","Orange"]
i=0
vowel=[]
consonants=[]
while i<len(fruits):
if fruits[i][0].lower() in 'aeiou':
vowel.append(fruits[i])
else:
consonants.append(fruits[i])
print(f"fruits[{i}]={fruits[i]},Vowels={vowel},Consonants={consonants
i=i+1
fruits[0]=Apple,Vowels=['Apple'],Consonants=[]
fruits[1]=Banana,Vowels=['Apple'],Consonants=['Banana']
fruits[2]=Mango,Vowels=['Apple'],Consonants=['Banana', 'Mango']
fruits[3]=Avacado,Vowels=['Apple', 'Avacado'],Consonants=['Banana', 'Mang
o']
fruits[4]=Orange,Vowels=['Apple', 'Avacado', 'Orange'],Consonants=['Banan
a', 'Mango']
In [6]: string=["Mom","dad","License","Civic","Silence","Malayalam"]
i=0
p=[]
n_p=[]
while i<len(string):
if string[i].lower()==string[i][::-1].lower():
p.append(string[i])
else:
n_p.append(string[i])
print(f'Palindrome={p},not_palindrome={n_p}')
i+=1
Palindrome=['Mom'],not_palindrome=[]
Palindrome=['Mom', 'dad'],not_palindrome=[]
Palindrome=['Mom', 'dad'],not_palindrome=['License']
Palindrome=['Mom', 'dad', 'Civic'],not_palindrome=['License']
Palindrome=['Mom', 'dad', 'Civic'],not_palindrome=['License', 'Silence']
Palindrome=['Mom', 'dad', 'Civic', 'Malayalam'],not_palindrome=['License',
'Silence']
5.Take input list of words and print the reversed version of strings using
while loop
dabaredyH,sbaL,hcraeseR,scitamonnI
6.Execute below problems using both for loop as well as while loop
given a list of numbers find product of all numbers in the list
given list of numbers find the product of even numbers and odd number separately
find a factorial of a given number
1
2
6
24
120
2
6
24
120
1 1 1
2 2 1
3 2 3
4 8 3
5 8 15
6 48 15
1 1 1
2 2 1
3 2 3
4 8 3
5 8 15
6 48 15
Factorial of 1 = 1
Factorial of 2 = 2
Factorial of 3 = 6
Factorial of 4 = 24
Factorial of 5 = 120
Factorial of 5 = 120
Factorial of 1 = 1
Factorial of 2 = 2
Factorial of 3 = 6
Factorial of 4 = 24
Factorial of 5 = 120
In [17]: n=list(range(1,6))
i=0
product=1
while i<len(n):
product=product*n[i]
print(f'Factorial of {n[i]} = {product}')
i+=1
Factorial of 1 = 1
Factorial of 2 = 2
Factorial of 3 = 6
Factorial of 4 = 24
Factorial of 5 = 120
In [18]: nums=[1,3,5,7,2,4,6,-1,22,45,74,89,-11]
for i in nums:
if i<0:
break
print(i)
print(f'Negative number {i} is encountered')
1
3
5
7
2
4
6
Negative number -1 is encountered
In [19]: nums=[1,3,5,7,2,4,6,-1,22,45,74,89,-11]
i=0
while i<len(nums):
if nums[i]<0:
break
print(nums[i])
i+=1
print(f'Negative number {nums[i]} is encountered')
1
3
5
7
2
4
6
Negative number -1 is encountered
Steps to solve
Lion
monkey
License
palindrome is encountered : Civic
In [21]: string = ['Lion','monkey','License','Civic','Silence','Malayalam']
for i in string:
if i.lower()==i.lower()[::-1]:
print(f'palindrome is encountered : {i}')
break
else:
print(i)
Lion
monkey
License
palindrome is encountered : Civic
1.For a given list of words skip words which are not palindrome using for
loop and while loop
string=
['Lion','monkey','License','Civic','Silence','Malayalam']
In [22]: string=['Lion','monkey','License','Civic','Silence','Malayalam']
for k in string :
if k.lower()!=k.lower()[::-1]:
continue
print(k)
Civic
Malayalam
In [1]: string=['Lion','monkey','License','Civic','Silence','Malayalam']
i=0
while i<len(string):
if string[i].lower()!=string[i].lower()[::-1]:
i=i+1
continue
print(string[i])
i=i+1
Civic
Malayalam
2.For a given list of words skip words which are palindrome using for
loop and while loop
string=['Lion','monkey','License','Civic','Silence','Malayalam']
In [23]: string=['Lion','monkey','License','Civic','Silence','Malayalam']
for k in string :
if k.lower()==k.lower()[::-1]:
continue
print(k)
Lion
monkey
License
Silence
In [ ]: string=['Lion','monkey','License','Civic','Silence','Malayalam']
i=0
while i<len(string):
if string[i].lower()==string[i].lower()[::-1]:
continue
print(string[i])
i=i+1
Lion
monkey
License
3.For a given numbers skip all even and print only odd
In [1]: n = [20,35,10,11,1,33,75]
for i in n:
if i%2==0:
continue
print(i)
35
11
1
33
75
In [2]: n = [20,35,10,11,1,33,75]
i=0
while i<len(n):
if n[i]%2==0:
i+=1
continue
print(n[i])
i+=1
35
11
1
33
75
4.For a given numbers skip all odd and print only even
In [3]: n = [20,35,10,11,1,33,75]
for i in n:
if i%2!=0:
continue
print(i)
20
10
In [4]: n = [20,35,10,11,1,33,75]
i=0
while i<len(n):
if n[i]%2!=0:
i+=1
continue
print(n[i])
i+=1
20
10
pass :
The pass statement in Python is a null operation, meaning it does nothing when
executed.
Its primary purpose is to act as a placeholder where a statement is syntactically
required but no action or code is intended to be implemented at that moment.
0
1
2
3
4
In [ ]:
range()-'range(start,stop,step)'
default value of start = 0
default value of stop = n-1
In [10]: range(10)
In [11]: list(range(10))
Out[11]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [12]: print(list(range(2,26)))
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 2
2, 23, 24, 25]
2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,
In [21]: l=[23,90,12,41,201,4,5,7,6,8,9,101]
for i in l:
if i%2==0:
print(i,end=" ")
90 12 4 6 8
In [22]: l=[23,90,12,41,201,4,5,7,6,8,9,101]
for i in l:
if i%2==0:
print(f"{i} is even number")
else :
print(f"{i} is odd number")
23 is odd number
90 is even number
12 is even number
41 is odd number
201 is odd number
4 is even number
5 is odd number
7 is odd number
6 is even number
8 is even number
9 is odd number
101 is odd number
Type Conversion
In [23]: data=[10,20,30,40,20,'New york',10,20]
type(data)
Out[23]: list
In [24]: data_t=tuple(data)
type(data_t)
Out[24]: tuple
In [25]: print(data_t)
10 20 30 40 20 New york 10 20
In [27]: data_t[-3:]
In [28]: data_t.count(10)
Out[28]: 2
In [29]: data_t.count(20)
Out[29]: 3
Out[30]: 4
Sets
Sets are unordered collection of mutable type
created using { }
unordered
not indexable
don't allow duplicates
Heterogeneous(allows multiple data types)
Mutable(add/delete,can't modify)
In [32]: set={-10,100,20,'apple',True}
set
In [33]: s={-10,100,'Hello',True,0.2001}
type(s)
Out[33]: set
In [34]: print(s)
{0.2001, True, 100, -10, 'Hello'}
In [35]: s={-10,100,'Hello',True,0.2001,10,100,'Hello'}
print(s,len(s))
In [36]: e={-20,0,200,True,"Cricket",1,False}
e
In [37]: e={-20,False,200,1,"Cricket",0,True}
e
--------------------------------------------------------------------------
-
TypeError Traceback (most recent call las
t)
Cell In[39], line 1
----> 1 v={20,-2,True,'new york',(-100,200),['pencil',3.04]}
2 print(v)
--------------------------------------------------------------------------
-
TypeError Traceback (most recent call las
t)
Cell In[40], line 1
----> 1 v={20,-2,True,'new york',(-100,200),{'pencil',3.04}}
2 print(v)
TypeError: unhashable type: 'set'
immutable types
'int','float','str','boolean','tuple'
mutable types
'list','set','dictionary'
In [42]: len(d)
Out[42]: 5
1.add()
In [43]: d.add(99) # adding single item to a set
print(d)
In [44]: len(d)
Out[44]: 6
2.update()
even if we pass list,set,dict(mutable_types) in update,it will treat as single items-
see in output
In [45]: d.update((34,-0.0001),[900,-1000,'mango'],{'soccer','hockey'})
print(d)
{1, 900, 10, 'hockey', 'soccer', -0.01, 20, -1000, 'mango', 34, 99, -0.000
1, 'apple'}
In [46]: print(d)
{1, 900, 10, 'hockey', 'soccer', -0.01, 20, -1000, 'mango', 34, 99, -0.000
1, 'apple'}
In [47]: len(d)
Out[47]: 13
In [48]: d.update(['soccer','pencil',56])
In [49]: print(d)
{1, 900, 10, 'hockey', 'soccer', -0.01, 20, -1000, 'pencil', 'mango', 34,
99, -0.0001, 56, 'apple'}
In [50]: len(d)
Out[50]: 15
In [52]: print(d)
{1, 900, 10, 'hockey', 'soccer', -0.01, 20, -1000, 'pencil', 'mango', 34,
99, -0.0001, -3.45, 56, 'apple'}
In [53]: len(d)
Out[53]: 16
3.sort()
In [55]: d={-0.01,-199,-150,34,21,60}
d
In [57]: print(d)
4.discard()
if the value is not there,discord will not show any error
In [58]: print(d)
Out[59]: 6
In [60]: a=d.discard(21)
print(a)
None
In [61]: print(d)
In [62]: len(d)
Out[62]: 5
In [ ]:
5.remove()
if the value is not there,then it generates error
In [65]: d.remove(60)
In [66]: print(d)
--------------------------------------------------------------------------
-
KeyError Traceback (most recent call las
t)
Cell In[67], line 1
----> 1 d.remove(125)
KeyError: 125
In [68]: print(d)
In [69]: d.pop()
Out[69]: 34
In [70]: print(d)
In [71]: d.pop()
Out[71]: -0.01
In [72]: print(d)
{-199, -150}
In [ ]:
7.clear()
In [73]: print(d)
{-199, -150}
In [74]: len(d)
Out[74]: 2
In [75]: d.clear()
In [76]: len(d)
Out[76]: 0
In [ ]:
Out[78]: dict
In [1]: s2=set() # creating emtty set
type(s2)
Out[1]: set
In [ ]:
Other operations
1.Union( )
2.Intersection( )
3.Difference( )
4.Symmetric difference
In [2]: s1={25,100,1,-1}
s2={1,125,-199,-1}
1.Union
In [3]: s1.union(s2)
In [4]: s1|s2
2.Intersection
In [5]: s1.intersection(s2)
Out[5]: {-1, 1}
In [6]: s1&s2
Out[6]: {-1, 1}
3.Difference
Here,order is very important
In [7]: s1-s2
In [8]: s1.difference(s2)
In [ ]:
4.Symmetric difference
In [10]: s1.symmetric_difference(s2)
In [11]: s1^s2
Aggregate function
In [12]: s1
In [13]: s2
In [14]: sum(s1)
Out[14]: 125
In [15]: sum(s1,start=10)
Out[15]: 135
In [16]: min(s1)
Out[16]: -1
In [17]: max(s2)
Out[17]: 125
In [18]: avg=(sum(s1)/len(s1))
In [19]: avg
Out[19]: 31.25
In [ ]:
🎓 Set Operations - Real-World Example
(Workshop Attendees)
You are managing attendees for Workshop A and Workshop B.
1. What happens when you create a set with duplicate values in attendees_A ?
2. Add "Ivan" to attendees_A . What does the set look like afterward?
6. Discard "Trent" from attendees_A (not in the set). Does this cause an
error?
Union
Intersection
Difference (only in attendees_A )
10. Clear attendees_A . What will the set contain after this?
In [21]: # What happens when you create a set with duplicate values in attendees_A
attendees_A = {"Alice", "Bob", "Charlie", "Diana", "Bob", "Eve"}
attendees_A
In [23]: # Add "Ivan" to attendees_A. What does the set look like afterward?
attendees_A.add("Ivan")
attendees_A
In [25]: # Discard "Bob" from attendees_A. What happens if "Bob" is not present?
attendees_A.discard("Bob")
attendees_A
In [26]: # Remove "Charlie" from attendees_A. How is remove() different from discar
attendees_A.remove("Charlie")
attendees_A
remove() method will throw an error if items are not there in set
In [27]: # Discard "Trent" from attendees_A (not in the set). Does this cause an er
attendees_A.discard("Trent")
attendees_A
--------------------------------------------------------------------------
-
KeyError Traceback (most recent call las
t)
Cell In[28], line 2
1 # Remove "Trent" from attendees_A. What happens?
----> 2 attendees_A.remove("Trent")
3 attendees_A
KeyError: 'Trent'
Out[30]: {'Alice',
'Charlie',
'Diana',
'Eve',
'Frank',
'Grace',
'Heidi',
'Ivan',
'Judy',
'Mallory'}
Out[31]: {'Eve'}
In [34]: # Clear attendees_A. What will the set contain after this?
attendees_A.clear()
In [35]: len(attendees_A)
Out[35]: 0
In [ ]:
Dictionaries
Dictionaries are collections of key-value pairs of mutable types
ordered
Indexable(keys are indices)
Mutable(add,modify,delete key value pair)
Keys allow only immutable types
values be of any data type
Duplicate keys are not allowed
For faster retrival of data (retrives fastly compared to list and tuple)
In [36]: d={'one':1,2:'Two','fruit':"Apple"}
d
In [37]: d['one']
Out[37]: 1
In [38]: d[2]
Out[38]: 'Two'
In [39]: d['fruit']
Out[39]: 'Apple'
In [40]: e={}
type(e)
Out[40]: dict
In [41]: s=set()
type(s)
Out[41]: set
Note: Python uses curly braces for sets and dictionaries.The syntax { }
denotes an empty dictionary.To create an empty set , use set( )
1.Creating a dictionary
In [42]: r={'Soccer':"Game",(34.02,45.001):'Banglore',2.0001:"Hello"}
Out[43]: 'Banglore'
In [44]: r={'Soccer':"Game",[34.02,45.001]:'Banglore',2.0001:"Hello"}
r #creating using list as key and throws error
--------------------------------------------------------------------------
-
TypeError Traceback (most recent call las
t)
Cell In[44], line 1
----> 1 r={'Soccer':"Game",[34.02,45.001]:'Banglore',2.0001:"Hello"}
2 r
retrieving
In [56]: marks['Deeksha']
Out[56]: 87
In [57]: marks['eeksha']
--------------------------------------------------------------------------
-
KeyError Traceback (most recent call las
t)
Cell In[57], line 1
----> 1 marks['eeksha']
KeyError: 'eeksha'
Out[58]: 60
get( )
To prevent a keyerror exception,we can use get() function an a dictionary.
Then, if a value is not found for a given key , it returns nothing(otherwise returns
that value associated with the key).
3.Getting all
1.keys( )
2.values( )
3.items( )
In [60]: marks.keys()
Alice
Ben
Charlie
Deeksha
In [62]: marks.values()
60 67 90 87
In [64]: marks.items()
Key : Alice,value = 60
Key : Ben,value = 67
Key : Charlie,value = 90
Key : Deeksha,value = 87
Alice
Ben
Charlie
Deeksha
4.Basic operations
Membership operator
1. in
2. not in
In [69]: l=[56,67,90,75]
l
In [70]: 'soccer' in l
Out[70]: False
In [71]: 67 in l
Out[71]: True
Out[72]: True
Out[74]: True
Out[75]: False
Out[76]: True
Out[77]: True
Comparision operations
1. ==
2. !=
In [78]: d1={'red':56,'orange':70}
d2={'orange':70,'red':56}
d1==d2
Out[78]: True
In [79]: d1={'red':56,'orange':70}
d2={'orange':70,'red':60}
In [80]: d1==d2
Out[80]: False
In [81]: d1!=d2
Out[81]: True
pop()
In [83]: popped_item=marks.pop("Ben")
popped_item
Out[83]: 80
In [84]: pop_item=marks.pop('david')
--------------------------------------------------------------------------
-
KeyError Traceback (most recent call las
t)
Cell In[84], line 1
----> 1 pop_item=marks.pop('david')
KeyError: 'david'
In [86]: marks
In [90]: marks
fromkeys()
In [91]: l=[56,'cricket','Lion']
l
Out[92]: {56: 'Initial value', 'cricket': 'Initial value', 'Lion': 'Initial valu
e'}
In [ ]:
zip()
In [93]: k=['Alice','Ben','Charlie','David']
v=[89,78,67,56]
In [94]: d=zip(k,v)
list(d)
In [95]: d=zip(k,v)
dict(d)
In [96]: d=zip(k,v)
tuple(d)
Out[96]: (('Alice', 89), ('Ben', 78), ('Charlie', 67), ('David', 56))
In [97]: d=zip(k,v)
set(d)
In [98]: k=['Alice','Ben','Charlie','David']
v=[89,78,67] # shortage of items
In [99]: dict(zip(k,v))
In [100… k=['Alice','Ben','Charlie']
v=[89,78,67,56] # shortage of items
In [101… dict(zip(k,v))
In [102… list(zip(k,v))
unpacking
In [103… fruits={'Apple':80,'Orange':45}
vegetables={'Tomato':30,'Onion':50}
combined={**fruits,**vegetables}
combined
Cls-Exercise
In [105… # Add a new key "subject" with value "Math" to the dictionary.
student["subjecct"]="Math"
student
Out[108… 'Srujan'
In [109… # Try accessing a non-existent key with get() and provide a default messag
student.get('city','key not exist')
Out[110… True
In [111… # Get all keys, values, and items from the dictionary.
student.keys()
In [112… student.values()
In [113… student.items()
In [114… # Loop through the dictionary and print keys and values.
for m,n in student.items():
print(f'Keys : {m},Values : {n}')
Keys : name,Values : Srujan
Keys : grade,Values : A+
Keys : subjecct,Values : Math
In [115… # Pop a key from the dictionary and store its value in a variable.
popped_item=student.pop('grade')
popped_item
Out[115… 'A+'
In [117… # Create a dictionary from two lists: keys = ['a', 'b'] and vals = [1, 2]
keys = ['a', 'b']
vals = [1, 2]
dict(zip(keys,vals))
clear()
Out[118… 3
In [119… student.clear()
In [120… len(student)
Out[120… 0
enumarete()
enumerate(iterable,start=value(default is 0))
to assign some number/index to element through for loop
actual for loop have only one 'element'
by using enumerate we get both index and element
In [121… l=[56,'lion','cricket']
for i in l:
print(i)
56
lion
cricket
0 56
1 lion
2 cricket
Index : 3,Item : 56
Index : 4,Item : lion
Index : 5,Item : cricket
Index : -3,Item : 56
Index : -2,Item : lion
Index : -1,Item : cricket
In [128… l1
In [129… l2
In [130… id(l1),id(l2)
In [131… l1.append(100)
In [132… l1
In [133… l2
Shallow copy
In [134… from copy import copy
e=[20,True,78,90,[45,-1,-10]]
In [136… e
In [137… w
In [138… id(e),id(w)
In [139… id(e[-1]),id(w[-1])
Both lists have different address,changes made to one list will not affect
the other
In [140… e.append(-199)
In [141… e
In [142… w
In [143… w[-1]
In [144… w[-1].append("Lion")
In [145… w
In [146… e
Out[146… [20, True, 78, 90, [45, -1, -10, 'Lion'], -199]
In [147… id(e),id(w)
Try adding to any list other than nested list and see difference
In [149… e.insert(1,-1000)
In [150… e
Out[150… [20, -1000, True, 78, 90, [45, -1, -10, 'Lion'], -199]
In [151… w
In [ ]:
deepcopy()
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
In [ ]:
Operator Precedence
Parenthesies ()
Exponentiation **
Mulitplication *
Division /
Floor Division //
Modulus Division %
Addition +
Subtraction -
Comparison operators <, <=,>,>=,==,!=
Logical NOT not
Logical AND and
Logical OR or
Assignment opeators =,+=,-=,=,/=,%=,*=,//=
Out[152… False
In [153… 2+3*4
#2+12
#14
Out[153… 14
In [154… (2+3)*4
#5*4
#20
Out[154… 20
In [155… a=5
b=2
c=6
result=(a-b)*c+2
result
#(3)*c+2
#3*6+2
#18+2
#20
Out[155… 20
In [156… a%b+a//b-a*b
# 5%2 +5//2 - 5*2
# 5%2 + 5//2 - 10
# 5%2 + 2 - 10
# 1 + 2 - 10
# 3 - 10
# -7
Out[156… -7
Out[157… -136.16666666666666
In [158… a=5
b=10
c=15
res=(a+b==c)and(b/a>1)or not (c-a<b)
res
Out[158… True
Strings
String is a sequence of characters enclosed within quotes and are immutable type
Quotes : (' '," "(mostly used for strings)) , ((''' ''',""" """)(used for multiline and
documentation))
In [160… x
String methods :
Concatenation
In [165… i="Hello"
c="Good Morning"
i+" "+c
In [166… i+c
In [167… i*5
Out[167… 'HelloHelloHelloHelloHello'
In [168… (i+c)*5
In [169… i
Out[169… 'Hello'
In [170… c
--------------------------------------------------------------------------
-
TypeError Traceback (most recent call las
t)
Cell In[173], line 1
----> 1 i[4]="P"
In [175… s
Out[175… 'Innomatics'
In [176… s[2]
Out[176… 'n'
In [177… s[-1]
Out[177… 's'
In [178… s[0:]
Out[178… 'Innomatics'
In [179… s[0:6]
Out[179… 'Innoma'
In [180… s[0::-1]
Out[180… 'I'
In [181… s[2:9:2]
Out[181… 'nmtc'
In [182… s[::-1]
Out[182… 'scitamonnI'
Out[185… 'PYGRAM'
Out[186… 'MR.PY'
Membership in string :
In [187… l="PYTHON PROGRAM"
l
In [188… "P" in l
Out[188… True
In [189… "p" in l
Out[189… False
In [190… "PRO" in l
Out[190… True
In [191… "PY" in l
Out[191… True
In [192… "YP" in l
Out[192… False
In [ ]:
malayalaM is palindrome
In [198… s="malayalaM"
In [199… s,s[::-1]
In [200… s.lower(),s[::-1].lower()
In [201… s.upper()
Out[201… 'MALAYALAM'
len() :
Returns no of characters
Out[203… 14
Built in Functions :
In [204… a='PyThoN is a PRograming And caSe SensItive LanguaGE'
1.lower()
To convert the string into lower case letters
In [205… a.lower()
2.upper()
To convert the string into upper case letters
In [207… a.upper()
3.capitalize():
To make the starting string in capital
In [208… a.capitalize()
4.title() :
if we want to make the first letter of each word in the string in capital
In [209… a.title()
5.count() :
to count the no of occurences of a sub-string in the main string
In [210… a
Out[212… 1
In [213… a.count("A")
Out[213… 1
In [214… a.count("P")
Out[214… 2
In [215… a.count("a")
Out[215… 5
6.startswith()
to check whether a string starts with a given sequence
In [217… a.startswith('P')
Out[217… True
In [218… a.startswith('Py')
Out[218… True
In [219… a.startswith('PyThoN')
Out[219… True
In [220… a.startswith('py')
Out[220… False
7.endswith()
to check whether a string starts with a given sequence
In [224… a.endswith("E")
Out[224… True
In [225… a.endswith("aGE")
Out[225… True
In [226… a.endswith("agE")
Out[226… False
Out[227… True
8.find() :
find() returns the index position of the starting character of the sub-string
returns -1 if not found
In [229… k.find('s')
Out[229… 9
In [230… k.find("Research")
Out[230… 11
In [231… k.find("research")
Out[231… -1
In [232… k.find("matics")
Out[232… 4
Out[234… 10
In [235… k.find("")
Out[235… 0
In [236… k.find("I")
Out[236… 0
In [ ]:
9.index() :
this index()method works similar to find() method
the difference is it will raise error if not found
In [238… k.index("Research")
Out[238… 11
In [239… k.index("Res")
Out[239… 11
In [240… k.index("arch")
Out[240… 15
In [241… k.index("s")
Out[241… 9
In [242… k.index("z")
--------------------------------------------------------------------------
-
ValueError Traceback (most recent call las
t)
Cell In[242], line 1
----> 1 k.index("z")
In [ ]:
10.isdigit() :
to check if the string is numeric
In [244… s="256k"
s
Out[244… '256k'
In [245… s.isdigit()
Out[245… False
In [246… d='256'
d
Out[246… '256'
In [247… d.isdigit()
Out[247… True
In [ ]:
11.replace() :
if we want to replace the part of the string with replacement
In [249… w.replace("Python","Java")
In [ ]:
12.strip() :
to remove any leading and trailing white spaces and new line characters
In [ ]:
13.split() :
splitting a string into sub-strings based on default delimter(space)
In [265… k.split()
In [266… k.split("a")
In [272… k.split('n',-1)
In [277… k.split('a',1)
Out[277… ['Innom', 'tics Research Labs']
In [278… k.split('a',2)
PQS:
From the string " Data Science ", apply strip() and then convert it to
uppercase.
In [282… "[email protected]".split('@')[-1]
Out[282… 'innomatics.in'
In [ ]:
✅ List Questions
Q1. Given my_list = [1, 2, 3, 4, 5, 2, 3] ,
Remove duplicates and sort the list in descending order.
✅ Tuple Questions
Q3. Given data = (10, 20, 30, 40, 50) ,
Check if 30 is present in the tuple and count how many times it appears.
✅ Set Questions
Q5. Given set1 = {1, 2, 3, 4} and set2 = {3, 4, 5, 6} ,
Find union, intersection, and difference of both sets.
✅ Dictionary Questions
Q7. Given student = {'name': 'Alice', 'age': 22, 'course':
'Math'} ,
Update age to 23 and add a new key 'grade' with value 'A' .
✅ String Questions
Q9. Given sentence = " Python is FUN " ,
Remove leading/trailing spaces and convert the string to lowercase.
List
In [285… my_list
Out[285… [1, 2, 3, 4, 5, 2, 3]
In [286… s=set(my_list)
s
Out[286… {1, 2, 3, 4, 5}
In [288… fruits[::-1]
Out[289… True
In [290… data.count(30)
Out[290… 1
In [292… d_list[1]=26
d_list
In [293… d_tuple=tuple(d_list)
d_tuple
Set
Out[295… {1, 2, 3, 4, 5, 6}
Out[296… {3, 4}
Out[297… {1, 2}
Out[298… {1, 2, 5, 6}
In [299… # Given nums = {10, 20, 30}
# Add 40 to the set and remove 20 using set methods.
nums = {10, 20, 30}
nums
In [300… nums.add(40)
nums
In [301… nums.remove(20)
nums
In [303… student['age']=23
student['grade']='A'
student
Out[304… 2
In [305… data
Out[306… True
In [307… list(data.keys())
strings
In [ ]:
list Comprehension
In [ ]:
In [310… nums=[1,2,3,4,5,6,7,8,9]
squares=[]
for n in nums:
squares.append(n**2)
print(n,squares)
1 [1]
2 [1, 4]
3 [1, 4, 9]
4 [1, 4, 9, 16]
5 [1, 4, 9, 16, 25]
6 [1, 4, 9, 16, 25, 36]
7 [1, 4, 9, 16, 25, 36, 49]
8 [1, 4, 9, 16, 25, 36, 49, 64]
9 [1, 4, 9, 16, 25, 36, 49, 64, 81]
In [311… nums=[1,2,3,4,5,6,7,8,9]
sq=[k**2 for k in nums]
sq
In [315… nums=[1,2,3,4,5,6,7,8,9]
sq=[k**2 for k in nums]
print(f'{nums[k]}:{sq}')
--------------------------------------------------------------------------
-
TypeError Traceback (most recent call las
t)
Cell In[315], line 3
1 nums=[1,2,3,4,5,6,7,8,9]
2 sq=[k**2 for k in nums]
----> 3 print(f'{nums[k]}:{sq}')
1 : 1
2 : 4
3 : 9
4 : 16
5 : 25
6 : 36
7 : 49
8 : 64
9 : 81
In [318… words=['sports','vegetables','fruits','hotels']
rev_words=[i[::-1] for i in words]
rev_words
In [319… words=['sports','vegetables','fruits','hotels']
rev_words=words[::-1]
rev_words
In [321… c=[39,41,32,29,36]
F = [ round((9/5)*i+32,2) for i in c]
F
In [323… sqrt(10)
Out[323… 3.1622776601683795
In [324… n=[1,4,9,12,16,20,36,40]
from math import sqrt
sq=[ sqrt(i) for i in n ]
sq
Out[324… [1.0,
2.0,
3.0,
3.4641016151377544,
4.0,
4.47213595499958,
6.0,
6.324555320336759]
7.Given list of fruits each in lower case,craete a list where items are
upper case of the same word
8.For a given list print their length in a list where length is atleast 4
Out[330… ['apple']
In [335… n = [1,3,4,5,7,9,12,15,25]
sq = [ s**2 if s%2==0 else round(sqrt(s),2) for s in n]
sq
Out[335… [1.0, 1.73, 16, 2.24, 2.65, 3.0, 144, 3.87, 5.0]
In [339… n = [1,3,4,5,7,9,12,15,25]
sq = [for s in n s**2 if s%2==0 else round(sqrt(s),2)]
sq # raises error
12.inline if-else
In [341… m = 77
"Passed" if m>35 else "Failed" # inline if-else statements
Out[341… 'Passed'
--------------------------------------------------------------------------
-
TypeError Traceback (most recent call las
t)
Cell In[343], line 2
1 marks = [55,70,23,36,95,11,28,77,92]
----> 2 list = [ "Passed" if marks>35 else "Failed" for s in marks ]
3 list
Dictionary comprehension
1. Given a list of numbers,key is number and value is corresponding
square of the same number
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 11: 121, 13: 169, 100: 10000, 14: 196, 1
7: 289}
3. Filter palindromes from a given list,key is the word and value is it's
uppercse
5. Given the list of words , key is the word convert to lower case if
palindrome and others to upper case
6. Given a list of prices,for prices greater than 500 add 18% GST and for
prices less than 500 add 5% GST.Output should contain only
(price+GST)
In [ ]:
Functions( ) :
Functions in Python are blocks of organized, reusable code designed to perform a
specific task. They enhance code modularity, readability, and reusability.
User-defined Functions:
These are functions created by developers to perform specific tasks tailored to
their needs.
Definition:
User-defined functions are defined using the def keyword, followed by the function
name, parentheses (which can contain parameters), and a colon. The function
body is indented.
Good Morning
Good morning
Hello kasi
Hellokasi
1.Create a function that two numbers as input and print their sum
In [359… help(total)
total(a, b)
Takes two parameters a,b
a--->int
b--->int
Calculates a+b
In [360… total(10,-100)
-90
In [361… m=total(4,5)
In [362… print(m)
None
Observe the difference when used return,it prints the value else None
Note :
1. Technically, every function in Python returns a value whether you use return or not.
If a function does not return a value, by default, it returns a special value None.
For this reason, a function that does not will return a value is also called a None
function. The None value can be assigned to a variable to indicate that the
variable does not reference any object. For example, if you see the program, you
see the output is None, because the sum function does not have a return
statement. By default, it returns None.
2. A return statement is not needed for a None function, but it can be used for
terminating the function and returning control to the function's caller. The syntax is
simply return (or) return None This is rarely used, but it is sometimes useful for
circumventing the normal flow of control in a function that does not return any
value. For example, the following code has a return statement to terminate the
function when the score is invalid.
2.Create a function that takes a string and print it's reversed version
NOHTYP
In [365… r_string("INNOMATICS")
SCITAMONNI
--------------------------------------------------------------------------
-
TypeError Traceback (most recent call las
t)
Cell In[367], line 1
----> 1 exp('Hi',3,'How are you?')
In [ ]:
3.Create a function that takes strings and returns it's reversed version
noiL
nohtyP
In [373… rev_str("Python")
Out[373… 'nohtyP'
96.8
104.0
21.0
In [379… sum_n = sum(10)
print(sum_n)
55.0
6. Create a function that takes radius and returns the area of the
circle(Use pi from math library)
2
Area = πr
Out[381… 78.54
In [383… sum_digits(12345)
Out[383… 15
In [385… len(n_words)
Out[385… 6
In [386… len(text)
Out[386… 30
(3, 9)
(5, 23)
5 23
In [393… exp(10,20,30,40,5)
<class 'tuple'>
args : (40, 5)
Out[393… (-870, 65)
In [394… exp(34,10,20,48,21,19,-100,34,50,30,67)
<class 'tuple'>
args : (48, 21, 19, -100, 34, 50, 30, 67)
Out[394… (-356, 1455)
In [396… exp_kw(30,12,10,30,45,10,29,23,56,r=45,f=59,n=100,x=300)
Out[397… 2550
1. Zip function :
zip( ) is an aggregator,meaning it aggregates two or more iterable or
sequences.The individual items of an iterables are combined to form tuples.The
zip() function stops whenever the shortest of the individual variables is exhausted
In [1]: k = [45,30,20]
v = ['Cricket','Lion','Pen']
t=zip(k,v)
In [2]: list(t)
In [3]: t=zip(k,v)
tuple(t)
In [4]: t=zip(k,v)
dict(t)
2.Lambda function :
Lambda function is used to create an anonymous function (i.e an inline function
without a name) used for a short calculation
Rules to create lambda function :
lambda can take any number of parameters(arguments)
Instead of def,we use lambda.No paranthesis required
colon seperates parameters and expression
no need of print/return keyword
parameters/arguments is optional
In [6]: squares(13)
Out[6]: 169
Out[7]: 25
In [8]: sq(2)
Out[8]: 4
In [9]: sq(13)
Out[9]: 169
Out[10]: 'Hello'
In [12]: greeting()
Out[12]: 'Hello'
9. Celcius to farenheit
In [14]: F(36)
Out[14]: 96.8
In [16]: add(4,5)
Out[16]: 9
10. Create a lambda function is palindrome that takes a string and
returns True if the string is palindrome , otherwise false
In [18]: is_palindrome("mam")
Out[18]: True
In [19]: is_palindrome("Student")
Out[19]: False
In [21]: is_palindrome("Student")
Out[21]: False
In [22]: is_palindrome("12321")
Out[22]: True
--------------------------------------------------------------------------
-
AttributeError Traceback (most recent call las
t)
Cell In[23], line 1
----> 1 is_palindrome(12321)
3. Map function :
map( ) function takes a function and a sequence as it's arguments. It returns
iterators (some kind of sequence over which you can iterate one by one) on which
the function is applied
In [25]: square_root
In [29]: r_strings
In [30]: list(r_strings)
Out[31]: [6, 2, 4, 2, 5]
Out[32]: [6, 2, 4, 2, 5]
4. Filter function :
In [33]: strings = ['mom','student','civic','telugu','Malayalam']
palindrome = filter( lambda x : x.lower()==x.lower()[::-1],strings)
list(palindrome)
13. Write a filter function which retains strings with length greater than 5
In [35]: li = [34,23,56,11,18]
even = filter(lambda x : x%2==0,li)
sq = map(lambda x : x**2,even)
list(sq)
In [36]: print(list(sq))
[]
15.In a list of words convert words starting with 's' to upper case
5.Reduce function :
reduce () function from funcctools module is used to apply a function repeatedly to
accumulate a single data value. A summation is a good example of this
process.The first value is added to second value then that sum is added to third
value,and so on,until the sum of all value is produced.
In [41]: from functools import reduce
In [42]: a = [34,23,56,45,11,18]
total = reduce(lambda x,y : x+y , a)
total
Out[42]: 187
--------------------------------------------------------------------------
-
TypeError Traceback (most recent call las
t)
Cell In[43], line 3
1 a = [34,23,56,45,11,18]
2 total = map(lambda x,y : x+y, a)
----> 3 list(total)
In [44]: a = [34,23,56,45,11,18]
b = [34,23,56,45,11,18,20]
total = map(lambda x,y : x+y, a,b)
list(total)
maximum
In [45]: a = [34,23,56,45,11,18]
max = reduce(lambda x,y : x if x>y else y,a)
max
Out[45]: 56
In [46]: a = [34,23,56,45,11,18]
product = reduce(lambda x,y : x*y,a)
product
Out[46]: 390186720
18.Calculate factorial of 10
Out[47]: 3628800
In [48]: product=1
for i in range (1,11):
product*=i
product
Out[48]: 3628800
Out[50]: 3628800
In [51]: li =[34,23,56,45,11,18]
even = filter(lambda x : x%2==0,li)
sq = map(lambda x : x**2,even)
sum = reduce(lambda x,y:x+y,sq)
sum
Out[51]: 4616
In [52]: li =[34,23,56,45,11,18]
sq_even = list(map(lambda x : x**2,filter(lambda x:x%2==0,li)))
sq_even
In [53]: sum(sq_even)
--------------------------------------------------------------------------
-
TypeError Traceback (most recent call las
t)
Cell In[53], line 1
----> 1 sum(sq_even)
6.Recursive function :
Recursive means calling a function in terms of itself.All Recursive alogorithms have
theses characteristics :
1.A recursive alogorithm must calll itself,recursively
2.A recursive alogorithm must have a base case.A base can occurs when the
problem after repeated calls to the recursive function,becomes so small that it
can be solved directly.
3.A recursive algorithm after each call to the recursive function,must move
towards the base case.So, in a well-designed recursive-algorithm,after each
iteration,the problem must become smaller.
In [55]: factorial(5)
Out[55]: 120
In python,you can also global variables.They are created outside all functions and
are accessible to all functions in their scope
In [57]: x=20
def func():
global x
x+=11
print(f"Value of x inside func :{x}")
# x+=4 #24
func()
def fn1():
global x
x+=4
print(f"Value of x inside func fn1 : {x}")
fn1()
print(f"Value of x outside func : {x}")
In [ ]:
In [ ]:
In [62]: li=['cat','elephant','tiger','lion']
length = []
for i in li:
length.append(len(i))
print(length)
[3, 8, 5, 4]
Out[63]: 'elephant'
Out[64]: 3
In [2]: is_armstrong(153)
Out[2]: True
In [3]: is_armstrong(270)
Out[3]: False
Out[6]: 9474
In [8]: ceil(31.01)
Out[8]: 32
In [9]: ceil(31.9999)
Out[9]: 32
In [10]: floor(31.999)
Out[10]: 31
In [11]: floor(31.00000001)
Out[11]: 31
In [12]: def is_prime(n):
for i in range(2,ceil(n**0.5)+1):
if n%i==0:
print(f'{n} is divisible by {i}')
return False
else :
return True
In [13]: is_prime(43)
Out[13]: True
In [14]: is_prime(25)
25 is divisible by 5
Out[14]: False
In [16]: is_prime(4) #it's returning true even if it's not prime,because the input
Out[16]: True
In [17]: is_prime(3)
Out[17]: True
In [18]: is_prime(8)
8 is divisible by 2
Out[18]: False
2 is divisible by 2
4 is divisible by 2
6 is divisible by 2
8 is divisible by 2
9 is divisible by 3
10 is divisible by 2
12 is divisible by 2
14 is divisible by 2
15 is divisible by 3
16 is divisible by 2
18 is divisible by 2
20 is divisible by 2
21 is divisible by 3
22 is divisible by 2
24 is divisible by 2
25 is divisible by 5
26 is divisible by 2
27 is divisible by 3
28 is divisible by 2
30 is divisible by 2
32 is divisible by 2
33 is divisible by 3
34 is divisible by 2
35 is divisible by 5
36 is divisible by 2
38 is divisible by 2
39 is divisible by 3
40 is divisible by 2
42 is divisible by 2
44 is divisible by 2
45 is divisible by 3
46 is divisible by 2
48 is divisible by 2
49 is divisible by 7
50 is divisible by 2
51 is divisible by 3
52 is divisible by 2
54 is divisible by 2
55 is divisible by 5
56 is divisible by 2
57 is divisible by 3
58 is divisible by 2
60 is divisible by 2
62 is divisible by 2
63 is divisible by 3
64 is divisible by 2
65 is divisible by 5
66 is divisible by 2
68 is divisible by 2
69 is divisible by 3
70 is divisible by 2
72 is divisible by 2
74 is divisible by 2
75 is divisible by 3
76 is divisible by 2
77 is divisible by 7
78 is divisible by 2
80 is divisible by 2
81 is divisible by 3
82 is divisible by 2
84 is divisible by 2
85 is divisible by 5
86 is divisible by 2
87 is divisible by 3
88 is divisible by 2
90 is divisible by 2
91 is divisible by 7
92 is divisible by 2
93 is divisible by 3
94 is divisible by 2
95 is divisible by 5
96 is divisible by 2
98 is divisible by 2
99 is divisible by 3
100 is divisible by 2
102 is divisible by 2
104 is divisible by 2
105 is divisible by 3
106 is divisible by 2
108 is divisible by 2
110 is divisible by 2
111 is divisible by 3
112 is divisible by 2
114 is divisible by 2
115 is divisible by 5
116 is divisible by 2
117 is divisible by 3
118 is divisible by 2
119 is divisible by 7
120 is divisible by 2
121 is divisible by 11
122 is divisible by 2
123 is divisible by 3
124 is divisible by 2
125 is divisible by 5
126 is divisible by 2
128 is divisible by 2
129 is divisible by 3
130 is divisible by 2
132 is divisible by 2
133 is divisible by 7
134 is divisible by 2
135 is divisible by 3
136 is divisible by 2
138 is divisible by 2
140 is divisible by 2
141 is divisible by 3
142 is divisible by 2
143 is divisible by 11
144 is divisible by 2
145 is divisible by 5
146 is divisible by 2
147 is divisible by 3
148 is divisible by 2
150 is divisible by 2
152 is divisible by 2
153 is divisible by 3
154 is divisible by 2
155 is divisible by 5
156 is divisible by 2
158 is divisible by 2
159 is divisible by 3
160 is divisible by 2
161 is divisible by 7
162 is divisible by 2
164 is divisible by 2
165 is divisible by 3
166 is divisible by 2
168 is divisible by 2
169 is divisible by 13
170 is divisible by 2
171 is divisible by 3
172 is divisible by 2
174 is divisible by 2
175 is divisible by 5
176 is divisible by 2
177 is divisible by 3
178 is divisible by 2
180 is divisible by 2
182 is divisible by 2
183 is divisible by 3
184 is divisible by 2
185 is divisible by 5
186 is divisible by 2
187 is divisible by 11
188 is divisible by 2
189 is divisible by 3
190 is divisible by 2
192 is divisible by 2
194 is divisible by 2
195 is divisible by 3
196 is divisible by 2
198 is divisible by 2
200 is divisible by 2
201 is divisible by 3
202 is divisible by 2
203 is divisible by 7
204 is divisible by 2
205 is divisible by 5
206 is divisible by 2
207 is divisible by 3
208 is divisible by 2
209 is divisible by 11
210 is divisible by 2
212 is divisible by 2
213 is divisible by 3
214 is divisible by 2
215 is divisible by 5
216 is divisible by 2
217 is divisible by 7
218 is divisible by 2
219 is divisible by 3
220 is divisible by 2
221 is divisible by 13
222 is divisible by 2
224 is divisible by 2
225 is divisible by 3
226 is divisible by 2
228 is divisible by 2
230 is divisible by 2
231 is divisible by 3
232 is divisible by 2
234 is divisible by 2
235 is divisible by 5
236 is divisible by 2
237 is divisible by 3
238 is divisible by 2
240 is divisible by 2
242 is divisible by 2
243 is divisible by 3
244 is divisible by 2
245 is divisible by 5
246 is divisible by 2
247 is divisible by 13
248 is divisible by 2
249 is divisible by 3
250 is divisible by 2
252 is divisible by 2
253 is divisible by 11
254 is divisible by 2
255 is divisible by 3
256 is divisible by 2
258 is divisible by 2
259 is divisible by 7
260 is divisible by 2
261 is divisible by 3
262 is divisible by 2
264 is divisible by 2
265 is divisible by 5
266 is divisible by 2
267 is divisible by 3
268 is divisible by 2
270 is divisible by 2
272 is divisible by 2
273 is divisible by 3
274 is divisible by 2
275 is divisible by 5
276 is divisible by 2
278 is divisible by 2
279 is divisible by 3
280 is divisible by 2
282 is divisible by 2
284 is divisible by 2
285 is divisible by 3
286 is divisible by 2
287 is divisible by 7
288 is divisible by 2
289 is divisible by 17
290 is divisible by 2
291 is divisible by 3
292 is divisible by 2
294 is divisible by 2
295 is divisible by 5
296 is divisible by 2
297 is divisible by 3
298 is divisible by 2
299 is divisible by 13
300 is divisible by 2
301 is divisible by 7
302 is divisible by 2
303 is divisible by 3
304 is divisible by 2
305 is divisible by 5
306 is divisible by 2
308 is divisible by 2
309 is divisible by 3
310 is divisible by 2
312 is divisible by 2
314 is divisible by 2
315 is divisible by 3
316 is divisible by 2
318 is divisible by 2
319 is divisible by 11
320 is divisible by 2
321 is divisible by 3
322 is divisible by 2
323 is divisible by 17
324 is divisible by 2
325 is divisible by 5
326 is divisible by 2
327 is divisible by 3
328 is divisible by 2
329 is divisible by 7
330 is divisible by 2
332 is divisible by 2
333 is divisible by 3
334 is divisible by 2
335 is divisible by 5
336 is divisible by 2
338 is divisible by 2
339 is divisible by 3
340 is divisible by 2
341 is divisible by 11
342 is divisible by 2
343 is divisible by 7
344 is divisible by 2
345 is divisible by 3
346 is divisible by 2
348 is divisible by 2
350 is divisible by 2
351 is divisible by 3
352 is divisible by 2
354 is divisible by 2
355 is divisible by 5
356 is divisible by 2
357 is divisible by 3
358 is divisible by 2
360 is divisible by 2
361 is divisible by 19
362 is divisible by 2
363 is divisible by 3
364 is divisible by 2
365 is divisible by 5
366 is divisible by 2
368 is divisible by 2
369 is divisible by 3
370 is divisible by 2
371 is divisible by 7
372 is divisible by 2
374 is divisible by 2
375 is divisible by 3
376 is divisible by 2
377 is divisible by 13
378 is divisible by 2
380 is divisible by 2
381 is divisible by 3
382 is divisible by 2
384 is divisible by 2
385 is divisible by 5
386 is divisible by 2
387 is divisible by 3
388 is divisible by 2
390 is divisible by 2
391 is divisible by 17
392 is divisible by 2
393 is divisible by 3
394 is divisible by 2
395 is divisible by 5
396 is divisible by 2
398 is divisible by 2
399 is divisible by 3
400 is divisible by 2
402 is divisible by 2
403 is divisible by 13
404 is divisible by 2
405 is divisible by 3
406 is divisible by 2
407 is divisible by 11
408 is divisible by 2
410 is divisible by 2
411 is divisible by 3
412 is divisible by 2
413 is divisible by 7
414 is divisible by 2
415 is divisible by 5
416 is divisible by 2
417 is divisible by 3
418 is divisible by 2
420 is divisible by 2
422 is divisible by 2
423 is divisible by 3
424 is divisible by 2
425 is divisible by 5
426 is divisible by 2
427 is divisible by 7
428 is divisible by 2
429 is divisible by 3
430 is divisible by 2
432 is divisible by 2
434 is divisible by 2
435 is divisible by 3
436 is divisible by 2
437 is divisible by 19
438 is divisible by 2
440 is divisible by 2
441 is divisible by 3
442 is divisible by 2
444 is divisible by 2
445 is divisible by 5
446 is divisible by 2
447 is divisible by 3
448 is divisible by 2
450 is divisible by 2
451 is divisible by 11
452 is divisible by 2
453 is divisible by 3
454 is divisible by 2
455 is divisible by 5
456 is divisible by 2
458 is divisible by 2
459 is divisible by 3
460 is divisible by 2
462 is divisible by 2
464 is divisible by 2
465 is divisible by 3
466 is divisible by 2
468 is divisible by 2
469 is divisible by 7
470 is divisible by 2
471 is divisible by 3
472 is divisible by 2
473 is divisible by 11
474 is divisible by 2
475 is divisible by 5
476 is divisible by 2
477 is divisible by 3
478 is divisible by 2
480 is divisible by 2
481 is divisible by 13
482 is divisible by 2
483 is divisible by 3
484 is divisible by 2
485 is divisible by 5
486 is divisible by 2
488 is divisible by 2
489 is divisible by 3
490 is divisible by 2
492 is divisible by 2
493 is divisible by 17
494 is divisible by 2
495 is divisible by 3
496 is divisible by 2
497 is divisible by 7
498 is divisible by 2
500 is divisible by 2
501 is divisible by 3
502 is divisible by 2
504 is divisible by 2
505 is divisible by 5
506 is divisible by 2
507 is divisible by 3
508 is divisible by 2
510 is divisible by 2
511 is divisible by 7
512 is divisible by 2
513 is divisible by 3
514 is divisible by 2
515 is divisible by 5
516 is divisible by 2
517 is divisible by 11
518 is divisible by 2
519 is divisible by 3
520 is divisible by 2
522 is divisible by 2
524 is divisible by 2
525 is divisible by 3
526 is divisible by 2
527 is divisible by 17
528 is divisible by 2
529 is divisible by 23
530 is divisible by 2
531 is divisible by 3
532 is divisible by 2
533 is divisible by 13
534 is divisible by 2
535 is divisible by 5
536 is divisible by 2
537 is divisible by 3
538 is divisible by 2
539 is divisible by 7
540 is divisible by 2
542 is divisible by 2
543 is divisible by 3
544 is divisible by 2
545 is divisible by 5
546 is divisible by 2
548 is divisible by 2
549 is divisible by 3
550 is divisible by 2
551 is divisible by 19
552 is divisible by 2
553 is divisible by 7
554 is divisible by 2
555 is divisible by 3
556 is divisible by 2
558 is divisible by 2
559 is divisible by 13
560 is divisible by 2
561 is divisible by 3
562 is divisible by 2
564 is divisible by 2
565 is divisible by 5
566 is divisible by 2
567 is divisible by 3
568 is divisible by 2
570 is divisible by 2
572 is divisible by 2
573 is divisible by 3
574 is divisible by 2
575 is divisible by 5
576 is divisible by 2
578 is divisible by 2
579 is divisible by 3
580 is divisible by 2
581 is divisible by 7
582 is divisible by 2
583 is divisible by 11
584 is divisible by 2
585 is divisible by 3
586 is divisible by 2
588 is divisible by 2
589 is divisible by 19
590 is divisible by 2
591 is divisible by 3
592 is divisible by 2
594 is divisible by 2
595 is divisible by 5
596 is divisible by 2
597 is divisible by 3
598 is divisible by 2
600 is divisible by 2
602 is divisible by 2
603 is divisible by 3
604 is divisible by 2
605 is divisible by 5
606 is divisible by 2
608 is divisible by 2
609 is divisible by 3
610 is divisible by 2
611 is divisible by 13
612 is divisible by 2
614 is divisible by 2
615 is divisible by 3
616 is divisible by 2
618 is divisible by 2
620 is divisible by 2
621 is divisible by 3
622 is divisible by 2
623 is divisible by 7
624 is divisible by 2
625 is divisible by 5
626 is divisible by 2
627 is divisible by 3
628 is divisible by 2
629 is divisible by 17
630 is divisible by 2
632 is divisible by 2
633 is divisible by 3
634 is divisible by 2
635 is divisible by 5
636 is divisible by 2
637 is divisible by 7
638 is divisible by 2
639 is divisible by 3
640 is divisible by 2
642 is divisible by 2
644 is divisible by 2
645 is divisible by 3
646 is divisible by 2
648 is divisible by 2
649 is divisible by 11
650 is divisible by 2
651 is divisible by 3
652 is divisible by 2
654 is divisible by 2
655 is divisible by 5
656 is divisible by 2
657 is divisible by 3
658 is divisible by 2
660 is divisible by 2
662 is divisible by 2
663 is divisible by 3
664 is divisible by 2
665 is divisible by 5
666 is divisible by 2
667 is divisible by 23
668 is divisible by 2
669 is divisible by 3
670 is divisible by 2
671 is divisible by 11
672 is divisible by 2
674 is divisible by 2
675 is divisible by 3
676 is divisible by 2
678 is divisible by 2
679 is divisible by 7
680 is divisible by 2
681 is divisible by 3
682 is divisible by 2
684 is divisible by 2
685 is divisible by 5
686 is divisible by 2
687 is divisible by 3
688 is divisible by 2
689 is divisible by 13
690 is divisible by 2
692 is divisible by 2
693 is divisible by 3
694 is divisible by 2
695 is divisible by 5
696 is divisible by 2
697 is divisible by 17
698 is divisible by 2
699 is divisible by 3
700 is divisible by 2
702 is divisible by 2
703 is divisible by 19
704 is divisible by 2
705 is divisible by 3
706 is divisible by 2
707 is divisible by 7
708 is divisible by 2
710 is divisible by 2
711 is divisible by 3
712 is divisible by 2
713 is divisible by 23
714 is divisible by 2
715 is divisible by 5
716 is divisible by 2
717 is divisible by 3
718 is divisible by 2
720 is divisible by 2
721 is divisible by 7
722 is divisible by 2
723 is divisible by 3
724 is divisible by 2
725 is divisible by 5
726 is divisible by 2
728 is divisible by 2
729 is divisible by 3
730 is divisible by 2
731 is divisible by 17
732 is divisible by 2
734 is divisible by 2
735 is divisible by 3
736 is divisible by 2
737 is divisible by 11
738 is divisible by 2
740 is divisible by 2
741 is divisible by 3
742 is divisible by 2
744 is divisible by 2
745 is divisible by 5
746 is divisible by 2
747 is divisible by 3
748 is divisible by 2
749 is divisible by 7
750 is divisible by 2
752 is divisible by 2
753 is divisible by 3
754 is divisible by 2
755 is divisible by 5
756 is divisible by 2
758 is divisible by 2
759 is divisible by 3
760 is divisible by 2
762 is divisible by 2
763 is divisible by 7
764 is divisible by 2
765 is divisible by 3
766 is divisible by 2
767 is divisible by 13
768 is divisible by 2
770 is divisible by 2
771 is divisible by 3
772 is divisible by 2
774 is divisible by 2
775 is divisible by 5
776 is divisible by 2
777 is divisible by 3
778 is divisible by 2
779 is divisible by 19
780 is divisible by 2
781 is divisible by 11
782 is divisible by 2
783 is divisible by 3
784 is divisible by 2
785 is divisible by 5
786 is divisible by 2
788 is divisible by 2
789 is divisible by 3
790 is divisible by 2
791 is divisible by 7
792 is divisible by 2
793 is divisible by 13
794 is divisible by 2
795 is divisible by 3
796 is divisible by 2
798 is divisible by 2
799 is divisible by 17
800 is divisible by 2
801 is divisible by 3
802 is divisible by 2
803 is divisible by 11
804 is divisible by 2
805 is divisible by 5
806 is divisible by 2
807 is divisible by 3
808 is divisible by 2
810 is divisible by 2
812 is divisible by 2
813 is divisible by 3
814 is divisible by 2
815 is divisible by 5
816 is divisible by 2
817 is divisible by 19
818 is divisible by 2
819 is divisible by 3
820 is divisible by 2
822 is divisible by 2
824 is divisible by 2
825 is divisible by 3
826 is divisible by 2
828 is divisible by 2
830 is divisible by 2
831 is divisible by 3
832 is divisible by 2
833 is divisible by 7
834 is divisible by 2
835 is divisible by 5
836 is divisible by 2
837 is divisible by 3
838 is divisible by 2
840 is divisible by 2
841 is divisible by 29
842 is divisible by 2
843 is divisible by 3
844 is divisible by 2
845 is divisible by 5
846 is divisible by 2
847 is divisible by 7
848 is divisible by 2
849 is divisible by 3
850 is divisible by 2
851 is divisible by 23
852 is divisible by 2
854 is divisible by 2
855 is divisible by 3
856 is divisible by 2
858 is divisible by 2
860 is divisible by 2
861 is divisible by 3
862 is divisible by 2
864 is divisible by 2
865 is divisible by 5
866 is divisible by 2
867 is divisible by 3
868 is divisible by 2
869 is divisible by 11
870 is divisible by 2
871 is divisible by 13
872 is divisible by 2
873 is divisible by 3
874 is divisible by 2
875 is divisible by 5
876 is divisible by 2
878 is divisible by 2
879 is divisible by 3
880 is divisible by 2
882 is divisible by 2
884 is divisible by 2
885 is divisible by 3
886 is divisible by 2
888 is divisible by 2
889 is divisible by 7
890 is divisible by 2
891 is divisible by 3
892 is divisible by 2
893 is divisible by 19
894 is divisible by 2
895 is divisible by 5
896 is divisible by 2
897 is divisible by 3
898 is divisible by 2
899 is divisible by 29
900 is divisible by 2
901 is divisible by 17
902 is divisible by 2
903 is divisible by 3
904 is divisible by 2
905 is divisible by 5
906 is divisible by 2
908 is divisible by 2
909 is divisible by 3
910 is divisible by 2
912 is divisible by 2
913 is divisible by 11
914 is divisible by 2
915 is divisible by 3
916 is divisible by 2
917 is divisible by 7
918 is divisible by 2
920 is divisible by 2
921 is divisible by 3
922 is divisible by 2
923 is divisible by 13
924 is divisible by 2
925 is divisible by 5
926 is divisible by 2
927 is divisible by 3
928 is divisible by 2
930 is divisible by 2
931 is divisible by 7
932 is divisible by 2
933 is divisible by 3
934 is divisible by 2
935 is divisible by 5
936 is divisible by 2
938 is divisible by 2
939 is divisible by 3
940 is divisible by 2
942 is divisible by 2
943 is divisible by 23
944 is divisible by 2
945 is divisible by 3
946 is divisible by 2
948 is divisible by 2
949 is divisible by 13
950 is divisible by 2
951 is divisible by 3
952 is divisible by 2
954 is divisible by 2
955 is divisible by 5
956 is divisible by 2
957 is divisible by 3
958 is divisible by 2
959 is divisible by 7
960 is divisible by 2
961 is divisible by 31
962 is divisible by 2
963 is divisible by 3
964 is divisible by 2
965 is divisible by 5
966 is divisible by 2
968 is divisible by 2
969 is divisible by 3
970 is divisible by 2
972 is divisible by 2
973 is divisible by 7
974 is divisible by 2
975 is divisible by 3
976 is divisible by 2
978 is divisible by 2
979 is divisible by 11
980 is divisible by 2
981 is divisible by 3
982 is divisible by 2
984 is divisible by 2
985 is divisible by 5
986 is divisible by 2
987 is divisible by 3
988 is divisible by 2
989 is divisible by 23
990 is divisible by 2
992 is divisible by 2
993 is divisible by 3
994 is divisible by 2
995 is divisible by 5
996 is divisible by 2
998 is divisible by 2
999 is divisible by 3
1000 is divisible by 2
[1, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 7
1, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 1
51, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229,
233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313,
317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409,
419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499,
503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601,
607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691,
701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809,
811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907,
911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]
[1, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 7
1, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 1
51, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229,
233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313,
317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409,
419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499,
503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601,
607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691,
701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809,
811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907,
911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997]
[1, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 7
1, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 1
51, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229,
233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313,
317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409,
419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499,
503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601,
607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691,
701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809,
811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907,
911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997],end =
24.Harshad number
if a number is divisible by sum of it's digits it is called Harshad number
18 ---> Sum of it's digits is 9 and 18%9 is 0.So,18 is Harshad number
In [25]: is_harshad(223)
Out[25]: 7
In [27]: is_harshad(19)
Out[27]: False
In [28]: is_harshad(18)
Out[28]: True
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21, 24, 27, 30, 36, 40, 42, 4
5, 48, 50, 54, 60, 63, 70, 72, 80, 81, 84, 90, 100, 102, 108, 110, 111, 11
2, 114, 117, 120, 126, 132, 133, 135, 140, 144, 150, 152, 153, 156, 162, 1
71, 180, 190, 192, 195, 198, 200, 201, 204, 207, 209, 210, 216, 220, 222,
224, 225, 228, 230, 234, 240, 243, 247, 252, 261, 264, 266, 270, 280, 285,
288, 300, 306, 308, 312, 315, 320, 322, 324, 330, 333, 336, 342, 351, 360,
364, 370, 372, 375, 378, 392, 396, 399, 400, 402, 405, 407, 408, 410, 414,
420, 423, 432, 440, 441, 444, 448, 450, 460, 465, 468, 476, 480, 481, 486,
500, 504, 506, 510, 511, 512, 513, 516, 518, 522, 531, 540, 550, 552, 555,
558, 576, 588, 592, 594, 600, 603, 605, 612, 621, 624, 629, 630, 640, 644,
645, 648, 660, 666, 684, 690, 700, 702, 704, 711, 715, 720, 730, 732, 735,
736, 738, 756, 770, 774, 777, 780, 782, 792, 800, 801, 803, 804, 810, 820,
825, 828, 832, 840, 846, 864, 870, 874, 880, 882, 888, 900, 902, 910, 912,
915, 918, 935, 936, 954, 960, 966, 972, 990, 999, 1000, 1002, 1008, 1010,
1011, 1012, 1014, 1015, 1016, 1017, 1020, 1026, 1032, 1035, 1040, 1044, 10
50, 1053, 1056, 1062, 1066, 1071, 1080, 1088, 1090, 1092, 1095, 1098, 110
0, 1101, 1104, 1107, 1110, 1116, 1120, 1122, 1125, 1128, 1130, 1134, 1140,
1141, 1143, 1148, 1152, 1160, 1161, 1164, 1168, 1170, 1180, 1183, 1185, 11
88, 1200, 1204, 1206, 1212, 1215, 1220, 1224, 1230, 1232, 1233, 1236, 124
2, 1251, 1260, 1270, 1272, 1274, 1275, 1278, 1296, 1300, 1302, 1304, 1305,
1308, 1310, 1314, 1320, 1323, 1330, 1332, 1341, 1344, 1350, 1360, 1365, 13
68, 1380, 1386, 1387, 1394, 1400, 1404, 1410, 1413, 1416, 1417, 1422, 143
1, 1440, 1450, 1452, 1455, 1456, 1458, 1476, 1494, 1500, 1503, 1512, 1520,
1521, 1524, 1526, 1530, 1534, 1540, 1545, 1547, 1548, 1558, 1560, 1566, 15
84, 1590, 1596, 1602, 1611, 1620, 1630, 1632, 1635, 1638, 1651, 1652, 165
6, 1659, 1674, 1679, 1680, 1692, 1701, 1704, 1710, 1720, 1725, 1728, 1729,
1740, 1744, 1746, 1764, 1770, 1782, 1785, 1800, 1810, 1812, 1815, 1818, 18
36, 1848, 1853, 1854, 1860, 1872, 1886, 1890, 1896, 1898, 1900, 1904, 190
5, 1908, 1920, 1926, 1944, 1950, 1962, 1968, 1974, 1980, 1998, 2000]
In [31]: count_vowels('Apple')
Out[31]: 2
In [32]: count_vowels("ZOMATOE")
Out[32]: 4
Out[34]: [1, 1]
In [35]: count_vowels("BanAna")
Out[35]: 3
In [36]: count_vowels("ZOMATOE")
Out[36]: 4
In [38]: char_count('banana')
{}
{'b': 1}
{'b': 1, 'a': 1}
{'b': 1, 'a': 1, 'n': 1}
{'b': 1, 'a': 2, 'n': 1}
{'b': 1, 'a': 2, 'n': 2}
Out[38]: {'b': 1, 'a': 3, 'n': 2}
STEPS :
1.Save correct PIN and set nax_attempts = 3
2.Check every attempt for user input
- If PIN is correct display correct PIN and stop the loop
- If PIN entered wrong increase number of attempts count
3.If 3 attempts are over display account is locked
In [40]: correct_PIN="123456"
max_attempts = 3
attempts = 0
while attempts<max_attempts:
user_input=input("Enter PIN : ")
if user_input == correct_PIN:
print("Entered PIn is correct")
break;
else :
attempts+=1
print(f"Wrong pin entered,{max_attempts-attempts} left ")
else :
print("Attempts Exhausted.Account is locked")
28. Create a function that takes name and marks from user
and returns average marks
In [41]: def average(name,**marks):
average = sum(marks.values())/len(marks.values())
return average
Out[42]: 82.5
Subject : Tel,marks = 80
Subject : Hin,marks = 85
Subject : Eng,marks = 90
Subject : Maths,marks = 75
Out[44]: 82.5
Subject : Tel,marks = 80
Subject : Hin,marks = 85
Subject : Eng,marks = 90
Subject : Maths,marks = 75
kasi secured 82.5 marks on an average
In [48]: final_price('Appliances',400,1000,2000,discount=30,delivery=36)
Out[48]: 2416.0
Out[49]: 3400.0
In [51]: total_price(LED=20_000,Refrigerator=15000,WM=16000,discount=20,delivery=2
LED 20000
Refrigerator 15000
WM 16000
Out[51]: 41000.0
H
eH
leH
lleH
olleH
@olleH
1@olleH
21@olleH
321@olleH
$321@olleH
!$321@olleH
&!$321@olleH
W&!$321@olleH
oW&!$321@olleH
roW&!$321@olleH
lroW&!$321@olleH
dlroW&!$321@olleH
&dlroW&!$321@olleH
?&dlroW&!$321@olleH
!?&dlroW&!$321@olleH
*!?&dlroW&!$321@olleH
(*!?&dlroW&!$321@olleH
((*!?&dlroW&!$321@olleH
A((*!?&dlroW&!$321@olleH
Reversed string : A((*!?&dlroW&!$321@olleH
Out[68]: '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
text="Hello@123$!&World&?!*((@"
count = sum([1 for i in text if i in string.punctuation])
count
Out[69]: 11
In [70]: text="Hello@123$!&World&?!*((@"
count=0
for i in text:
if i in string.punctuation:
count+=1
count
Out[70]: 11
In [72]: is_strong_number(145)
Out[72]: True
In [73]: list(filter(is_strong_number,range(1,1_00_001)))
Out[73]: [1, 2, 145, 40585]
32.Perfect numbers
A number is said to be a perfect number if sum of it's divisors is same as the
number
6---> factors 1,2,3(excluding 6)==>1+2+3=6
In [75]: is_perfect_number(6)
Out[75]: True
In [76]: list(filter(is_perfect_number,range(1,10001)))
In [79]: is_perfect_numbers(28)
Out[79]: True
In [80]: list(filter(is_perfect_numbers,range(10001)))
In [ ]:
File Handling
"r" = read
"w" = write
"a" = append
"x" = creates new file if not there,else raise error if exists
read()
close()
readline()
readlines()
Exception
In [81]: x=15
y=0
print(x/y)
z=12
w=10
print(z+w)
--------------------------------------------------------------------------
-
ZeroDivisionError Traceback (most recent call las
t)
Cell In[81], line 3
1 x=15
2 y=0
----> 3 print(x/y)
4 z=12
5 w=10
In [83]: try :
x = int(input("Enter a number : "))
y = int(input("Enter a number : "))
print(x/y)
except ZeroDivisionError:
print("Inside zero division error block,\
Denominator is zero and division by zero not posssible")
except Exception as e:
print(f"Error :{e}")
finally :
z=12
w=10
print(z+w)
number = 10
while True:
try:
user_input=int(input("Guess the number : "))
if user_input>number:
raise ValueToolLargeError
elif user_input<number :
raise ValueToolSmallError
else :
print("Correct Guess")
break
except ValueToolLargeError:
print("Input is too large,Try again !!")
except ValueToolSmallError:
print("Input is too small,Try again !!")
In [86]: num = []
while True:
inp=float(input("Enter a number : "))
if int(inp)!=0:
num.append(inp)
continue
avg=sum(num)/len(num)
print(avg)
break;
3.5
34.Write a program that takes inputs from user.After each input prints
cummulative average which is average of numbers entered so
far,program should stop taking inputs once user enters done .Ignore
invalid entriesnon-numeric values except done )and display appropriate
message
In [87]: numbers = []
total = 0
count = 0
while True:
inp=input("Enter your input when done is entered,this will stop taking
if inp.lower()=='done':
print(f"Final average for {numbers} : {round(avg,3)}")
break;
try:
num = float(inp)
numbers.append(num)
total+=num
count+=1
avg = total/count
print(f"Cummulative average for {numbers} : {round(avg,3)}")
except:
print("Enter a number or done")
In [90]: numbers = []
while True:
inp=input("Enter your input when done is entered,this will stop taking
if inp.lower()=='done':
print(f"Final average for {numbers[-3::]} : {round(avg,3)}")
break;
try:
num = float(inp)
numbers.append(num)
window = numbers[-3:]
if window:
avg=sum(window)/len(window)
print(f"Moving average for {numbers[-3:]} : {round(avg,3)}")
except:
print("Enter a number or done")
In [ ]:
Oops
In [91]: class Sample:
def __init__(self):
print(f"Object is created")
In [94]: s1=Sample() #Instantiation of object from class and object is also called
Object is created
In [95]: Sample()
Object is created
Out[95]: <__main__.Sample at 0x2199d0e2ed0>
In [96]: Sample
Out[96]: __main__.Sample
In [98]: p1 = Person("Ram",28,'FeMale')
In [99]: p1.display_info()
In [100… p2 = Person("John",30,"Male")
In [101… p2.display_info()
In [102… p1.name='Mukesh'
In [103… p1.display_info()
In [104… type(p1)
Out[104… __main__.Person
In [107… print(dir(car1)[-5::])
In [108… car1.car_details()
In [109… car2.car_details()
In [110… car1.brand
Out[110… 'Tesla'
In [112… Student("TOM","DS001","CSE",english=70,maths=80,science=90).student_detail
In [114… s1 =Student("TOM","DS001","CSE",english=70,maths=80,science=90)
s2=Student("jerry","DS002","CS",english=90,maths=75,science=60,others=370
In [115… s1.student_details()
In [116… s2.student_details()
In [117… s1.average_marks()
In [118… s2.average_marks()
In [121… bankacc1.name
Out[121… 'John'
In [122… bankacc1.IFSC
--------------------------------------------------------------------------
-
AttributeError Traceback (most recent call las
t)
Cell In[122], line 1
----> 1 bankacc1.IFSC
In [123… bankacc1.ifsc
Out[123… 'SBI98989'
In [124… bankacc1.check_balance()
Balance : 6000
In [126… bankacc1.withdrawl()
Balance : 5000
In [127… bankacc1.deposit()
Balance : 8000
In [128… bankacc1.check_balance()
Balance : 8000
In [129… bankacc1.withdrawl()
Insufficient funds
In [ ]:
Inheritance
Simple inheritance
In [130… class Person:
def __init__(self,name,age,gender):
self.name = name
self.age = age
self.gender = gender
def display_info(self):
print(f"{self.name} is {self.age} years old is {self.gender}")
In [133… print(dir(person1)[-5:])
In [134… dir(person1)[-5:]
In [135… dir(emp1)[-7:]
In [136… person1.display_info()
Jack is 28 years old is Male
In [137… person1.emp_details()
--------------------------------------------------------------------------
-
AttributeError Traceback (most recent call las
t)
Cell In[137], line 1
----> 1 person1.emp_details()
In [139… emp1.emp_details()
In [140… person1.emp_details()
--------------------------------------------------------------------------
-
AttributeError Traceback (most recent call las
t)
Cell In[140], line 1
----> 1 person1.emp_details()
In [141… person1.name
Out[141… 'Jack'
In [142… emp1.name
Out[142… 'Ramsa'
In [146… person1.emp_ID
--------------------------------------------------------------------------
-
AttributeError Traceback (most recent call las
t)
Cell In[146], line 1
----> 1 person1.emp_ID
In [145… emp1.emp_ID
Out[145… 'A001'
Single inheritance :
A class inherits from one parent class.
In our example ElectricCar demonstrate Single inheritance.
This is the simplest form of inheritance,allowing the derived class to gain
functionality from the parent class
In [150… electric_car_1.display_info()
In [151… ElectricCar.__mro__
In [152… electric_car_1.charge()
In [153… electric_car_1.charge()
Multi-Level Inheritance :
This occurs when a class is derived from a class that is itself derived from another
class.
For example, Luxurycar inherits from ElectricCar , which in turn inherits
from Car .
This creates chain hierarchy of inheritance,allowing for more specialized behaviour
at each level
In [156… dir(electric_car_1)[-6:]
In [157… dir(ferrari)[-10:]
Out[157… ['__subclasshook__',
'__weakref__',
'battery_capacity',
'brand',
'charge',
'display_info',
'luxury_features',
'luxury_features_available',
'model',
'year']
In [158… car_1.display_info()
In [159… electric_car_1.display_info()
In [160… ferrari.display_info()
ferrari Nitro has battery capacity : 80 and luxury features : ['nitro boos
t', 'Super charge']
In [161… LuxuryCar.__mro__
In [163… luxury_car_1.charge()
In [164… luxury_car_1.luxury_features_available()
In [165… luxury_car_1.display_info()
In [ ]:
Multiple Inheritance :
Multiple inheritance in Python allows a class to inherit attributes and methods from
more than one parent class.
This means a single child class can be derived from two or more base classes,
combining their functionalities.
In [171… amp.display_speed()
In [172… AmphibiousVehicle.__mro__
Out[172… (__main__.AmphibiousVehicle,
__main__.LandVehicle,
__main__.WaterVehicle,
object)
In [176… amp_vehicle_water.display_speed()
In [177… AmphibiousVehicle.__mro__
Out[177… (__main__.AmphibiousVehicle,
__main__.LandVehicle,
__main__.WaterVehicle,
object)
In [178… AmphibiousWaterVehicle.__mro__
Out[178… (__main__.AmphibiousWaterVehicle,
__main__.WaterVehicle,
__main__.LandVehicle,
object)
In [180… AmphibiousLandVehicle.__mro__
Out[180… (__main__.AmphibiousLandVehicle,
__main__.LandVehicle,
__main__.WaterVehicle,
object)
In [ ]:
Hybrid Inheritance
Hybrid inheritance is a concept in object-oriented programming where a class
inherits properties and behaviors from multiple base classes.
combining different types of inheritance (like single, multiple, and hierarchical).
This allows for a more flexible and complex class structure, enabling the reuse of
code and the modeling of intricate relationships
In [183… emp1.get_details()
In [184… emp2.get_details()
In [185… emp1.name
Out[185… 'John'
In [186… emp2.name
Out[186… 'Tom'
In [187… emp2.company
Out[187… 'Language.ai'
In [190… dev1.project,dev2.project
In [192… dev1.project,dev2.project
In [193… dev1.change_project("Fine-Tuning")
In [194… dev1.project,dev2.project
In [196… m1 = Manager("Ranchan","Vision.ai")
In [197… Manager.__mro__
In [198… m1.manage()
In [199… print(dir(m1)[-5:])
In [201… TeamLead.__mro__
Out[201… (__main__.TeamLead,
__main__.Developer,
__main__.Manager,
__main__.Employee,
object)
In [203… TL1.name
Out[203… 'Patrick'
In [204… TL1.get_details()
In [205… Developer.__mro__
In [206… Manager.__mro__
Encapsulation :
Process of restricting the object to change some variables is called
"Encapsulation"
To restrcit the data,we have to create private variables and methods
__Double underscore to create private variables and private methods
Counter
Attributes - count , maxcount
Methods - start_counting() , auto_increment()
start_counting() - For starting the counting process
auto_increment() - A private method which is responsible for counting process
def __auto_increment(self):
while self.__count<self.__max_count:
self.__count+=1
print(f"Counter value : {self.__count}")
def start_counting(self):
self.__auto_increment()
print("Maximum count reached")
In [208… counter_1=Counter(20)
counter_2=Counter() #it takes default 10
In [209… counter_1.__count
--------------------------------------------------------------------------
-
AttributeError Traceback (most recent call las
t)
Cell In[209], line 1
----> 1 counter_1.__count
In [210… counter_1.__max_count
--------------------------------------------------------------------------
-
AttributeError Traceback (most recent call las
t)
Cell In[210], line 1
----> 1 counter_1.__max_count
In [211… counter_1.__auto_increment()
--------------------------------------------------------------------------
-
AttributeError Traceback (most recent call las
t)
Cell In[211], line 1
----> 1 counter_1.__auto_increment()
In [212… counter_n=Counter(20)
counter_1.__count=100
counter_1.__max_count=120
In [213… counter_n.start_counting()
Counter value : 1
Counter value : 2
Counter value : 3
Counter value : 4
Counter value : 5
Counter value : 6
Counter value : 7
Counter value : 8
Counter value : 9
Counter value : 10
Counter value : 11
Counter value : 12
Counter value : 13
Counter value : 14
Counter value : 15
Counter value : 16
Counter value : 17
Counter value : 18
Counter value : 19
Counter value : 20
Maximum count reached
Abstract :
Abstraction is the concept of hiding the complex details.It involes creating simple
interface that hide implementation and details are left to be inherited
@abstractmethod
def message(self,number,message):
''' Message to a contact......'''
pass
@abstractmethod
def turn_on(self):
'''functionality to turn on.....'''
pass
@abstractmethod
def turn_off(self):
'''functionality to turn off.....'''
pass
In [218… apple_iphone.call(234567)
Calling 234567
In [219… apple_iphone.message(234567,'Hi')
In [220… apple_iphone.turn_on()
Mobile in turning on
In [221… apple_iphone.turn_off()
Polymorphism :
Poly means many
Morph means forms
Polymorphism refers to behaving the same function or operator differently base on
situations or One function can have multiple characters
for example : Human can play many characters like
student,son,husband,teacher,driver,employee and so on
Types : Method overloading and Operator overloading
Out[222… 4
In [224… '2'+'2'
Out[224… '22'
In [225… # Concatenation
"Hi" + " " + "Good Morning"
In [226… [3,4,5]+[5,2,1]
Out[226… [3, 4, 5, 5, 2, 1]
Out[227… 3
Out[228… 5
class Circle:
def draw(self):
print("Draw a circle")
class Square:
def draw(self):
print("Draw a square")
In [230… s1 = Shape()
c1 = Circle()
sq1 = Square()
Draw a polygon
Draw a circle
Draw a square
Draw a polygon
Draw a circle
Draw a square
In [235… for i in (s1,c1,sq1):
print(i.draw())
Draw a polygon
None
Draw a circle
None
Draw a square
None
In [ ]:
In [ ]: