0% found this document useful (0 votes)
2 views147 pages

Python Basics 3

The document provides an overview of Python programming, covering its features, data types, variables, operators, and control structures. It includes examples of basic syntax, arithmetic operations, conditional statements, and user input handling. Additionally, it discusses various programming problems and their solutions using Python code.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views147 pages

Python Basics 3

The document provides an overview of Python programming, covering its features, data types, variables, operators, and control structures. It includes examples of basic syntax, arithmetic operations, conditional statements, and user input handling. Additionally, it discusses various programming problems and their solutions using Python code.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 147

In [1]: !

python --version

Python 3.12.7

In [2]: print("Kasi")

Kasi

High level language


Community and eco system
Interpreted language
Easy to learn

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

In [4]: #print the value assigned to price


print(price)

100

In [5]: GST = price*1.18


print(GST)

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

In [11]: #finding cost of apples


quantity = int(input("Enter the number of apples : "))
price = int(input("Enter the price of each apple : "))
total_price=quantity*price
print(total_price)

60

In [12]: type(quantity)
Out[12]: int

In [13]: #type conversion


b = int(quantity)
c = int(price)

In [14]: type(c)

Out[14]: int

In [15]: total_price = quantity*price


print(total_price)

60

In [16]: Quantity_A = int(input("Enter the quantity of type A books : "))


Quantity_B = int(input("Enter the quantity of type B books : "))
price_of_A = int(input("Enter the price of type A Books : "))
price_of_B = int(input("Enter the price of type B Books : "))

In [18]: total_price_A=Quantity_A * price_of_A


total_price_B=Quantity_B * price_of_B
total_price=total_price_A + total_price_B
print(total_price)

240

In [23]: 17/4 # Division : gives quotient in float

Out[23]: 4.25

In [24]: 17//4 # Floor Division : gives quotient in integer

Out[24]: 4

In [25]: 17%4 #gives remainder

Out[25]: 1

In [26]: 1568%100 #gives remainder

Out[26]: 68

In [27]: 5**2 #exponentiation

Out[27]: 25

In [28]: 14**0.5 #square root of a number

Out[28]: 3.7416573867739413

In [29]: round(14**0.5 , 3) #rounding of to the nearest or prints no decimal points

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.

The return value is an integer if ndigits is omitted or None. Otherwi


se
the return value has the same type as the number. ndigits may be nega
tive.

Operators
1.Arithmetic operator
2.Assignment operator
3.Comparision operator
4.Logical operator
5.Identity operator
6.Membership operator

Assignment and Arithmetic operator


In [31]: x=5
x+=5 #x=x+5 also called updating operator
print(x)

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

Logical operators 'and' 'or' 'not' :


In [46]: 90>34 and 23<12
# 1 * 0---> false

Out[46]: False

In [47]: 56==56 and 10!=13 and 21>22

Out[47]: False

in logical 'and' operations if one of the expression is


' false' then entire expression is false

In [48]: 56==56 or 10!=13 or 21>22

Out[48]: True
in logical 'or' operations if one of the expression is
' true' then entire expression is 'true'

In [49]: not 45==23

Out[49]: True

In [50]: not 45<60

Out[50]: False

In [51]: not 2025>2018

Out[51]: False

in logical 'not' ,the result is simply opposite of expression

not >> and >> or

Identity operators ( is , is not )


In [52]: x=34
y=34
x==y #Is x and y are same by value?

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

In [55]: x is y #Is x and y are same by value and reference ?

Out[55]: True

In [56]: id(x),id(y)

Out[56]: (140719882907096, 140719882907096)

In [57]: id(a),id(b)
Out[57]: (140719882914200, 140719882914200)

In [58]: id(m),id(n)

Out[58]: (2551481510192, 2551481513296)

f-format string
In [65]: boxes = 100
boxes+=20
print(f"Total no of boxes = {boxes}")

Total no of boxes = 120

In [66]: print("Total no of boxes = {boxes}") #removing 'f' will considers only as

Total no of boxes = {boxes}

In [67]: apple_count = int(input("Enter no of apples in kg : "))


apple_price=int(input("Enter the price of 1 kg apple : "))
banana_count=float(input("Enter no of bananas in kg : "))
banana_price=float(input("Enter the price of 1kg bananas : "))
total_price=apple_count*apple_price+banana_count*banana_price
# print(total_price)
print(f"Apple price = {apple_count*apple_price}\nBanana price = {banana_co

Apple price = 60
Banana price = 100.0

In [68]: given_time=int(input("Enter time in minutes: "))


in_hours=given_time//60
print(in_hours)
in_minutes=given_time%60
print(in_minutes)
print(f"Total work time = {in_hours} hours {in_minutes} minutes")

2
30
Total work time = 2 hours 30 minutes

In [69]: bill_amount=float(input("Enter the bill amount : "))


discount_price=bill_amount*(15/100)
print(discount_price)
bill_amount_after_discount=bill_amount-discount_price
print(f"Billing amount after discount= {bill_amount_after_discount}")

150.0
Billing amount after discount= 850.0

In [70]: pencils=125
print(f"Total full boxes = {125//12} and {pencils%12} left out")

Total full boxes = 10 and 5 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

1.check whether a person is eligible to vote

In [77]: age=int(input("Enter age : "))


if age>=18:
print("Eligible to vote")
else :
print("Not eligible to vote")

Not eligible to vote

2.check whether a number is even or odd

In [78]: num=int(input("Enter a number : "))


if num%2==0:
print(f"{num} is even number")
else:
print(f"{num} is odd number")

9 is odd number

3.Take marks as input and print whether passed or failed

In [79]: marks=int(input("Enter marks : "))


if marks>=35:
print("You have passed")
else:
print("You have failed")

You have passed

4.Check whether a given number is divisible by 2 and 3

In [80]: num=int(input("Enter a number : "))


if num%2==0 and num%3==0 :
print(f"{num} is exactly divisible by 2 and 3")
else:
print(f"{num} is not divisible by 2 and 3")

18 is exactly divisible by 2 and 3

5.Check whether a word is starting with vowel

In [82]: word = input('enter the word :')


if word[0].lower() in "aeiou":
print(f"{word} is starting with vowel")
else :
print(f"{word} is not starting with vowel")

Innomatics is starting with vowel

In [ ]:

elif ladder

1.Number problem
(100 ->999) - three digit number
(10->99) - two digit number
(0 ->9) - one digit number

In [81]: num = int(input("enter the number:"))


if num <= 999 and num >= 100:
print(f"{num} is three digit number")
elif num <= 99 and num >= 10:
print(f"{num} is two digit number")
elif num <= 9 and num >= 0:
print(f"{num} is three digit number")
else :
print("invalid number")

99 is two 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

in case of negetive number or >100 - invalid number

In [90]: marks = int(input("enter the marks:"))


if 75 <= marks <= 100: # or marks >= 75 and marks
print(f"{marks} belongs to A grade") # though two canditions sa
elif 65<= marks <= 75:
print(f"{marks} belongs to B grade")
elif 50 <= marks <= 65:
print(f"{marks} belongs to C grade")
elif 35 <= marks <= 50:
print(f"{marks} belongs to D grade")
elif 0 <= marks <= 34 :
print(f"{marks} under failed")
else :
print("invalid number")

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

4.VOWEL WORD AND EVEN NUMBER

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

In [100… word = input("enter the word :")


num = int(input("enter the num :"))
if word[0].lower() in "aeiou" and num % 2 == 0 :
print(f"{word} is starting with vowel and {num} is even")
elif word[0].lower() in "aeiou" and num % 2 != 0 :
print(f"{word} is starting with vowel and {num} is odd")
elif word[0].lower() not in "aeiou" and num % 2 == 0 :
print(f"{word} is not starting with vowel and {num} is even")
else :
print(f"{word} is not starting with vowel and {num} is odd")

Innomatics is starting with vowel and 7 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

Nested if and if-else


1.Marks problem
> 35
>75 distinction
<75 passed
<35 failed

In [106… marks=int(input("Enter marks:"))


if marks>=35:
if marks>=75:
print("Distinction")
else :
print("Passed")
else:
print("Failed")

Distinction

2.Problem:
You are building a simple electricity billing system. Based on the number of units
consumed, the rate per unit varies:

Units Consumed Rate per Unit

0–100 units ₹5/unit

101–200 units ₹7/unit

201–300 units ₹10/unit

Above 300 ₹15/unit

Write a Python program that:

Takes the number of units consumed as input.


Calculates and prints the total bill.

📌 Bonus: Add a fixed meter charge of ₹50 to the final bill.


In [109… units=int(input("Enter no of units consumed : "))
if units >=0 and units<=100 :
bill=units*5+50;
elif units>100 and units<=200 :
bill=units*7+50;
elif 200< units <=300 :
bill=units*10+50;
elif units>300:
bill=units*15+50;
else :
print("Invalid input")
print(f"Units consumed = {units}")
print(f"Your electricity bill is Rs.{bill}")

Units consumed = 300


Your electricity bill is Rs.3050

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

In [111… L=[3,4,7,"kasi",5.27,"pass",7,3] #creating a list

In [112… print(L) #printing a list

[3, 4, 7, 'kasi', 5.27, 'pass', 7, 3]

In [113… L[3] #accesing specific item

Out[113… 'kasi'

In [114… print(L[3])

kasi

In [115… print(L[-1]) #to access last item in the list =

In [116… L[2]="python" #modifying

In [117… print(L)

[3, 4, 'python', 'kasi', 5.27, 'pass', 7, 3]

In [118… print(len(L)) #to know the length of L

In [119… type(L) #to know the type of data


Out[119… list

In [120… # create a list of fruits


fruits=["Apple","Mango","Banana","PineApple","Water Melon"]

In [121… print(fruits)

['Apple', 'Mango', 'Banana', 'PineApple', 'Water Melon']

In [122… print(len(fruits))

In [123… print(fruits[len(fruits)-3])

Banana

In [124… fruits[3]="Avacado"

In [125… print(fruits)

['Apple', 'Mango', 'Banana', 'Avacado', 'Water Melon']

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]

Out[130… [5, 'lion', 'true', 42]

In [131… l[1::2]

Out[131… [4, 'lion', 42, 'true']

In [132… l[::3]

Out[132… [3, 'lion', 'lion']

In [133… l[6::-1] #prints in reverse direction

Out[133… ['lion', 42, 'true', 'lion', 5, 4, 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]

Out[135… [3.125, 'lion', 'true']


In [136… fruits=["Apple","Mango","Banana","Pine Apple","Water Melon","Pomegranate"
print(fruits)

['Apple', 'Mango', 'Banana', 'Pine Apple', 'Water Melon', 'Pomegranate',


'kiwi']

In [137… fruits[2::2] #print every second element starting from 3rd item

Out[137… ['Banana', 'Water Melon', 'kiwi']

In [138… fruits[-1:-4:-1] #print all 3 in reverse direction

Out[138… ['kiwi', 'Pomegranate', 'Water Melon']

In [139… fruits[:len(fruits)-1:1] #print all elements except the last

Out[139… ['Apple', 'Mango', 'Banana', 'Pine Apple', 'Water Melon', 'Pomegranate']

In [140… fruits[3::-1] #print first 4 elements in reverse direction

Out[140… ['Pine Apple', 'Banana', 'Mango', 'Apple']

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

Out[142… ['hello', 'Kasi', 2, 3, 4, 'fruits', 'animals', 'birds']

In [143… print(g)

['hello', 'Kasi', 2, 3, 4, 'fruits', 'animals', 'birds']

In [144… e #the original list remains same

Out[144… ['hello', 'Kasi', 2, 3, 4]

In [145… f #the original list remains same

Out[145… ['fruits', 'animals', 'birds']

nested list
In [146… c =[30,20,50,["Hello","good",10]]
c[3] #accessing list item

Out[146… ['Hello', 'good', 10]

In [147… c[3][1] #accesiing list and then items in list

Out[147… 'good'

In [148… c[-1][1::] #slicing

Out[148… ['good', 10]

built in functions of a list

1.append( )- used to add single element at the end of the


list
In [149… fruits=["Apple","Banana","Cherry"]
print(fruits)
fruits.append("kiwi")
fruits

['Apple', 'Banana', 'Cherry']


Out[149… ['Apple', 'Banana', 'Cherry', 'kiwi']

In [150… fruits

Out[150… ['Apple', 'Banana', 'Cherry', 'kiwi']

In [ ]:

2.extend()-used to attend our current with another list


In [151… fruits=["Apple","Banana","Cherry"]
print(fruits)
fruits.extend(["Water melon","pine apple","orange"]) #don't forget to keep
fruits #we should keep items in a list

['Apple', 'Banana', 'Cherry']


Out[151… ['Apple', 'Banana', 'Cherry', 'Water melon', 'pine apple', 'orange']

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)

['Apple', 'Banana', 'Cherry', 'pomegrante', 'Water melon', 'pine apple',


'grapes']

In [155… fruits

Out[155… ['Apple',
'Banana',
'Cherry',
'pomegrante',
'Water melon',
'pine apple',
'grapes']

In [ ]:

4.pop()-removes values in the list based on index value , by


default its[-1]
In [156… fruits=['Apple', 'Banana', 'Cherry', 'pomegrante', 'Water melon', 'pine ap
print(fruits)

['Apple', 'Banana', 'Cherry', 'pomegrante', 'Water melon', 'pine apple',


'orange']

In [157… fruits.pop() #by default it's -1


fruits

Out[157… ['Apple', 'Banana', 'Cherry', 'pomegrante', 'Water melon', 'pine apple']

In [158… fruits.pop(4)
fruits

Out[158… ['Apple', 'Banana', 'Cherry', 'pomegrante', 'pine apple']

In [159… fruits.pop(-3)
fruits

Out[159… ['Apple', 'Banana', 'pomegrante', 'pine apple']

In [ ]:

5.remove()-remove is used to remove a value from the list if


the value is known but not it's index
In [160… fruits=['Apple', 'Banana', 'Cherry', 'pomegrante', 'Water melon', 'pine ap
print(fruits)

['Apple', 'Banana', 'Cherry', 'pomegrante', 'Water melon', 'pine apple',


'orange']

In [161… fruits.remove("Water melon")


fruits

Out[161… ['Apple', 'Banana', 'Cherry', 'pomegrante', 'pine apple', 'orange']

In [162… fruits.remove("grapes") # try removing an item not in list and observe

--------------------------------------------------------------------------
-
ValueError Traceback (most recent call las
t)
Cell In[162], line 1
----> 1 fruits.remove("grapes")

ValueError: list.remove(x): x not in list

In [ ]:

6.del - used to remove values from a list based on their


indexing position using del keyword
In [163… fruits=["Apple","mango","water melon","banana"]
fruits

Out[163… ['Apple', 'mango', 'water melon', 'banana']

In [164… del fruits[1]


fruits

Out[164… ['Apple', 'water melon', 'banana']

In [165… del fruits[-1]


fruits

Out[165… ['Apple', 'water melon']

In [166… fruits

Out[166… ['Apple', 'water melon']

In [ ]:

7.clear()-this method removes all the elements and makes


the list empty
In [167… fruits=['water melon','grapes','banana','apple']
fruits

Out[167… ['water melon', 'grapes', 'banana', 'apple']

In [168… len(fruits)

Out[168… 4

In [169… fruits.clear()
In [170… len(fruits)

Out[170… 0

In [ ]:

8.count()-to look at the no of occurences of an element in


the list
In [171… n=[1,2,3,4,5,4,6,4,7,8,9,6,10,'Apple','Banana','Apple']

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

9.index-to look at the index position of the first occurence of


an element
In [177… n=[1,2,3,4,5,4,6,4,7,8,9,6,10]

In [178… n

Out[178… [1, 2, 3, 4, 5, 4, 6, 4, 7, 8, 9, 6, 10]

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)

ValueError: 6 is not in list

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]

In [187… q[::-1] #temporarily chamges

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 [190… q.reverse() # double reversing will gives the original list

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]

In [194… q.sort() # defaulit sort is ascending order


q

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 [196… fruits=["Apple","orange","banana","grapes","cherry","water melon"]


fruits

Out[196… ['Apple', 'orange', 'banana', 'grapes', 'cherry', 'water melon']

In [197… fruits.sort()
fruits

Out[197… ['Apple', 'banana', 'cherry', 'grapes', 'orange', 'water melon']

In [198… fruits.sort(reverse=True)
fruits

Out[198… ['water melon', 'orange', 'grapes', 'cherry', 'banana', 'Apple']

In [199… fruits.sort(key=len)
fruits

Out[199… ['Apple', 'orange', 'grapes', 'cherry', 'banana', 'water melon']

In [200… fruits.sort(key=len,reverse=True)
fruits

Out[200… ['water melon', 'orange', 'grapes', 'cherry', 'banana', 'Apple']

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

1. Add 'basketball' to the end of the list.


2. Insert 'volleyball' at index 2.
3. Add 'kabaddi' and 'rugby' to the list in one step.
4. Remove 'tennis' from the list.
5. Remove the last item from the list and store it in a variable.
6. Remove the item at index 1 and print what was removed.
7. Find and print the index of 'hockey'.
8. Add 'cricket' again to the list and count how many times it appears.
9. Sort the list in alphabetical order.
10. Reverse the order of the list.
11. Clear all elements from the original list.

In [204… sports=["cricket","football","tennis","hockey","badminton"]

In [205… # Add 'basketball' to the end of the list


sports

Out[205… ['cricket', 'football', 'tennis', 'hockey', 'badminton']

In [206… sports.append("basketball") # add to the end of list


sports

Out[206… ['cricket', 'football', 'tennis', 'hockey', 'badminton', 'basketball']

In [207… # Insert 'volleyball' at index 2


sports.insert(2,"volleyball")
sports

Out[207… ['cricket',
'football',
'volleyball',
'tennis',
'hockey',
'badminton',
'basketball']

In [208… # Add 'kabaddi' and 'rugby' to the list in one step


sports.extend(["kabaddi","ruggy"])
sports
Out[208… ['cricket',
'football',
'volleyball',
'tennis',
'hockey',
'badminton',
'basketball',
'kabaddi',
'ruggy']

In [209… # Remove 'tennis' from the list


sports.remove("tennis")
sports

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 [212… # Find and print the index of 'hockey'


print(sports)
sports.index("hockey")

['cricket', 'volleyball', 'hockey', 'badminton', 'basketball', 'kabaddi']


Out[212… 2

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

In [216… # Reverse the order of the list


sports.reverse()
sports

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 [219… # Clear all elements from the original list


sports.clear()

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)

(100, 'pencil', 2.001, True)

In [223… type(t1) # to check data type

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

Out[226… (100, 'pencil', 2.001, True)

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

TypeError: 'tuple' object does not support item assignment

In [228… t1[-1] #we can access using index

Out[228… True

In [229… t2=(600,"Good morning",(30,-2,"Apple"),[0.001,"python",-10])

In [230… t2[3]

Out[230… [0.001, 'python', -10]

In [231… t2[-1].append(200) # we can add items to the list,though it's a tuple-we


t2
Out[231… (600, 'Good morning', (30, -2, 'Apple'), [0.001, 'python', -10, 200])

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

Out[236… (100, 'pencil', 2.001, True)

In [237… t2

Out[237… (600, 'Good morning', (30, -2, 'Apple'), [0.001, 'python', -10])

In [ ]:

tuple declaraation

How to add elements in tuple ?- only count and index but


can't add,delete,modify
In [238… t3=(100,'hello',2.001,True,100,2.001,True,100)
t3

Out[238… (100, 'hello', 2.001, True, 100, 2.001, True, 100)

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

['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr_


_', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__',
'__getattribute__', '__getitem__', '__getstate__', '__gt__', '__hash__',
'__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le
__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '_
_reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__s
etitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear',
'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse',
'sort']

In [247… print(dir(list)[-15:])

['__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'cl


ear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reve
rse', 'sort']

In [248… print(dir(tuple))

['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr_


_', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribut
e__', '__getitem__', '__getnewargs__', '__getstate__', '__gt__', '__hash_
_', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__l
t__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__re
pr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook
__', 'count', 'index']

In [249… print(dir(tuple)[-6:])

['__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'ind


ex']

sorted
In [250… t=(3,4,7,9,1,0,-1,-100)
t

Out[250… (3, 4, 7, 9, 1, 0, -1, -100)

In [251… sorted(t) # directly we don't have method for sorting but we can do it wi

Out[251… [-100, -1, 0, 1, 3, 4, 7, 9]

In [252… t # original tuple remain same

Out[252… (3, 4, 7, 9, 1, 0, -1, -100)

In [253… sorted_tu=sorted(t)
sorted_tu # we can assign it to variable and can make it permanent

Out[253… [-100, -1, 0, 1, 3, 4, 7, 9]


In [254… fruits=["Apple","orange","banana","grapes","cherry","water melon"]
sorted(fruits) # for temporary sort

Out[254… ['Apple', 'banana', 'cherry', 'grapes', 'orange', 'water melon']

sort by length
sorted(tuple_name,key=len)

In [255… fruits_tuple=("apple","orange","banana","grapes","cherry","water melon","k


sorted(fruits_tuple,key=len)

Out[255… ['kiwi', 'apple', 'orange', 'banana', 'grapes', 'cherry', 'water melon']

packing and unpacking


In [256… t1=(100,'hello',2.001)
x,y,z=t1 #unpacking

In [257… x

Out[257… 100

In [258… y

Out[258… 'hello'

In [259… z

Out[259… 2.001

In [260… t1

Out[260… (100, 'hello', 2.001)

In [261… a='welcome'
b=45
c=200
d=False
t1= a,b,c,d #packing

In [262… t1

Out[262… ('welcome', 45, 200, False)

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

Out[267… (100, -1, 2.001, 2000, -0.111)

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

Class Excercise on Tuple


data = ("John", 25, "Developer", 75000.0, ("Python", "Java"))
Questions on This Tuple

🔹 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?

🔹 5. Nested Tuple Access


Access "Python" from data
Add a new skill to the inner tuple – What challenge will you face?

🔹 6. Tuple with Single Element


What is the type of single = ("John")?
Fix it so single becomes a tuple with one element.

In [274… data = ("John", 25, "Developer", 75000.0, ("Python", "Java"))

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

Out[280… ('John', 25, 'Developer')

In [281… data[0:len(data)-1]

Out[281… ('John', 25, 'Developer', 75000.0)

🔹 4. Immutability Test
Try modifying data[1] = 30
What happens?

In [282… data[0]=30 # It rises an error as tuples are immutable

--------------------------------------------------------------------------
-
TypeError Traceback (most recent call las
t)
Cell In[282], line 1
----> 1 data[0]=30

TypeError: 'tuple' object does not support item assignment

🔹 5. Nested Tuple Access


Access "Python" from data
Add a new skill to the inner tuple – What challenge will you face?

In [283… data[4][0]

Out[283… 'Python'

In [284… data[4].append('new skill')

--------------------------------------------------------------------------
-
AttributeError Traceback (most recent call las
t)
Cell In[284], line 1
----> 1 data[4].append('new skill')

AttributeError: 'tuple' object has no attribute 'append'

🔹 6. Tuple with Single Element


What is the type of single = ("John")?
Fix it so single becomes a tuple with one element

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

In [289… for n in "Innomatics":


print(n,end=" ")

I n n o m a t i c s

In [290… for n in "Kasi Reddy":


print(n,end=" ")

K a s i R e d d y

In [292… for n in "Kasi Reddy":


print(n,end=",")

K,a,s,i, ,R,e,d,d,y,

In [293… len("")

Out[293… 0

In [294… len(" ")

Out[294… 1

In [296… len(" ")


Out[296… 2

In [297… fruits=['apple','mango','banana','water melon','pine apple','kiwi']


fruits

Out[297… ['apple', 'mango', 'banana', 'water melon', 'pine apple', 'kiwi']

In [298… for i in fruits:


print(i)

apple
mango
banana
water melon
pine apple
kiwi

In [299… t_sort=[100,-0.01,-12,99,101]
t_sort

Out[299… [100, -0.01, -12, 99, 101]

In [300… for fruit in t_sort:


print(fruit+100) # by default prints in a new line

200
99.99
88
199
201

In [301… for fruit in t_sort:


print(fruit+100,end=" ") # prints in same line with spacing provided

200 99.99 88 199 201

In [302… for fruit in t_sort:


print(fruit+100,end=" ")

200 99.99 88 199 201

Problems on if_else and elif


1.Given list of marks and save the grades in a list

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

2.Given a list of numbers,save "Even" and "Odd" to another list


m=[30,11,66,73,43,55]
['even','odd','even','odd','odd','odd']

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

Even = [30, 66],Odd=[11, 73, 43, 55]

4.Given the marks,add them to lists passsed or failed


marks=[56,87,23,90,34,48]

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

m : 56, Passed : [56],Failed : []


m : 87, Passed : [56, 87],Failed : []
m : 23, Passed : [56, 87],Failed : [23]
m : 90, Passed : [56, 87, 90],Failed : [23]
m : 34, Passed : [56, 87, 90],Failed : [23, 34]
m : 48, Passed : [56, 87, 90, 48],Failed : [23, 34]

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

Passed : [56, 87, 90, 48],Failed : [23, 34]

5.Create a list of squares of first 10 natural numbers

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]

6.For a given list of numbers


square it if it is even
otherwise cube it

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

sq_cubes=[59319, 205379, 576, 166375, 1764, 5776, 1]

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

Nested for loop : A loop inside another


loop
In [9]: for i in range(3):
for j in range(2):
print(f"i={i},j={j}")

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

1.Given list of marks and save the grades in a list

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

i:0,marks[0] : 56,grades : ['C']


i:1,marks[1] : 87,grades : ['C', 'A']
i:2,marks[2] : 23,grades : ['C', 'A', 'Failed']
i:3,marks[3] : 90,grades : ['C', 'A', 'Failed', 'A']
i:4,marks[4] : 34,grades : ['C', 'A', 'Failed', 'A', 'Failed']
i:5,marks[5] : 48,grades : ['C', 'A', 'Failed', 'A', 'Failed', 'D']

2.Given a list of numbers,save "Even" and "Odd" to another list


m=[30,11,66,73,43,55]
['even','odd','even','odd','odd','odd']

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]

3.For a list of fruits


If the string is starting with vowel add it to vowels list
Otherwise add it to constatnts list

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

4.Given a list of strings


if they are palindrome ,add them to palindrome list
otherwise add them to not_palindrome list

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

In [7]: 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

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

In [8]: nums=input("Enter numbers seperated by comma : ").split(",")


product=1
for i in nums:
product=product*int(i)
print(product)

1
2
6
24
120

In [9]: nums=input("Enter numbers seperated by comma : ").split(",")


i=1
product=1
while i <len(nums):
product=product*int(nums[i])
print(product)
i=i+1

2
6
24
120

In [10]: nums=input("Enter numbers seperated by comma : ").split(",")


pr_E=1
pr_O=1
for i in nums:
if int(i)%2==0:
pr_E=pr_E*int(i)
else:
pr_O=pr_O*int(i)
print(i,pr_E,pr_O)

1 1 1
2 2 1
3 2 3
4 8 3
5 8 15
6 48 15

In [11]: nums=input("Enter numbers seperated by comma : ").split(",")


pr_E=1
pr_O=1
i=0
while i<len(nums):
if int(nums[i])%2==0:
pr_E=pr_E*int(nums[i])
else:
pr_O=pr_O*int(nums[i])
i=i+1
print(i,pr_E,pr_O)

1 1 1
2 2 1
3 2 3
4 8 3
5 8 15
6 48 15

In [13]: n=int(input("Enter a number : "))


product=1
for i in range(1,n+1):
product=product*i
print(f'Factorial of {i} = {product}')

Factorial of 1 = 1
Factorial of 2 = 2
Factorial of 3 = 6
Factorial of 4 = 24
Factorial of 5 = 120

In [15]: n=int(input("Enter a number : "))


product=1
for i in range(1,n+1):
product=product*i
print(f'Factorial of {i} = {product}')

Factorial of 5 = 120

In [16]: n=int(input("Enter a number : "))


i=0
product=1
while i<n:
product=product*(i+1)
print(f'Factorial of {i+1} = {product}')
i+=1

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

Loop Control flow statements


pass : The pass keyword is used in the place of a block which is required
syntatically but not logically
break : The break keyword is used to terminate the loop altogether
continue : The continue keyword is used to terminate the current
execution

break : The break keyword is used to


terminate the loop altogether
1.Terminate the loop if negative number is encountered

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

2.For a given list of words print till a palindrome is found


string=
['Lion','monkey','License','Civic','Silence','Malayalam']

Steps to solve

1.Loop through the items in a list


2.If the string is not palindrome,print the string
3.if the string is palindrome,break the loop

In [20]: string = ['Lion','monkey','License','Civic','Silence','Malayalam']


for i in string:
if i.lower()==i.lower()[::-1]:
print(f'palindrome is encountered : {i}')
break
print(i)

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

continue : The continue keyword is used to


terminate the current execution

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.

In [8]: for i in range(5):


if i==2:
pass
print(i)

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)

Out[10]: range(0, 10)

1.Print numbers using range()

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.print numbers using range and for loop

In [13]: for i in range(10):


print(i,end=" ")
0 1 2 3 4 5 6 7 8 9

3.print even numbers

In [18]: for i in range(2,32,2):


print(i,end=",")

2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,

4.print only even numbers

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

5.Print number and it's type even or odd

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)


looping through tuple and print in same line

In [31]: for i in data_t:


print(i,end=" ")

10 20 30 40 20 New york 10 20

Print last 3 elements

In [27]: data_t[-3:]

Out[27]: ('New york', 10, 20)

Count and Index

In [28]: data_t.count(10)

Out[28]: 2

In [29]: data_t.count(20)

Out[29]: 3

In [30]: data_t.index(20,2,) #we can ignore stop value

Out[30]: 4

Website to practice python : https://pynative.com/

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

Out[32]: {-10, 100, 20, True, 'apple'}

In [33]: s={-10,100,'Hello',True,0.2001}
type(s)

Out[33]: set

In [34]: print(s)
{0.2001, True, 100, -10, 'Hello'}

Checking for duplicates


Duplicates will not be printed in output

In [35]: s={-10,100,'Hello',True,0.2001,10,100,'Hello'}
print(s,len(s))

{0.2001, True, 100, -10, 10, 'Hello'} 6

in set 0 and 1 falls as '1-True,0-False"--> considers as duplicates and fisrt occurence is


retained and remaining duplicates are removed

In [36]: e={-20,0,200,True,"Cricket",1,False}
e

Out[36]: {-20, 0, 200, 'Cricket', True}

In [37]: e={-20,False,200,1,"Cricket",0,True}
e

Out[37]: {-20, 1, 200, 'Cricket', False}

In [38]: v={20,-2,True,'new york',(-100,200)}


print(v)
len(v)

{True, 'new york', 20, (-100, 200), -2}


Out[38]: 5

In [39]: v={20,-2,True,'new york',(-100,200),['pencil',3.04]}


print(v) # rises error

--------------------------------------------------------------------------
-
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: unhashable type: 'list'

we can't add a mutable types to set i.e list,set,dictionary


In [40]: v={20,-2,True,'new york',(-100,200),{'pencil',3.04}}
print(v) #raises error

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

Mutable Types : list,set,dictionary

immutable Types : int,float,bool,string,tuple

in set the first occcurence is retained and remaining


duplicates are removed
integer 1 and boolean True are duplicates
integer 0 and boolean False are duplicates

Set only allows immutable data types as members

immutable types
'int','float','str','boolean','tuple'
mutable types
'list','set','dictionary'

Built in methods of set


In [41]: d={10,-0.01,20,'apple',1}
print(d)

{1, -0.01, 20, 10, 'apple'}

In [42]: len(d)

Out[42]: 5

1.add()
In [43]: d.add(99) # adding single item to a set
print(d)

{1, 99, -0.01, 20, 10, 'apple'}

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 [51]: d.update({True,-3.45,10,56}) #providing duplicates

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

Out[55]: {-199, -150, -0.01, 21, 34, 60}

In [56]: sorted(d) #temporarily sorted

Out[56]: [-199, -150, -0.01, 21, 34, 60]

In [57]: print(d)

{34, -0.01, 21, -199, -150, 60}

4.discard()
if the value is not there,discord will not show any error

In [58]: print(d)

{34, -0.01, 21, -199, -150, 60}


In [59]: len(d)

Out[59]: 6

In [60]: a=d.discard(21)
print(a)

None

In [61]: print(d)

{34, -0.01, -199, -150, 60}

In [62]: len(d)

Out[62]: 5

In [63]: d.discard(125) # not rises an error even if value is not there

In [ ]:

5.remove()
if the value is not there,then it generates error

In [64]: d={34, -0.01, -199, -150, 60}


print(d)

{34, -0.01, -199, -150, 60}

In [65]: d.remove(60)

In [66]: print(d)

{34, -0.01, -199, -150}

In [67]: d.remove(125) #rises an error as there's no value

--------------------------------------------------------------------------
-
KeyError Traceback (most recent call las
t)
Cell In[67], line 1
----> 1 d.remove(125)

KeyError: 125

if the items exists in set


discord and remove methods will remove item

if the item is not exist


discord will not rise error
remove rises an error
6.pop()
pop is used to delete items from the set
we can't predict the wwhich item will be delete because pop in unindexed
pop() will delete items randomnly

In [68]: print(d)

{34, -0.01, -199, -150}

In [69]: d.pop()

Out[69]: 34

In [70]: print(d)

{-0.01, -199, -150}

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

creating empty set


In [78]: s1={} # not correct way of creating emtty set
type(s1)

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)

Out[3]: {-199, -1, 1, 25, 100, 125}

In [4]: s1|s2

Out[4]: {-199, -1, 1, 25, 100, 125}

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

Out[7]: {25, 100}

In [8]: s1.difference(s2)

Out[8]: {25, 100}


In [9]: s2-s1

Out[9]: {-199, 125}

In [ ]:

4.Symmetric difference
In [10]: s1.symmetric_difference(s2)

Out[10]: {-199, 25, 100, 125}

In [11]: s1^s2

Out[11]: {-199, 25, 100, 125}

Aggregate function
In [12]: s1

Out[12]: {-1, 1, 25, 100}

In [13]: s2

Out[13]: {-199, -1, 1, 125}

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.

attendees_A = {"Alice", "Bob", "Charlie", "Diana", "Bob", "Eve"}

attendees_B = {"Charlie", "Frank", "Grace", "Eve", "Heidi"}

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?

3. Update attendees_A with new names: ["Judy", "Mallory"] .

4. Discard "Bob" from attendees_A . What happens if "Bob" is not present?

5. Remove "Charlie" from attendees_A . How is remove() different from


discard() ?

6. Discard "Trent" from attendees_A (not in the set). Does this cause an
error?

7. Remove "Trent" from attendees_A . What happens?

8. Sort and display the names in attendees_A .

9. Perform these set operations between attendees_A and attendees_B :

Union
Intersection
Difference (only in attendees_A )

10. Clear attendees_A . What will the set contain after this?

In [20]: attendees_A = {"Alice", "Bob", "Charlie", "Diana", "Bob", "Eve"}

attendees_B = {"Charlie", "Frank", "Grace", "Eve", "Heidi"}

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

Out[21]: {'Alice', 'Bob', 'Charlie', 'Diana', 'Eve'}

In [22]: # duplicates will be removed and not shown in output

In [23]: # Add "Ivan" to attendees_A. What does the set look like afterward?
attendees_A.add("Ivan")
attendees_A

Out[23]: {'Alice', 'Bob', 'Charlie', 'Diana', 'Eve', 'Ivan'}


In [24]: # Update attendees_A with new names: ["Judy", "Mallory"]
attendees_A.update( ["Judy", "Mallory"])
attendees_A

Out[24]: {'Alice', 'Bob', 'Charlie', 'Diana', 'Eve', 'Ivan', 'Judy', 'Mallory'}

In [25]: # Discard "Bob" from attendees_A. What happens if "Bob" is not present?
attendees_A.discard("Bob")
attendees_A

Out[25]: {'Alice', 'Charlie', 'Diana', 'Eve', 'Ivan', 'Judy', 'Mallory'}

even if "Bob" is not present,it will not throw error

In [26]: # Remove "Charlie" from attendees_A. How is remove() different from discar
attendees_A.remove("Charlie")
attendees_A

Out[26]: {'Alice', 'Diana', 'Eve', 'Ivan', 'Judy', 'Mallory'}

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

Out[27]: {'Alice', 'Diana', 'Eve', 'Ivan', 'Judy', 'Mallory'}

No,it's not showing an error

In [28]: # Remove "Trent" from attendees_A. What happens?


attendees_A.remove("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'

It's throwing an error as 'trent' not there in set

In [29]: # Sort and display the names in attendees_A.


sorted(attendees_A)

Out[29]: ['Alice', 'Diana', 'Eve', 'Ivan', 'Judy', 'Mallory']

In [30]: # Perform these set operations between attendees_A and attendees_B:


# 1.Union
# 2.Intersection
# 3.Difference (only in attendees_A)
attendees_A|attendees_B

Out[30]: {'Alice',
'Charlie',
'Diana',
'Eve',
'Frank',
'Grace',
'Heidi',
'Ivan',
'Judy',
'Mallory'}

In [31]: attendees_A & attendees_B

Out[31]: {'Eve'}

In [32]: attendees_A - attendees_B

Out[32]: {'Alice', 'Diana', 'Ivan', 'Judy', 'Mallory'}

In [33]: attendees_B - attendees_A

Out[33]: {'Charlie', 'Frank', 'Grace', 'Heidi'}

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

Out[36]: {'one': 1, 2: 'Two', 'fruit': 'Apple'}

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

In [43]: r[(34.02,45.001)] #indexing

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

TypeError: unhashable type: 'list'

NOTE : keys should be only immutable types

In [45]: d={2:"Two",'Fruit':"Apple",'One':1,'Fruit':"Water melon",2:"India"}


d

Out[45]: {2: 'India', 'Fruit': 'Water melon', 'One': 1}

2.Adding,Modifying and retrieving


In [46]: marks={'Alice':87,'Ben':67,'Charlie':90}
marks

Out[46]: {'Alice': 87, 'Ben': 67, 'Charlie': 90}

adding a new key-value pair


In [54]: marks['Deeksha']=87
marks

Out[54]: {'Alice': 60, 'Ben': 67, 'Charlie': 90, 'Deeksha': 87}

updating an existing key-value pair


In [55]: marks['Alice']=60
marks

Out[55]: {'Alice': 60, 'Ben': 67, 'Charlie': 90, 'Deeksha': 87}

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'

Here,we will get an error if not there.So,in order of not to get


error use get() method for retrieving
In [58]: marks.get('Alice',"key doesn't exist")

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 [59]: marks={'Alice': 60, 'Ben': 67, 'Charlie': 90, 'Deeksha': 87}


marks

Out[59]: {'Alice': 60, 'Ben': 67, 'Charlie': 90, 'Deeksha': 87}

In [60]: marks.keys()

Out[60]: dict_keys(['Alice', 'Ben', 'Charlie', 'Deeksha'])

In [61]: for k in marks.keys(): # looping through keys


print(k)

Alice
Ben
Charlie
Deeksha

In [62]: marks.values()

Out[62]: dict_values([60, 67, 90, 87])

In [63]: for k in marks.values(): # looping through values


print(k,end=" ")

60 67 90 87

In [64]: marks.items()

Out[64]: dict_items([('Alice', 60), ('Ben', 67), ('Charlie', 90), ('Deeksha', 8


7)])

In [65]: for k in marks.items(): #looping through items


print(k,end=" ")

('Alice', 60) ('Ben', 67) ('Charlie', 90) ('Deeksha', 87)

In [66]: for k,v in marks.items(): # looping through keys and values


print(f'Key : {k},value = {v}')

Key : Alice,value = 60
Key : Ben,value = 67
Key : Charlie,value = 90
Key : Deeksha,value = 87

In [67]: for k,v in marks.items(): #accessing keys alone


print(k)

Alice
Ben
Charlie
Deeksha

In [68]: for k,v in marks.items(): #accessing keys values


print(v)
60
67
90
87

4.Basic operations
Membership operator
1. in
2. not in

In [69]: l=[56,67,90,75]
l

Out[69]: [56, 67, 90, 75]

In [70]: 'soccer' in l

Out[70]: False

In [71]: 67 in l

Out[71]: True

In [72]: 'soccer' not in l

Out[72]: True

In [73]: marks=marks={'Alice': 60, 'Ben': 67, 'Charlie': 90, 'Deeksha': 87}


marks

Out[73]: {'Alice': 60, 'Ben': 67, 'Charlie': 90, 'Deeksha': 87}

In [74]: 'Charlie' in marks

Out[74]: True

In [75]: 67 in marks # by default it checks only keys

Out[75]: False

In [76]: 67 in marks.values() #specifically we have to mention marks.values() to ch

Out[76]: True

In [77]: 80 not in marks

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

5.Removing items from dictionary

pop()

In [82]: marks={'Alice': 60, 'Ben':80,'Charlie': 90, 'Deeksha': 87}


marks

Out[82]: {'Alice': 60, 'Ben': 80, 'Charlie': 90, 'Deeksha': 87}

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 [85]: pop_item=marks.pop('david',"key not exist")


pop_item

Out[85]: 'key not exist'

popitem()-to remove the last key-value pair

In [86]: marks

Out[86]: {'Alice': 60, 'Charlie': 90, 'Deeksha': 87}


In [87]: last_item=marks.popitem()
last_item

Out[87]: ('Deeksha', 87)

del - using del to remove

In [88]: marks={'Alice': 60, 'Charlie': 90}


marks

Out[88]: {'Alice': 60, 'Charlie': 90}

In [89]: del marks['Alice']

In [90]: marks

Out[90]: {'Charlie': 90}

6.Some dictionary methods

fromkeys()
In [91]: l=[56,'cricket','Lion']
l

Out[91]: [56, 'cricket', 'Lion']

In [92]: q=dict.fromkeys(l,'Initial value')


q

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)

Out[94]: [('Alice', 89), ('Ben', 78), ('Charlie', 67), ('David', 56)]

In [95]: d=zip(k,v)
dict(d)

Out[95]: {'Alice': 89, 'Ben': 78, 'Charlie': 67, 'David': 56}

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)

Out[97]: {('Alice', 89), ('Ben', 78), ('Charlie', 67), ('David', 56)}

In [98]: k=['Alice','Ben','Charlie','David']
v=[89,78,67] # shortage of items

In [99]: dict(zip(k,v))

Out[99]: {'Alice': 89, 'Ben': 78, 'Charlie': 67}

In [100… k=['Alice','Ben','Charlie']
v=[89,78,67,56] # shortage of items

In [101… dict(zip(k,v))

Out[101… {'Alice': 89, 'Ben': 78, 'Charlie': 67}

In [102… list(zip(k,v))

Out[102… [('Alice', 89), ('Ben', 78), ('Charlie', 67)]

unpacking

In [103… fruits={'Apple':80,'Orange':45}
vegetables={'Tomato':30,'Onion':50}
combined={**fruits,**vegetables}
combined

Out[103… {'Apple': 80, 'Orange': 45, 'Tomato': 30, 'Onion': 50}

Cls-Exercise

🧠 Practice Questions on Python Dictionary


1. Create a dictionary student with keys "name" , "age" , "grade" , and
assign any values.
2. Add a new key "subject" with value "Math" to the dictionary.
3. Update the "grade" key to a new value.
4. Delete the "age" key from the dictionary.
5. Use get() to access the value of "name" safely.
6. Try accessing a non-existent key with get() and provide a default message.
7. Check if the key "grade" exists in the dictionary.
8. Get all keys, values, and items from the dictionary.
9. Loop through the dictionary and print keys and values.
10. Pop a key from the dictionary and store its value in a variable.
11. Create a dictionary from two lists: keys = ['a', 'b'] and vals = [1,
2] .
In [104… # Create a dictionary student with keys "name", "age", "grade", and assign
student={"name":'Srujan', "age":21, "grade":'O'}
student

Out[104… {'name': 'Srujan', 'age': 21, 'grade': 'O'}

In [105… # Add a new key "subject" with value "Math" to the dictionary.
student["subjecct"]="Math"
student

Out[105… {'name': 'Srujan', 'age': 21, 'grade': 'O', 'subjecct': 'Math'}

In [106… # Update the "grade" key to a new value


student["grade"]='A+'
student

Out[106… {'name': 'Srujan', 'age': 21, 'grade': 'A+', 'subjecct': 'Math'}

In [107… # Delete the "age" key from the dictionary.


student.pop('age') # del student['age']
student

Out[107… {'name': 'Srujan', 'grade': 'A+', 'subjecct': 'Math'}

In [108… # Use get() to access the value of "name" safely.


student.get('name')

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[109… 'key not exist'

In [110… # Check if the key "grade" exists in the dictionary.


'grade' in student

Out[110… True

In [111… # Get all keys, values, and items from the dictionary.
student.keys()

Out[111… dict_keys(['name', 'grade', 'subjecct'])

In [112… student.values()

Out[112… dict_values(['Srujan', 'A+', 'Math'])

In [113… student.items()

Out[113… dict_items([('name', 'Srujan'), ('grade', 'A+'), ('subjecct', 'Math')])

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

Out[117… {'a': 1, 'b': 2}

clear()

In [118… student={"name":'Srujan', "age":21, "grade":'O'}


len(student)

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

In [122… for index,item in enumerate(l,):


print(index,item)

0 56
1 lion
2 cricket

In [123… for index,item in enumerate(l,1):


print(f'Index : {index},Item : {item}')
Index : 1,Item : 56
Index : 2,Item : lion
Index : 3,Item : cricket

In [124… for index,item in enumerate(l,3):


print(f'Index : {index},Item : {item}')

Index : 3,Item : 56
Index : 4,Item : lion
Index : 5,Item : cricket

In [125… for index,item in enumerate(l,-3):


print(f'Index : {index},Item : {item}')

Index : -3,Item : 56
Index : -2,Item : lion
Index : -1,Item : cricket

List and tuple some more concepts


copy
In [126… l1=[34,10,20,'Hi']

In [127… l2=l1 #copying using assignment operator

In [128… l1

Out[128… [34, 10, 20, 'Hi']

In [129… l2

Out[129… [34, 10, 20, 'Hi']

In [130… id(l1),id(l2)

Out[130… (2499555444288, 2499555444288)

In [131… l1.append(100)

In [132… l1

Out[132… [34, 10, 20, 'Hi', 100]

In [133… l2

Out[133… [34, 10, 20, 'Hi', 100]

Chnages made to one list is affecting another list.So,no use of


asssigning to another varaible

Shallow copy
In [134… from copy import copy
e=[20,True,78,90,[45,-1,-10]]

In [135… w=e.copy() #shallow copy

In [136… e

Out[136… [20, True, 78, 90, [45, -1, -10]]

In [137… w

Out[137… [20, True, 78, 90, [45, -1, -10]]

In [138… id(e),id(w)

Out[138… (2499555625664, 2499556196480)

In [139… id(e[-1]),id(w[-1])

Out[139… (2499556201472, 2499556201472)

Both lists have different address,changes made to one list will not affect
the other

In [140… e.append(-199)

In [141… e

Out[141… [20, True, 78, 90, [45, -1, -10], -199]

In [142… w

Out[142… [20, True, 78, 90, [45, -1, -10]]

changes made to one list will not affects the other

In [143… w[-1]

Out[143… [45, -1, -10]

In [144… w[-1].append("Lion")

In [145… w

Out[145… [20, True, 78, 90, [45, -1, -10, 'Lion']]

In [146… e

Out[146… [20, True, 78, 90, [45, -1, -10, 'Lion'], -199]

In [147… id(e),id(w)

Out[147… (2499555625664, 2499556196480)


In [148… id(e[-1]),id(w[-2])

Out[148… (2499556294960, 140719446439128)

changes made to one nested list is seen in another list also,because


nested list shared the same address

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

Out[151… [20, True, 78, 90, [45, -1, -10, 'Lion']]

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 =,+=,-=,=,/=,%=,*=,//=

In [152… 2>3 and 3<4


#False and True
#False

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

In [157… a%b + a/c - a**b*c + 12


# 5%2 + 5/6 - 5**2*6 + 12
# 5%2 + 5/6 - 25*6 + 12
# 5%2 + 5/6 - 150 + 12
# 5%2 + 0.8333 - 150 + 12
# 1 + 0.8333 - 150 + 12
# 1.8333 - 150 + 12
# 1.8333 -138
# - 136.666666

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 [159… x="This is niva's pen"


print(x)

This is niva's pen

In [160… x

Out[160… "This is niva's pen"

In [161… x='This is "winter" season'


print(x)

This is "winter" season

In [162… x="This is niva's p" en 'hi'

Cell In[162], line 1


x="This is niva's p" en 'hi'
^
SyntaxError: invalid syntax

In [163… m='''This is multi-line string


created using triple quotes'''
print(m)

This is multi-line string


created using triple quotes

In [164… m="""This is multi-line string


created using triple quotes"""
print(m)

This is multi-line string


created using triple quotes

String methods :
Concatenation
In [165… i="Hello"
c="Good Morning"
i+" "+c

Out[165… 'Hello Good Morning'

In [166… i+c

Out[166… 'HelloGood Morning'

In [167… i*5

Out[167… 'HelloHelloHelloHelloHello'

In [168… (i+c)*5

Out[168… 'HelloGood MorningHelloGood MorningHelloGood MorningHelloGood MorningHel


loGood Morning'

In [169… i

Out[169… 'Hello'

In [170… c

Out[170… 'Good Morning'

In [173… i[4]="P" #strings are immutable

--------------------------------------------------------------------------
-
TypeError Traceback (most recent call las
t)
Cell In[173], line 1
----> 1 i[4]="P"

TypeError: 'str' object does not support item assignment

Indexing and slicing :


In [174… s = "Innomatics"

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'

In [184… l="PYTHON PROGRAM"


l

Out[184… 'PYTHON PROGRAM'

In [185… l[:2:1]+l[10::1] #PYGRAM

Out[185… 'PYGRAM'

In [186… l[13:10:-2]+"."+l[0:2] #MR.PY

Out[186… 'MR.PY'

Membership in string :
In [187… l="PYTHON PROGRAM"
l

Out[187… 'PYTHON PROGRAM'

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

Checking whether a string is palindrome or not ?

In [193… s=input("Enter a string : ")


if s==s[::-1]:
print(f'{s} is palindrome')
else :
print(f'{s} is not a palindrome')

malayalaM is not a palindrome

In [194… s=input("Enter a string : ")


if s.lower()==s[::-1].lower():
print(f'{s} is palindrome')
else :
print(f'{s} is not a palindrome')

malayalaM is palindrome

In [198… s="malayalaM"

In [199… s,s[::-1]

Out[199… ('malayalaM', 'Malayalam')

In [200… s.lower(),s[::-1].lower()

Out[200… ('malayalam', 'malayalam')

In [201… s.upper()

Out[201… 'MALAYALAM'

len() :
Returns no of characters

In [203… l='PYTHON PROGRAM'


len(l)

Out[203… 14

Note: In python,when we are trying to transform strings,the


change observed is only valid until that cell and isn't made
permanent.If we want the change to be made
permanent,reassign the back into the variable

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

Out[205… 'python is a programing and case sensitive language'

2.upper()
To convert the string into upper case letters

In [207… a.upper()

Out[207… 'PYTHON IS A PROGRAMING AND CASE SENSITIVE LANGUAGE'

3.capitalize():
To make the starting string in capital

In [208… a.capitalize()

Out[208… 'Python is a programing and case sensitive language'

4.title() :
if we want to make the first letter of each word in the string in capital

In [209… a.title()

Out[209… 'Python Is A Programing And Case Sensitive Language'

5.count() :
to count the no of occurences of a sub-string in the main string

In [210… a

Out[210… 'PyThoN is a PRograming And caSe SensItive LanguaGE'


In [212… a.count("And")

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 [222… a='PyThoN is a PRograming And caSe SensItive LanguaGE'


a

Out[222… 'PyThoN is a PRograming And caSe SensItive LanguaGE'

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 [223… a='PyThoN is a PRograming And caSe SensItive LanguaGE'


a

Out[223… 'PyThoN is a PRograming And caSe SensItive LanguaGE'

In [224… a.endswith("E")
Out[224… True

In [225… a.endswith("aGE")

Out[225… True

In [226… a.endswith("agE")

Out[226… False

In [227… a.endswith("And caSe SensItive LanguaGE")

Out[227… True

8.find() :
find() returns the index position of the starting character of the sub-string
returns -1 if not found

In [228… k='Innomatics Research Labs'


k

Out[228… 'Innomatics Research Labs'

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

In [234… k.find(" ")

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 [237… k='Innomatics Research Labs'


k

Out[237… 'Innomatics Research Labs'

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

ValueError: substring not found

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 [248… w='Python is a easy to learn programming..Python has english like syntax'


w

Out[248… 'Python is a easy to learn programming..Python has english like syntax'

In [249… w.replace("Python","Java")

Out[249… 'Java is a easy to learn programming..Java has english like syntax'

In [ ]:

12.strip() :
to remove any leading and trailing white spaces and new line characters

In [250… n=" Hello world "


n.strip()

Out[250… 'Hello world'

In [253… m="$$$$$$$$$ Hello world $$$$$"


m.strip('$')

Out[253… ' Hello world '

In [254… m="$$$$$$$$$ Hello world $$$$$"


m.strip('$ ')

Out[254… 'Hello world'

In [257… m=" $$$$$$$$$ Hello world $$$$$"


m.strip('$')

Out[257… ' $$$$$$$$$ Hello world '

In [258… m=" $$$$$$$$$ Hello world $$$$$ "


m.strip('$')
Out[258… ' $$$$$$$$$ Hello world $$$$$ '

In [259… m=" $$$$$$$$$ Hello world $$$$$"


m.strip(' $')

Out[259… 'Hello world'

In [260… m="$$$$$$$$$@ Hello world $$$$$"


m.strip('$')

Out[260… '@ Hello world '

In [261… m="$$$$$$$$$@ Hello world $$@$$$"


m.strip('$')

Out[261… '@ Hello world $$@'

In [262… m="$$$$$$$$$@ Hello world $$@$$$"


m.strip('$ @') # '$ @'are treated as a single characters and removed

Out[262… 'Hello world'

In [ ]:

13.split() :
splitting a string into sub-strings based on default delimter(space)

In [264… k='Innomatics Research Labs'


k

Out[264… 'Innomatics Research Labs'

In [265… k.split()

Out[265… ['Innomatics', 'Research', 'Labs']

In [266… k.split("a")

Out[266… ['Innom', 'tics Rese', 'rch L', 'bs']

In [269… k.split(" ")

Out[269… ['Innomatics Research Labs']

In [271… k.split(" ")

Out[271… ['Innomatics', 'Research', 'Labs']

In [272… k.split('n',-1)

Out[272… ['I', '', 'omatics Research Labs']

In [277… k.split('a',1)
Out[277… ['Innom', 'tics Research Labs']

In [278… k.split('a',2)

Out[278… ['Innom', 'tics Rese', 'rch Labs']

In [280… k.split('a',-1) #default is maxsplit==-1

Out[280… ['Innom', 'tics Rese', 'rch L', 'bs']

PQS:

How to extract the domain name from the email string:


"[email protected]"?

From the string " Data Science ", apply strip() and then convert it to
uppercase.

In [282… "[email protected]".split('@')[-1]

Out[282… 'innomatics.in'

In [283… " Data Science ".strip().upper()

Out[283… 'DATA SCIENCE'

In [ ]:

🧠 Practice Questions on Lists, Tuples, Sets,


Dictionaries, and Strings

✅ List Questions
Q1. Given my_list = [1, 2, 3, 4, 5, 2, 3] ,
Remove duplicates and sort the list in descending order.

Q2. Given fruits = ['apple', 'banana', 'cherry'] ,


Add 'orange' to the list and then reverse the list.

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

Q4. Given details = ('John', 25, 'Engineer') ,


Convert the tuple into a list, update age to 26, and convert it back to a tuple.

✅ Set Questions
Q5. Given set1 = {1, 2, 3, 4} and set2 = {3, 4, 5, 6} ,
Find union, intersection, and difference of both sets.

Q6. Given nums = {10, 20, 30} ,


Add 40 to the set and remove 20 using set methods.

✅ Dictionary Questions
Q7. Given student = {'name': 'Alice', 'age': 22, 'course':
'Math'} ,
Update age to 23 and add a new key 'grade' with value 'A' .

Q8. Given data = {'a': 1, 'b': 2, 'c': 3} ,


Remove key 'b' , check if 'c' exists, and get the list of all keys.

✅ String Questions
Q9. Given sentence = " Python is FUN " ,
Remove leading/trailing spaces and convert the string to lowercase.

Q10. Given msg = "hello world" ,


Replace 'world' with 'Python' and capitalize the first letter of the string.

List

In [284… # Q1. Given my_list = [1, 2, 3, 4, 5, 2, 3],


# Remove duplicates and sort the list in descending order.
my_list = [1, 2, 3, 4, 5, 2, 3]

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 [287… # Given fruits = ['apple', 'banana', 'cherry'],


# Add 'orange' to the list and then reverse the list.
fruits = ['apple', 'banana', 'cherry']
fruits.append("orange")
fruits

Out[287… ['apple', 'banana', 'cherry', 'orange']

In [288… fruits[::-1]

Out[288… ['orange', 'cherry', 'banana', 'apple']


Tuple

In [289… # Given data = (10, 20, 30, 40, 50),


# Check if 30 is present in the tuple and count how many times it appears
data = (10, 20, 30, 40, 50)
30 in data

Out[289… True

In [290… data.count(30)

Out[290… 1

In [291… # Given details = ('John', 25, 'Engineer'),


# Convert the tuple into a list, update age to 26, and convert it back to
details = ('John', 25, 'Engineer')
d_list=list(details)
d_list

Out[291… ['John', 25, 'Engineer']

In [292… d_list[1]=26
d_list

Out[292… ['John', 26, 'Engineer']

In [293… d_tuple=tuple(d_list)
d_tuple

Out[293… ('John', 26, 'Engineer')

Set

In [294… # Given set1 = {1, 2, 3, 4} and set2 = {3, 4, 5, 6},


# Find union, intersection, and difference of both sets.
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

In [295… set1 | set2

Out[295… {1, 2, 3, 4, 5, 6}

In [296… set1 & set2

Out[296… {3, 4}

In [297… set1 - set2

Out[297… {1, 2}

In [298… set1 ^ set2

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

Out[299… {10, 20, 30}

In [300… nums.add(40)
nums

Out[300… {10, 20, 30, 40}

In [301… nums.remove(20)
nums

Out[301… {10, 30, 40}

In [302… #### dict


# Given student = {'name': 'Alice', 'age': 22, 'course': 'Math'},
# Update age to 23 and add a new key 'grade' with value 'A'.
student = {'name': 'Alice', 'age': 22, 'course': 'Math'}
student

Out[302… {'name': 'Alice', 'age': 22, 'course': 'Math'}

In [303… student['age']=23
student['grade']='A'
student

Out[303… {'name': 'Alice', 'age': 23, 'course': 'Math', 'grade': 'A'}

In [304… # Q8. Given data = {'a': 1, 'b': 2, 'c': 3},


# Remove key 'b', check if 'c' exists, and get the list of all keys.
data = {'a': 1, 'b': 2, 'c': 3}
data.pop('b')

Out[304… 2

In [305… data

Out[305… {'a': 1, 'c': 3}

In [306… 'c' in data

Out[306… True

In [307… list(data.keys())

Out[307… ['a', 'c']

strings

In [308… # Given sentence = " Python is FUN ",


# Remove leading/trailing spaces and convert the string to lowercase.
sentence = " Python is FUN "
sentence.strip().lower()
Out[308… 'python is fun'

In [309… # Q10. Given msg = "hello world",


# Replace 'world' with 'Python' and capitalize the first letter of the str
msg = "hello world"
msg.replace("world","Python")

Out[309… 'hello Python'

In [ ]:

list Comprehension
In [ ]:

1.For a given list of nums,square it and save them into a list

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

Out[311… [1, 4, 9, 16, 25, 36, 49, 64, 81]

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

TypeError: list indices must be integers or slices, not str

In [317… nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]


sq = [k**2 for k in nums]
for num, s in zip(nums, sq):
print(f"{num} : {s}")

1 : 1
2 : 4
3 : 9
4 : 16
5 : 25
6 : 36
7 : 49
8 : 64
9 : 81

2.Given list of words reverse all words

In [318… words=['sports','vegetables','fruits','hotels']
rev_words=[i[::-1] for i in words]
rev_words

Out[318… ['strops', 'selbategev', 'stiurf', 'sletoh']

In [319… words=['sports','vegetables','fruits','hotels']
rev_words=words[::-1]
rev_words

Out[319… ['hotels', 'fruits', 'vegetables', 'sports']

3.Given list of words capitalize all


sports =
['cricket','soccer','badminton','basketball','volleyball']

In [320… sports = ['cricket','soccer','badminton','basketball','volleyball']


cap = [ i.capitalize() for i in sports]
cap

Out[320… ['Cricket', 'Soccer', 'Badminton', 'Basketball', 'Volleyball']

4.Given list of centigrage temperature,print farenheit temperature in a list


9
F = ∗ c + 32
5

In [321… c=[39,41,32,29,36]
F = [ round((9/5)*i+32,2) for i in c]
F

Out[321… [102.2, 105.8, 89.6, 84.2, 96.8]

5.Given list of numbers find square of each numbers(from math import


sqrt)

In [322… from math import sqrt


sqrt(9)
Out[322… 3.0

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]

In [325… from math import sqrt


n=[1,4,9,12,16,20,36,40]
sq=[ round(sqrt(i),2) for i in n ]
sq

Out[325… [1.0, 2.0, 3.0, 3.46, 4.0, 4.47, 6.0, 6.32]

6.Given a list of fruits print their length in a list

In [326… fruits = ['Apple','Cherry','papaya','Banana','Kiwi','Pomegranate','water m


length=[ len(i) for i in fruits]
length

Out[326… [5, 6, 6, 6, 4, 11, 11]

7.Given list of fruits each in lower case,craete a list where items are
upper case of the same word

In [327… fruits = ['apple','cherry','papaya','banana','kiwi','pomegranate','water m


upp_case = [ s.upper() for s in fruits]
upp_case

Out[327… ['APPLE', 'CHERRY', 'PAPAYA', 'BANANA', 'KIWI', 'POMEGRANATE', 'WATER ME


LON']

List comprehension with if condition

8.For a given list print their length in a list where length is atleast 4

In [328… fruits = ['apple','cat','cherry','dog','papaya','banana','kiwi','pomegrana


length = [ len(s) for s in fruits if len(s)>=4 ]
length

Out[328… [5, 6, 6, 6, 4, 11, 11]


9.For a given list of words,filter the words starting with a

In [329… words = [ 'Banana','cricket','sports','apple','Amla','beetroot','papapa',


f_a = [ s for s in words if s.lower()[0]=='a']
f_a

Out[329… ['apple', 'Amla', 'Almond']

In [330… words = [ 'Banana','cricket','sports','apple','Amla','beetroot','papapa',


f_a = [ s for s in words if s[0]=='a']
f_a

Out[330… ['apple']

In [331… words = [ 'Banana','cricket','sports','apple','Amla','beetroot','papapa',


f_a = [ s for s in words if s.lower().startswith('a')]
f_a

Out[331… ['apple', 'Amla', 'Almond']

10.Given a list of words,filter palindromes

In [332… words = ['Mom','aple','python','dad','civic','laptop','Malayalam']


palindrome = [ s for s in words if s.lower()==s.lower()[::-1]]
palindrome

Out[332… ['Mom', 'dad', 'civic', 'Malayalam']

In [333… words = ['Mom','aple','python','dad','civic','laptop','Malayalam']


palindrome = [ s for s in words if s==s.lower()[::-1]]
palindrome

Out[333… ['dad', 'civic']

In [334… words = ['Mom','aple','python','dad','civic','laptop','Malayalam']


palindrome = [ s for s in words if s==s[::-1]]
palindrome

Out[334… ['dad', 'civic']

list comprehension with if-else statements


if statement if if condition else else statement for i in iterable

11.Given list of number,square even numbers and apply sqrt to odd


numbers

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

Cell In[339], line 2


sq = [for s in n s**2 if s%2==0 else round(sqrt(s),2)]
^
SyntaxError: invalid syntax

12.inline if-else

In [341… m = 77
"Passed" if m>35 else "Failed" # inline if-else statements

Out[341… 'Passed'

13.Given a list of marks,print a list of passed or failed

In [342… marks = [55,70,23,36,95,11,28,77,92]


list = [ "Passed" if s>35 else "Failed" for s in marks ]
print(list)

['Passed', 'Passed', 'Failed', 'Passed', 'Passed', 'Failed', 'Failed', 'Pa


ssed', 'Passed']

In [343… marks = [55,70,23,36,95,11,28,77,92]


list = [ "Passed" if marks>35 else "Failed" for s in marks ]
list # raises error : compare the marks not list

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

TypeError: '>' not supported between instances of 'list' and 'int'

Dictionary comprehension
1. Given a list of numbers,key is number and value is corresponding
square of the same number

In [344… nums = [1,2,3,4,5,11,13,100,14,17]


dict_n = { k : k**2 for k in nums}
print(dict_n)

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 11: 121, 13: 169, 100: 10000, 14: 196, 1
7: 289}

2. Given a list of words,key is the word and corresponding value is it's


length
In [345… words = ['fruits','Mom','vegetables','civic','veg','sports','Cultural Even
dict_w = { k : len(k) for k in words}
print(dict_w)

{'fruits': 6, 'Mom': 3, 'vegetables': 10, 'civic': 5, 'veg': 3, 'sports':


6, 'Cultural Events': 15, 'Colleges': 8}

3. Filter palindromes from a given list,key is the word and value is it's
uppercse

In [346… words = ['madam','level','fruits','Mom','vegetables','civic','veg','sports


pal_list = { s : s.upper() for s in words if s.lower()==s.lower()[::-1]}
print(pal_list)

{'madam': 'MADAM', 'level': 'LEVEL', 'Mom': 'MOM', 'civic': 'CIVIC', 'da


d': 'DAD'}

4.Given a list of words,create a dictionary with key as word and length


as value such that words of length greater than 3 can form dictionary

In [347… words = ['madam','level','fruits','Mom','vegetables','civic','veg','sports


words_len_3= { s : len(s) for s in words if len(s)>3}
print(words_len_3)

{'madam': 5, 'level': 5, 'fruits': 6, 'vegetables': 10, 'civic': 5, 'sport


s': 6, 'Cultural Events': 15, 'Colleges': 8}

5. Given the list of words , key is the word convert to lower case if
palindrome and others to upper case

In [348… words = ['apple','Banana','mom','Dad','bengali','civic','Kannada']


dict_words = { s : s.lower() if s.lower()==s.lower()[::-1] else s.upper(
print(dict_words)

{'apple': 'APPLE', 'Banana': 'BANANA', 'mom': 'mom', 'Dad': 'dad', 'bengal


i': 'BENGALI', 'civic': 'civic', 'Kannada': 'KANNADA'}

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 [349… prices =[200,510,300,1200,120,500]


price_GST = [ round(s+s*(18/100), 2) if s>500 else round(s+s*(5/100), 2) f
price_GST

Out[349… [210.0, 601.8, 315.0, 1416.0, 126.0, 525.0]

In [350… prices =[200,510,300,1200,120,500]


price_GST = [ round(s*1.18, 2) if s>500 else round(s*1.05, 2) for s in pr
price_GST

Out[350… [210.0, 601.8, 315.0, 1416.0, 126.0, 525.0]

7. Given a dictionary of products and their prices,for prices greater than


500 add 18% GST and for prices less than 500 add 5% GST.Output
should contain product as key and (price+GST) as value.
prices={'Laptop' : 200,'Monitor' : 740,'KeyBoard' : 510 ,'USB':
370}

In [351… prices={'Laptop' : 200,'Monitor' : 740,'KeyBoard' : 510 ,'USB': 370}


product_prices = { product : round(price*1.18,2)
if price>=500
else round(price*1.05,2)
for product,price in prices.items() }
product_prices

Out[351… {'Laptop': 210.0, 'Monitor': 873.2, 'KeyBoard': 601.8, 'USB': 388.5}

8. Gven a list of prices,filter only non-zero prices.If the price is non-zero


key is word and (price+value is 18% GST)
prices={'Laptop' : 200,'Mouse' : 0,'Monitor' : 510,'KeyBoard' : 0
,'USB': 370}

In [352… prices={'Laptop' : 200,'Mouse' : 0,'Monitor' : 510,'KeyBoard' : 0 ,'USB':


non_zero_prices = { product : price*1.18 for product,price in prices.item
non_zero_prices

Out[352… {'Laptop': 236.0, 'Monitor': 601.8, 'USB': 436.59999999999997}

In [353… prices={'Laptop' : 200,'Mouse' : 0,'Monitor' : 510,'KeyBoard' : 0 ,'USB':


non_zero_prices = { product : round(price*1.18,2) for product,price in pri
non_zero_prices

Out[353… {'Laptop': 236.0, 'Monitor': 601.8, 'USB': 436.6}

In [ ]:
Functions( ) :
Functions in Python are blocks of organized, reusable code designed to perform a
specific task. They enhance code modularity, readability, and reusability.

Types of Functions in Python:


Built-in Functions:
These are predefined functions readily available in Python's standard library.
Examples include print( ), len( ), sum( ), max( ), min( ), type( ), range( ), etc.

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.

In [354… # function definition


def greet(): # function header contains def keyword,function name and
print("Good Morning")
greet() # function call

Good Morning

function with one parameter


In [355… def greet_msg(message):
print(message)
greet_msg("Good morning")

Good morning

In [356… def greeting(name,msg):


print(f'{msg} {name}') # give space between msg and name
greeting('kasi','Hello')

Hello kasi

In [357… def greeting(name,msg):


print(f'{msg}{name}')
greeting('kasi','Hello')

Hellokasi

1.Create a function that two numbers as input and print their sum

In [358… def total(a,b):


# addind doc string to function
'''
Takes two parameters a,b
a--->int
b--->int
Calculates a+b
'''
print(a+b)
total(1,5)

In [359… help(total)

Help on function total in module __main__:

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

In [363… def total_sum(a,b):


return a+b
d=total_sum(3,4)
print(d)

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

In [364… def r_string(string):


print(string[::-1])
r_string("PYTHON")

NOHTYP

In [365… r_string("INNOMATICS")

SCITAMONNI

Positional and Keyword Arguments


The power of a function is it's ability to work with parameters.When calling a
function, you need to pass arguments to parameters. There are two kinds of
arguments : positional arguments and keyword arguments
Using positional arguments requires that the arguments be passed in the same
order as their respective parameters in the function header. The arguments must
match the parameters in order, number and compatible type, as defined in the
function header
You can also call a function using keyword arguments passing each arguments in
a form of name = value. The arguments can appear in any order using keyword
arguments

Argument and Parameter :


Parameter: Parameters are the named variables listed inside the parentheses in a
function's def statement. They act as placeholders for the values that the function
expects to receive when it is called.
Argument : Arguments are the actual values passed to a function when it is called.
These values are assigned to the corresponding parameters within the function's
scope during execution.

In [366… def exp(s1,s2,n):


e=(s1+" "+s2)*n
print(e)
exp('Hi','How are you?',3)

Hi How are you?Hi How are you?Hi How are you?

In [367… exp('Hi',3,'How are you?') # it throws an error as it's positional argumen

--------------------------------------------------------------------------
-
TypeError Traceback (most recent call las
t)
Cell In[367], line 1
----> 1 exp('Hi',3,'How are you?')

Cell In[366], line 2, in exp(s1, s2, n)


1 def exp(s1,s2,n):
----> 2 e=(s1+" "+s2)*n
3 print(e)

TypeError: can only concatenate str (not "int") to str

In [368… exp(s1='Hi',n=3,s2='How are you?') # This is keyword arguments

Hi How are you?Hi How are you?Hi How are you?

In [ ]:

3.Create a function that takes strings and returns it's reversed version

In [370… def rev_str(str):


return str[::-1]

In [371… reversed = rev_str("Lion")


print(reversed)

noiL

In [372… reversed = rev_str("Python")


print(reversed)

nohtyP

In [373… rev_str("Python")

Out[373… 'nohtyP'

4. Create a function that takes centigrade and returns farenheit


9
F = ∗ c + 32
5

In [374… def Farenheit(c):


return (9/5)*c+32

In [375… temp_c = Farenheit(36)


print(temp_c)

96.8

In [376… temp_c = Farenheit(40)


print(temp_c)

104.0

5. Create a function that takes n and prints sum of n natural numbers


n(n+1)
Sum =
2

In [377… def sum(n):


return (n*(n+1))/2

In [378… sum_n = sum(6)


print(sum_n)

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

In [380… from math import pi


def area_circle_r(r):
A = pi*(r**2)
return A

In [381… Area = round(area_circle_r(5),2)


Area

Out[381… 78.54

Write a function and import module


create .py file and write functions in it
import the module and check whether it works

7.Given a number the function has to return sum of it's digits

In [382… def sum_digits(n):


s=str(n)
sum = 0
for i in s :
sum = sum + int(i)
return sum

In [383… sum_digits(12345)

Out[383… 15

We can solve above using modular method

8.Count no of words and no of characters in given text

In [384… text = "I am learning DS at Innomatics"


n_words = text.split( )
print(n_words)

['I', 'am', 'learning', 'DS', 'at', 'Innomatics']

In [385… len(n_words)

Out[385… 6

In [386… len(text)
Out[386… 30

In [387… def count_words_char(text):


t_split=text.split()
n_words=len(t_split)
n_char=len(text)
return n_words,n_char

In [388… count=count_words_char("I am kasi")


print(count)

(3, 9)

In [389… def count_words_char(text):


return len(text.split()),len(text)

In [390… count = count_words_char("Python is easy to learn")


print(count) # we can store in single variable

(5, 23)

In [391… n_words,n_characters = count_words_char("Python is easy to learn")


print(n_words,n_characters) # we can store in two different variables , th

5 23

args and kwargs


*args - when you have no idea about how many arguments you will be receiving
as an input for the function
** kwargs - how many keyword arguments you will be.....

In [392… def exp(a,b,c, *args):


print(type(args))
print(f"args : {args}")
v = args[0]+args[-1]*args[1]
return a+b-c**2,v

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 [395… def exp_kw(a,b,c,*args,**kwargs):


print(type(args),type(kwargs))
print(f'args : {args},kwargs : {kwargs}')
z = args[0]+args[-1]*args[1]
for k,v in kwargs.items():
print(f'key:{k},value:{v}')
return a+b-c**2,z

In [396… exp_kw(30,12,10,30,45,10,29,23,56,r=45,f=59,n=100,x=300)

<class 'tuple'> <class 'dict'>


args : (30, 45, 10, 29, 23, 56),kwargs : {'r': 45, 'f': 59, 'n': 100, 'x':
300}
key:r,value:45
key:f,value:59
key:n,value:100
key:x,value:300
Out[396… (-58, 2550)

In [397… args = (30, 45, 10, 29, 23, 56)


v = args[0]+args[-1]*args[1]
v

Out[397… 2550

Some special functions

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)

Out[2]: [(45, 'Cricket'), (30, 'Lion'), (20, 'Pen')]

In [3]: t=zip(k,v)
tuple(t)

Out[3]: ((45, 'Cricket'), (30, 'Lion'), (20, 'Pen'))

In [4]: t=zip(k,v)
dict(t)

Out[4]: {45: 'Cricket', 30: 'Lion', 20: 'Pen'}

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 [5]: def squares(x):


return x**2

In [6]: squares(13)

Out[6]: 169

In [7]: sq = lambda y : y**2


sq(5)

Out[7]: 25

In [8]: sq(2)

Out[8]: 4

In [9]: sq(13)

Out[9]: 169

In [10]: greet = lambda : "Hello"


greet() # parameters/arguments is optional

Out[10]: 'Hello'

In [11]: def greeting():


return "Hello"

In [12]: greeting()

Out[12]: 'Hello'

Note : def and lambda functions function is same,but they


are syntatically differ

9. Celcius to farenheit

In [13]: F = lambda C : C*(9/5)+32

In [14]: F(36)

Out[14]: 96.8

In [15]: add = lambda a,b : a+b

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 [17]: is_palindrome = lambda text : True if text.lower()==text.lower()[::-1] els

In [18]: is_palindrome("mam")

Out[18]: True

In [19]: is_palindrome("Student")

Out[19]: False

In [20]: is_palindrome = lambda text : text.lower()==text.lower()[::-1]

In [21]: is_palindrome("Student")

Out[21]: False

In [22]: is_palindrome("12321")

Out[22]: True

In [23]: is_palindrome(12321) # raises error , always keep inside quotes

--------------------------------------------------------------------------
-
AttributeError Traceback (most recent call las
t)
Cell In[23], line 1
----> 1 is_palindrome(12321)

Cell In[20], line 1, in <lambda>(text)


----> 1 is_palindrome = lambda text : text.lower()==text.lower()[::-1]

AttributeError: 'int' object has no attribute 'lower'

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 [24]: import math


li = [20,45,60,91,10]
square_root = map(lambda x : round(math.sqrt(x),2),li)
list(square_root)

Out[24]: [4.47, 6.71, 7.75, 9.54, 3.16]

In [25]: square_root

Out[25]: <map at 0x21a9a561270>


In [26]: print(square_root)

<map object at 0x0000021A9A561270>

In [27]: Centigrade = [41,34,30,39,56]


Farenheit = map(F,Centigrade) # F = lambda C : C*(9/5)+32
list(Farenheit)

Out[27]: [105.8, 93.2, 86.0, 102.2, 132.8]

11. Write a function ro return reversed version of strings

In [28]: strings = ["Python" , "is" , "easy" , "to" , "learn"]


r_strings = map(lambda i : i[::-1],strings)

In [29]: r_strings

Out[29]: <map at 0x21a9a5619f0>

In [30]: list(r_strings)

Out[30]: ['nohtyP', 'si', 'ysae', 'ot', 'nrael']

12. Write a function to return lengths of all words in list

In [31]: strings = ["Python" , "is" , "easy" , "to" , "learn"]


len_words = map(lambda i : len(i),strings)
list(len_words)

Out[31]: [6, 2, 4, 2, 5]

In [32]: strings = ["Python" , "is" , "easy" , "to" , "learn"]


len_words = map(len,strings)
list(len_words)

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)

Out[33]: ['mom', 'civic', 'Malayalam']

13. Write a filter function which retains strings with length greater than 5

In [34]: strings = ['mom','student','civic','telugu','Malayalam','kanada','python'


length_5 = filter(lambda x : len(x)>5,strings)
list(length_5)

Out[34]: ['student', 'telugu', 'Malayalam', 'kanada', 'python', 'Javascript']


14.Given a list calculate square of even numbers

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)

Out[35]: [1156, 3136, 324]

In [36]: print(list(sq))

[]

15.In a list of words convert words starting with 's' to upper case

In [37]: strings = ['Singer','Raven','Steve','New York','Singapore']


s = filter(lambda x : x.lower().startswith('s'),strings)
S_upper_Case = map(lambda x : x.upper(),s)
list(S_upper_Case)

Out[37]: ['SINGER', 'STEVE', 'SINGAPORE']

16.From a list of price increase prices>100 by 10%

In [38]: prices = [80,120,90,150]


p_100 = filter(lambda x : x>100,prices)
increase_10 = map(lambda x : x*1.1,p_100)
list(increase_10)

Out[38]: [132.0, 165.0]

Note : Differ between map() and filter()


In [39]: prices = [80,120,90,150]
p_100 = map(lambda x : x>100,prices)
list(p_100)

Out[39]: [False, True, False, True]

In [40]: prices = [80,120,90,150]


p_100 = filter(lambda x : x>100,prices)
list(p_100)

Out[40]: [120, 150]

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

Note : Observe differ


In [43]: a = [34,23,56,45,11,18]
total = map(lambda x,y : x+y, a)
list(total)

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

TypeError: <lambda>() missing 1 required positional argument: 'y'

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)

Out[44]: [68, 46, 112, 90, 22, 36]

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

17. Calculate product of items in the list a = [34,23,56,45,11,18]

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

In [47]: fact = reduce(lambda x,y : x*y ,range(1,11))


fact

Out[47]: 3628800
In [48]: product=1
for i in range (1,11):
product*=i
product

Out[48]: 3628800

In [49]: def func(x,y):


return x*y

In [50]: fact = reduce(func,range(1,11))


fact

Out[50]: 3628800

19. Sum of squares of even numbers in given list li =


[34,23,56,45,11,18]

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

Out[52]: [1156, 3136, 324]

In [53]: sum(sq_even)

--------------------------------------------------------------------------
-
TypeError Traceback (most recent call las
t)
Cell In[53], line 1
----> 1 sum(sq_even)

TypeError: 'int' object is not callable

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 [54]: def factorial(n):


if n<=1:
return 1
else :
return n*factorial(n-1)

In [55]: factorial(5)

Out[55]: 120

The scope of variables


The scope of variables is part of the program where the variable can be
referenced.A variable created inside a function is referred to as local variable.Local
variables can only be accessed within a function.The scope of a local variable
starts from it's creation and continues to the end of the function that contains the
variable.

In python,you can also global variables.They are created outside all functions and
are accessible to all functions in their scope

In [56]: x=10 #global variable


def func():
x=2 #local variable
x+=2
print(f"Value of x inside function is {x}")
func()
x+=10
print(f"Value of x outside function is {x}")

Value of x inside function is 4


Value of x outside function is 20

If we want to maintain same value of x throughout

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

Value of x inside func :31


Value of x inside func fn1 : 35
Value of x outside func : 35
In [58]: 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}")

Value of x inside func :35


Value of x inside func fn1 : 39
Value of x outside func : 39

In [ ]:

In [ ]:

20. Find the largest word in the list


['cat','elephant','tiger','lion']

In [62]: li=['cat','elephant','tiger','lion']
length = []
for i in li:
length.append(len(i))
print(length)

[3, 8, 5, 4]

In [63]: from functools import reduce


words = ['cat','elephant','tiger','lion']
longest_word = reduce(lambda x,y : x if len(x)>len(y) else y,words)
longest_word

Out[63]: 'elephant'

21.Find armstrong numbers upto 1000


A number is called Armstrong number if sum of it's own digits raised to the power
of the number of the digits equal to the number itself
Example 153 = 1^3+5^3+3^3
Steps to solve :
1.Calculate the number of digits
2.Loop through number and raise to power to number of digits
3.sum them and compare with original number
4.If the sum is same as original number it is Armstrong number otherwise not an
armstrong number

In [64]: # find no of digits


n=153
n=str(n)
len(n)

Out[64]: 3

In [1]: def is_armstrong(num):


n = len(str(num))
total = sum([int(i)**n for i in str(num)])
if total == num:
return True
else:
return False

In [2]: is_armstrong(153)

Out[2]: True

In [3]: is_armstrong(270)

Out[3]: False

In [4]: arm_numbers = list(filter(is_armstrong,range(1,1001)))


print(arm_numbers)

[1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407]

In [5]: arm_numbers = filter(is_armstrong,range(1,10001))


print(list(arm_numbers))

[1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208, 9474]

In [6]: # Check manually is_armstrong or not


9**4 + 4**4 + 7**4 + 4**4

Out[6]: 9474

23.Prime number problem

In [7]: from math import ceil,floor

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 [15]: # y we need to add +1 to ceil ,let's check by removing + 1


def is_prime(n):
for i in range(2,ceil(n**0.5)):
if n%i==0:
print(f'{n} is divisible by {i}')
return False
else :
return True

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

In [19]: from math import ceil,floor


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 [20]: prime_nums = filter(is_prime,range(1,1001))


print(list(prime_nums))

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]

In [21]: def is_prime(n):


for i in range(2,ceil(n**0.5)+1):
if n%i==0:
return False
else :
return True

In [22]: prime_nums = filter(is_prime,range(1,1001))


print(list(prime_nums))

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

In [23]: prime_nums = filter(is_prime,range(1,1001))


print(f'{list(prime_nums)},end = ' '')

[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 [24]: def is_harshad(n):


sum=0
for i in str(n):
sum = sum + int(i) # pass int(i) not i,here i = 'n' which is str
return sum

In [25]: is_harshad(223)

Out[25]: 7

In [26]: def is_harshad(n):


total = sum([ int(i) for i in str(n)])
return n%total == 0

In [27]: is_harshad(19)

Out[27]: False
In [28]: is_harshad(18)

Out[28]: True

In [29]: harshad_nums = list(filter(is_harshad,range(1,2001)))


print(harshad_nums)

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

25.Write a function to count vowels in a given word

In [30]: def count_vowels(word):


count=0
for i in word:
if i.lower() in 'aeiou':
count+=1
return count

In [31]: count_vowels('Apple')

Out[31]: 2

In [32]: count_vowels("ZOMATOE")

Out[32]: 4

In [33]: def count_vowels(word):


vowels_count = sum(1 for i in word if i.lower() in "aeiou")
return vowels_count
In [34]: [1 for i in "APPLE" if i.lower() in "aeiou"]

Out[34]: [1, 1]

In [35]: count_vowels("BanAna")

Out[35]: 3

In [36]: count_vowels("ZOMATOE")

Out[36]: 4

26.Write a function to print count of each character in a given word

In [37]: def char_count(word):


freq={ }
for i in word :
print(freq)
freq[i]=freq.get(i,0)+1 #if we don't put 1,we will get all 0's
return freq

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}

In [39]: word = "Apple"


{ char : word.count(char) for char in set(word)}

Out[39]: {'l': 1, 'A': 1, 'e': 1, 'p': 2}

27.Write a program to check PIN 3 times


If the PIN is correct in any of 3 attempts,print correct PIN
If PIN is wrong everytime increase attempts count and after 3 attempts,print the
account is locked

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

Wrong pin entered,2 left


Wrong pin entered,1 left
Entered PIn is correct

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

In [42]: average('kasi',Tel = 80,Hin = 85,Eng = 90,Maths = 75)

Out[42]: 82.5

In [43]: def average(name,**marks):


average = sum(marks.values())/len(marks.values())
for s,m in marks.items():
print(f'Subject : {s},marks = {m}')
return average

In [44]: average('kasi',Tel = 80,Hin = 85,Eng = 90,Maths = 75)

Subject : Tel,marks = 80
Subject : Hin,marks = 85
Subject : Eng,marks = 90
Subject : Maths,marks = 75
Out[44]: 82.5

In [45]: def average(name,**marks):


average = sum(marks.values())/len(marks.values())
for s,m in marks.items():
print(f'Subject : {s},marks = {m}')
return print(f'{name} secured {average} marks on an average')

In [46]: average('kasi',Tel = 80,Hin = 85,Eng = 90,Maths = 75)

Subject : Tel,marks = 80
Subject : Hin,marks = 85
Subject : Eng,marks = 90
Subject : Maths,marks = 75
kasi secured 82.5 marks on an average

29. Create a function that takes name prices of items and


two other(discount and delivery)to be added and print final
price
In [47]: def final_price(name,*prices,**others):
discount_percentage=others.get("discount",0)
delivery_fee = others.get("delivery",0)
total=sum(prices)*(1-(discount_percentage/100))+delivery_fee
return total

In [48]: final_price('Appliances',400,1000,2000,discount=30,delivery=36)

Out[48]: 2416.0

In [49]: final_price('Appliances',400,1000,2000) #not prodiving any discount and de

Out[49]: 3400.0

(1-(discount_percentage/100))=1-30/100=70% means we are charging


70% as discount is 30%

In [50]: def total_price(**prices):


discount_percentage=prices.get("discount",0)
delivery_fee=prices.get("delivery",0)
price = 0
for a,p in prices.items():
if a!='discount' and a!='delivery':
print(a,p)
price=price+p
return price*(1-(discount_percentage/100))+delivery_fee

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

30.Reverse a string without slicing

In [67]: text = "Hello@123$!&World&?!*((A"


e=""
for s in text:
e=s+e
print(e)
print(f'Reversed string : {e}')

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

31.Count special characters in a string

In [68]: import string


string.punctuation

Out[68]: '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

In [69]: import string

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

31.Check if a number is a strong number


145 = 1!+4!+5!

In [71]: from math import factorial


def is_strong_number(n):
total=0
for i in str(n):
total+=factorial(int(i))
if n==total:
return True
else:
return False

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 [74]: def is_perfect_number(n):


a=[]
sum=0
for i in range(1,n):
if n%i==0:
sum+=i
if sum==n:
return True
else:
return False

In [75]: is_perfect_number(6)

Out[75]: True

In [76]: list(filter(is_perfect_number,range(1,10001)))

Out[76]: [6, 28, 496, 8128]

In [77]: import math

In [78]: def is_perfect_numbers(n):


factors=[]
for i in range(1,math.ceil(n/2)+1):
if n%i==0:
factors.append(i)
# print(n,factors)
return sum(factors)==n

In [79]: is_perfect_numbers(28)

Out[79]: True

In [80]: list(filter(is_perfect_numbers,range(10001)))

Out[80]: [0, 1, 6, 28, 496, 8128]

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

ZeroDivisionError: division by zero

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)

Inside zero division error block, Denominator is zero and division by z


ero not posssible
22

In [84]: class ValueToolSmallError(Exception):


"""This exception will be raised if inputs too small"""
pass
class ValueToolLargeError(Exception):
"""This exception will be raised if inputs too large"""
pass

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

Input is too small,Try again !!


Input is too large,Try again !!
Correct Guess

33.Find average of numbers taken in a loop and stop accetping input


once user enters 0

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

Cummulative average for [2.0] : 2.0


Cummulative average for [2.0, 3.0] : 2.5
Cummulative average for [2.0, 3.0, 4.0] : 3.0
Final average for [2.0, 3.0, 4.0] : 3.0
35.Write a program that takes inputs from user.After each valid input
print complete and display the moving average of last 3 numbers
entered(or fewer,if fewer than 3 numbers),program should stop taking
inputs once user enters sone .Handle invalid entries(non-numeric
values except done )and display appropriate message.

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

Moving average for [1.0] : 1.0


Moving average for [1.0, 2.0] : 1.5
Moving average for [1.0, 2.0, 3.0] : 2.0
Moving average for [2.0, 3.0, 4.0] : 3.0
Moving average for [3.0, 4.0, 5.0] : 4.0
Moving average for [4.0, 5.0, 6.0] : 5.0
Final average for [4.0, 5.0, 6.0] : 5.0

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 [97]: 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 [98]: p1 = Person("Ram",28,'FeMale')

In [99]: p1.display_info()

Ram is 28 years old is FeMale

In [100… p2 = Person("John",30,"Male")

In [101… p2.display_info()

John is 30 years old is Male

In [102… p1.name='Mukesh'

In [103… p1.display_info()

Mukesh is 28 years old is FeMale

In [104… type(p1)

Out[104… __main__.Person

1.Create car class with brand , model and year as attributes.Add


method car_details() which displays car details model,brand and
year

In [105… class Car:


def __init__(self,brand,model,year):
self.brand=brand
self.model=model
self.year=year
def car_details(self):
print(f'{self.brand} {self.model} manufactured in {self.year}')

In [106… car1 = Car("Tesla","Model S",2023)


car2 = Car("Mahindra","XUV",2024)

In [107… print(dir(car1)[-5::])

['__weakref__', 'brand', 'car_details', 'model', 'year']

In [108… car1.car_details()

Tesla Model S manufactured in 2023

In [109… car2.car_details()

Mahindra XUV manufactured in 2024

In [110… car1.brand

Out[110… 'Tesla'

2.create a student class with name , roll_number , branch and


marks(dictionary .Write a method student_details() with all
information of a student and a method that calculates
average_marks()

In [111… class Student:


def __init__(self,name,roll_number,branch,**marks): #constructor meth
self.name=name #self.name can be anything like it can be self.stud
self.roll_number=roll_number
self.branch=branch
self.marks=marks
def student_details(self):
print(f"{self.name} with {self.roll_number} enrolled in {self.bran
def average_marks(self):
return round(sum(self.marks.values())/len(self.marks),2)

In [112… Student("TOM","DS001","CSE",english=70,maths=80,science=90).student_detail

TOM with DS001 enrolled in CSE in following subjects dict_keys(['english',


'maths', 'science'])

if we keep {(self.marks.keys())} it returns dict_keys in output,to avoid that


we use {list(self.marks.keys())}

In [113… class Student:


def __init__(self,name,roll_number,branch,**marks): #constructor meth
self.a=name #self.name can be anything like it can be self.studen
self.roll_number=roll_number
self.branch=branch
self.marks=marks
def student_details(self):
print(f"{self.a} with {self.roll_number} enrolled in {self.branch
def average_marks(self):
print(f"Marks are {list(self.marks.values())}") # to display mark
return round(sum(self.marks.values())/len(self.marks),2)

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

TOM with DS001 enrolled in CSE in following subjects ['english', 'maths',


'science']

In [116… s2.student_details()

jerry with DS002 enrolled in CS in following subjects ['english', 'maths',


'science', 'others']

In [117… s1.average_marks()

Marks are [70, 80, 90]


Out[117… 80.0

In [118… s2.average_marks()

Marks are [90, 75, 60, 370]


Out[118… 148.75
3.Bank Account class
Attributes
Name
Account Number
IFSC
Balance
Methods
Check Balance
Deposit
Withdrawl

In [119… class BankAccount:


def __init__(self,name,AccountNumber,IFSC,Balance):
self.name=name
self.accountNumber=AccountNumber
self.ifsc=IFSC
self.balance=Balance
def check_balance(self):
print(f"Balance : {self.balance}")
def deposit(self):
amount=int(input("Enter amount to be deposited : "))
self.balance+=amount
self.check_balance()
def withdrawl(self):
amount=int(input("Enter amount to be withdrawn : "))
if amount<=self.balance:
self.balance-=amount
self.check_balance()
else:
print("Insufficient funds")

In [120… bankacc1 = BankAccount("John","IN001","SBI98989",6_000)

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

AttributeError: 'BankAccount' object has no attribute '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 [131… class Employee(Person):


def __init__(self,name,age,gender,emp_ID,position):
super().__init__(name,age,gender)
self.emp_ID = emp_ID
self.position = position
def emp_details(self):
print(f"{self.name} with {self.emp_ID} is working as {self.positio

In [132… person1 = Person("Jack",28,"Male")


emp1 = Employee("Ramsa",24,"Male","A001","Data Scientist")

In [133… print(dir(person1)[-5:])

['__weakref__', 'age', 'display_info', 'gender', 'name']

In [134… dir(person1)[-5:]

Out[134… ['__weakref__', 'age', 'display_info', 'gender', 'name']

In [135… dir(emp1)[-7:]

Out[135… ['age', 'display_info', 'emp_ID', 'emp_details', 'gender', 'name', 'posi


tion']

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

AttributeError: 'Person' object has no attribute 'emp_details'

In [139… emp1.emp_details()

Ramsa with A001 is working as Data Scientist

In [140… person1.emp_details()

--------------------------------------------------------------------------
-
AttributeError Traceback (most recent call las
t)
Cell In[140], line 1
----> 1 person1.emp_details()

AttributeError: 'Person' object has no attribute '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

AttributeError: 'Person' object has no attribute 'emp_ID'

In [145… emp1.emp_ID

Out[145… 'A001'

Whatever is available in Person class is available in emp_ID but in


converse not

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 [147… class Car: #Parent vlas or super class or Base class


def __init__(self,brand,model,year):
self.brand=brand
self.model=model
self.year=year
def display_info(self): #Instance method
print(f'{self.brand} {self.model} manufactured in year : {self.yea

In [148… # child class(Electric car) is inherited from parent class(car)


class ElectricCar(Car):
def __init__(self,brand,model,year,battery_capacity):
super().__init__(brand,model,year)
self.battery_capacity = battery_capacity
def charge(self):
print(f"{self.brand} {self.model} is charging to {self.battery_cap

In [149… car_1 = Car("Tesla","Model S",2021)


electric_car_1 = ElectricCar("Ola","Model N",2023,75)

In [150… electric_car_1.display_info()

Ola Model N manufactured in year : 2023

In [151… ElectricCar.__mro__

Out[151… (__main__.ElectricCar, __main__.Car, object)

In [152… electric_car_1.charge()

Ola Model N is charging to 75kwh

In [153… electric_car_1.charge()

Ola Model N is charging to 75kwh

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 [154… # Multi level Inheritance


class LuxuryCar(ElectricCar):
def __init__(self,brand,model,year,battery_capacity,luxury_features):
super().__init__(brand,model,year,battery_capacity)
self.luxury_features = luxury_features
def luxury_features_available(self):
print(f"Luxury features : {self.luxury_features}")
def display_info(self):
print(f"{self.brand} {self.model} has battery capacity : {self.bat

In [155… ferrari = LuxuryCar("ferrari","Nitro",2024,80,["nitro boost","Super charge

In [156… dir(electric_car_1)[-6:]

Out[156… ['battery_capacity', 'brand', 'charge', 'display_info', 'model', 'year']

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

Tesla Model S manufactured in year : 2021

In [159… electric_car_1.display_info()

Ola Model N manufactured in year : 2023

In [160… ferrari.display_info()

ferrari Nitro has battery capacity : 80 and luxury features : ['nitro boos
t', 'Super charge']

In [161… LuxuryCar.__mro__

Out[161… (__main__.LuxuryCar, __main__.ElectricCar, __main__.Car, object)

In [162… luxury_car_1 = LuxuryCar("porsche","Paramera",2024,80,["ambience lighting

In [163… luxury_car_1.charge()

porsche Paramera is charging to 80kwh

In [164… luxury_car_1.luxury_features_available()

Luxury features : ['ambience lighting', 'air bag']

display_info() is first referred in LuxuryCar class


if it's not there it is referred in immediate parent(ElectricCar)
If it's not there in immediate parent it is referred in parent of immediate
parent(Car class

In [165… luxury_car_1.display_info()

porsche Paramera has battery capacity : 80 and luxury features : ['ambienc


e lighting', 'air bag']
If display info() is present in Car,ElectricCar and Luxurycar classes,then
what is the priority which should be preferred?

MRO : Method Resolution Order


In [166… LuxuryCar.__mro__

Out[166… (__main__.LuxuryCar, __main__.ElectricCar, __main__.Car, object)

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 [167… class LandVehicle :


def __init__(self,land_speed):
self.land_speed=land_speed
def display_speed(self):
print(f"Speed of vehicle in land : {self.land_speed}km/h")

In [168… class WaterVehicle :


def __init__(self,Water_speed):
self.water_speed=Water_speed
def display_speed(self):
print(f"Speed of vehicle in water : {self.water_speed}knots")

In [169… class AmphibiousVehicle(LandVehicle,WaterVehicle):


def __init__(self,land_speed,water_speed):
LandVehicle.__init__(self,land_speed) # self.land_speed=land_speed
WaterVehicle.__init__(self,water_speed)

In [170… amp = AmphibiousVehicle(34,28)

In [171… amp.display_speed()

Speed of vehicle in land : 34km/h

In [172… AmphibiousVehicle.__mro__

Out[172… (__main__.AmphibiousVehicle,
__main__.LandVehicle,
__main__.WaterVehicle,
object)

In [173… class AmphibiousLandVehicle(LandVehicle,WaterVehicle):


def __init__(self,land_speed,water_speed):
LandVehicle.__init__(self,land_speed)
WaterVehicle.__init__(self,water_speed)
In [174… class AmphibiousWaterVehicle(WaterVehicle,LandVehicle):
def __init__(self,land_speed,water_speed):
LandVehicle.__init__(self,land_speed)
WaterVehicle.__init__(self,water_speed)

In [175… amp_vehicle_water = AmphibiousWaterVehicle(34,28)

In [176… amp_vehicle_water.display_speed()

Speed of vehicle in water : 28knots

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 [179… amp_vehicle_land = AmphibiousLandVehicle(20,12)


amp_vehicle_land.display_speed()

Speed of vehicle in land : 20km/h

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 [181… class Employee:


def __init__(self,name,company):
self.name = name
self.company = company
def get_details(self):
print(f"{self.name} is working at {self.company}")
In [182… emp1 = Employee("John","Vision.ai")
emp2 = Employee("Tom","Language.ai")

In [183… emp1.get_details()

John is working at Vision.ai

In [184… emp2.get_details()

Tom is working at Language.ai

In [185… emp1.name

Out[185… 'John'

In [186… emp2.name

Out[186… 'Tom'

In [187… emp2.company

Out[187… 'Language.ai'

In [188… class Developer(Employee):


def __init__(self,name,company):
super().__init__(name,company)
self.project = "LLMs"
def project_details(self):
print(f"{self.name} is working in {self.project}")
def change_project(self,project):
self.project = project

In [189… dev1 = Developer("Pramod","Virtusa.ai")


dev2 = Developer("Siddarth","Modelling.ai")

In [190… dev1.project,dev2.project

Out[190… ('LLMs', 'LLMs')

In [191… dev1.project = "Audio Analyst"


dev1.project,dev2.project

Out[191… ('Audio Analyst', 'LLMs')

In [192… dev1.project,dev2.project

Out[192… ('Audio Analyst', 'LLMs')

In [193… dev1.change_project("Fine-Tuning")

In [194… dev1.project,dev2.project

Out[194… ('Fine-Tuning', 'LLMs')

In [195… #Manager is sub class of Employee


class Manager(Employee):
def __init__(self,name,company):
super().__init__(name, company)
def manage(self):
print(f"{self.name} manages teams at {self.company}")

In [196… m1 = Manager("Ranchan","Vision.ai")

In [197… Manager.__mro__

Out[197… (__main__.Manager, __main__.Employee, object)

In [198… m1.manage()

Ranchan manages teams at Vision.ai

In [199… print(dir(m1)[-5:])

['__weakref__', 'company', 'get_details', 'manage', 'name']

In [200… class TeamLead(Developer,Manager):


def develop(self):
print(f"{self.name} is a developer")
def lead(self):
print(f"{self.name} leads the development and manages development

In [201… TeamLead.__mro__

Out[201… (__main__.TeamLead,
__main__.Developer,
__main__.Manager,
__main__.Employee,
object)

In [202… TL1 = TeamLead("Patrick","Vision.ai")

In [203… TL1.name

Out[203… 'Patrick'

In [204… TL1.get_details()

Patrick is working at Vision.ai

In [205… Developer.__mro__

Out[205… (__main__.Developer, __main__.Employee, object)

In [206… Manager.__mro__

Out[206… (__main__.Manager, __main__.Employee, object)

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

In [207… class Counter:


def __init__(self,max_count=10): #providing default,if we don,t provid
self.__count = 0
self.__max_count = max_count

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

Accesing Counter_1.__count directly will result in an attribute error because


__count is a private attribute
Trying to call private variable or private method will result in an error because
private variables or methods are not accessible from outside their class

In [209… counter_1.__count

--------------------------------------------------------------------------
-
AttributeError Traceback (most recent call las
t)
Cell In[209], line 1
----> 1 counter_1.__count

AttributeError: 'Counter' object has no attribute '__count'

In [210… counter_1.__max_count

--------------------------------------------------------------------------
-
AttributeError Traceback (most recent call las
t)
Cell In[210], line 1
----> 1 counter_1.__max_count

AttributeError: 'Counter' object has no attribute '__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()

AttributeError: 'Counter' object has no attribute '__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

In [214… # Abstact Base Class


from abc import ABC,abstractmethod

In [215… class MobilePhone(ABC):


@abstractmethod
def call(self,number):
''' calling a contact.....'''
paass

@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

If any method is declared as abstractmethod in super class it should be


implemented in sub class/child classs

In [216… class MySmartPhone(ABC):


def call(self,number):
print(f"Calling {number}")
def message(self,number,context):
print(f'Sending message to {number} : {context}')
def turn_on(self):
print(f'Mobile in turning on')
def turn_off(self):
print(f'Mobile is turning off')

In [217… apple_iphone = MySmartPhone()

In [218… apple_iphone.call(234567)

Calling 234567

In [219… apple_iphone.message(234567,'Hi')

Sending message to 234567 : Hi

In [220… apple_iphone.turn_on()

Mobile in turning on

In [221… apple_iphone.turn_off()

Mobile is turning 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

In [222… # Adding two numbers


2+2

Out[222… 4

In [224… '2'+'2'

Out[224… '22'
In [225… # Concatenation
"Hi" + " " + "Good Morning"

Out[225… 'Hi Good Morning'

In [226… [3,4,5]+[5,2,1]

Out[226… [3, 4, 5, 5, 2, 1]

Here,the "+" is same but doing different operations

In [227… # calculates the length of a string


len("ABC")

Out[227… 3

In [228… # calculates the length of a list


len([1,2,3,4,5])

Out[228… 5

Here,same len() function also

Here,polymorphism is showcased by "+" and "len()" function

In [229… class Shape:


def draw(self):
print("Draw a polygon")

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

In [233… for i in (s1,c1,sq1):


i.draw()

Draw a polygon
Draw a circle
Draw a square

In [234… for i in (s1,c1,sq1):


i.draw()
print()

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

You might also like