Python Full
Python Full
Hello World
1 1. Variable
[2]: a=10
[3]: b=20
[4]: print(a,b)
print(id(a),id(b)) # memory addr
10 20
140319984563616 140319984563936
[5]: print('a')
print('a',a,b)
a
a 10 20
[6]: c='hello'
print(c)
hello
[7]: a1=20
1a=20
1
1.0.1 String contatenation
[9]: c=20
a+c
␣
---------------------------------------------------------------------------
,→
<ipython-input-9-0df1ba1d4cf2> in <module>
1 c=20
----> 2 a+c
[10]: a=20
b=5
print('a'+'b')
print(a+b)
print(a*b)
print(a/b)
print(a-b)
2
print(a//b) # Floor division
print(10%7)
print(5**3)
ab
25
100
4.0
15
0
3200000
4
3
125
7
[11]: x=5
print(x)
[12]: x+=7
print(x)
12
[13]: x-=8
print(x)
[14]: a=8
b=10
a==b
[14]: False
3
[15]: a!=b
[15]: True
[16]: a>b
[16]: False
[17]: a<b
[17]: True
[18]: a>=b
[18]: False
[19]: a<=b
[19]: True
[20]: a=5
a<8 and a>6
[20]: False
[21]: True
[22]: x=10
[22]: True
[23]: True
[24]: x=10
y=20
4
True
[25]: False
[26]: x!=y
[26]: True
[27]: False
[28]: X='Hello'
print('e' in X)
True
[29]: print('L' in X)
False
True
[31]: l=[10,20,30,29]
print(40 in l)
False
False
[33]: x=10
y=10
x is y
[33]: True
5
[34]: x == y
[34]: True
[35]: a=3
b=6
a is b
[35]: False
[36]: a==b
[36]: False
[37]: x is not y
[37]: False
[38]: x!=y
[38]: False
1= True 0= False
0b1010
0b1000
[40]: print(x&y,bin(x&y))
8 0b1000
6
[41]: print(x|y,bin(x|y))
10 0b1010
2 0b10
[43]: a=18
b=9
if a%b=0:
print('Divisible')
else:
print('NA')
. Numeric
- Integer
- Float
- COmplex Numbers
. Sequence type
- String
- List (Mutable)
- Tuple
. Dictionary (Mutable)
. Set
7
2.0.1 Integer
[44]: a= 10
type(a)
[44]: int
2.0.2 Float
[45]: a=2.5
type(a)
[45]: float
2.0.3 Complex
[46]: x=1+3j
type(x)
[46]: complex
2.0.4 String
x='Apple'
type(x)
[47]: str
[48]: a='Hello@123'
type(a)
[48]: str
[49]: A='''
Hello
Welcome to India
'''
print(A)
Hello
8
Welcome to India
2.0.5 List
[50]: list
[51]: A.append(10)
A
[52]: A.remove(10)
[54]: X[2]='Grapes'
[55]: X
[56]: X.append(100)
[57]: X
Tuple
[58]: s=(10,20,'Hello')
type(s)
[58]: tuple
[59]: s.append(10)
␣
,→---------------------------------------------------------------------------
9
AttributeError Traceback (most recent call␣
,→ last)
<ipython-input-59-bc62c451aa5b> in <module>
----> 1 s.append(10)
[60]: s[0]
s[2]
[60]: 'Hello'
2.0.6 Dictionary
[61]: Empty_Dist={}
type(Empty_Dist)
[61]: dict
[62]: dict
[63]: print(Siblings['Zaman'])
27
[64]: Siblings
[65]: set
[66]: {1, 2, 3, 6, 7}
10
3 Getting user input & Type casting
### Key points: #### . inout() #### . int() #### . float() #### . e val()
[67]: '12'
[71]: a+b
[71]: 58
[73]: a+b
[73]: 3.0
11
Enter the value:- 45
Enter the value2:- 12
[75]: a+b
[75]: 57
[76]: 112
1. If statement
if(conditional statement):
(statement to be executed)
[77]: #eg.
a=10
if a%2==0:
print('a is an even number')
a is an even number
[78]: z=100
if z%10==0:
print("10 is factor of z")
10 is factor of z
12
[81]: A=eval(input("Enter your number1:-"))
if A%2==0:
print("No is even")
2. If Else statement
if(conditional statement):
(statement to be executed)
else:
(alternate statement)
[83]: #eg
A=eval(input("Enter the value:-"))
if A%2==0:
print("No. is Even")
else:
print("No. is Odd")
elif(condition 2):
(statement# 2)
elif(cond 3):
(3rd statement)
else:
(alternate statement)
13
[85]: #eg.
M=eval(input("Enter your marks:-"))
if M>=60:
print("first div")
elif 48<M<60:
print("Second div")
elif 33<M<48:
print("Third div")
else:
print("Student is Fail")
[86]: print('''
+ Add
- Subtract
* Multiply
/ Divide''')
+ Add
- Subtract
* Multiply
/ Divide
14
[88]: X=eval(input("Enter first val:1"))
Y=eval(input("Enter second val:2"))
opr=input("Enter the operator")
if opr=="+":
print(X+Y)
elif opr=="-":
print(X-Y)
elif opr=="*":
print(X*Y)
elif opr=="/":
print(X/Y)
else:
print("invalid operation")
15
Range function which is used for number it is the most important function for creating
a For Loop condition
[90]: range(5) #start from 0 and #conditoin<5 increment 1
[90]: range(0, 5)
[91]: range(1, 6)
[92]: range(1, 6, 2)
[93]: #help(range)
0
1
2
3
4
Hello world
Hello world
Hello world
Hello world
Hello world
5
6
7
8
9
10
11
12
13
14
16
[97]: for N in range(5,40,5):
print(N)
5
10
15
20
25
30
35
2* 1 = 2
2* 2 = 4
2* 3 = 6
2* 4 = 8
2* 5 = 10
2* 6 = 12
2* 7 = 14
2* 8 = 16
2* 9 = 18
2* 10 = 20
5* 1 = 5
5* 2 = 10
5* 3 = 15
5* 4 = 20
5* 5 = 25
5* 6 = 30
5* 7 = 35
5* 8 = 40
5* 9 = 45
5* 10 = 50
5* 11 = 55
5* 12 = 60
5* 13 = 65
5* 14 = 70
17
[101]: for n in range(10,0,-1):
print(n)
10
9
8
7
6
5
4
3
2
1
10
8
6
4
2* 10 = 20
2* 9 = 18
2* 8 = 16
2* 7 = 14
2* 6 = 12
2* 5 = 10
2* 4 = 8
2* 3 = 6
2* 2 = 4
2* 1 = 2
6 While loop
.start
.condition
[104]: 4-6
[104]: -2
18
[105]: i=1
while i<=10:
print(i, '.hello world')
i=i+1
print(i)
1 .hello world
2 .hello world
3 .hello world
4 .hello world
5 .hello world
6 .hello world
7 .hello world
8 .hello world
9 .hello world
10 .hello world
11
[107]: a=10
while a>=1:
print(a,'Reverse loop')
a=a-1
10 Reverse loop
9 Reverse loop
8 Reverse loop
7 Reverse loop
6 Reverse loop
5 Reverse loop
4 Reverse loop
3 Reverse loop
2 Reverse loop
1 Reverse loop
[107]: 0
19
7 20. String Indexing & String slicing in Python
[108]: 'n'
String
[110]: print(len(w))
15
Srn neig
[112]: print(w[-1])
[113]: print(w[-1::-1])
gnixednI gnirtS
[114]: print(w[-1::-2])
gien nrS
[115]: 22
[116]: Z[2:18:2]
20
0 M
1 y
2
3 n
4 a
5 m
6 e
7
8 i
9 s
10
11 H
12 a
13 s
14 a
15 n
16
17 R
18 i
19 z
20 v
21 i
[119]: A=len(Z)
A
[119]: 22
0 i
1 v
2 z
3 i
4 R
5
6 n
7 a
8 s
9 a
21
10 H
11
12 s
13 i
14
15 e
16 m
17 a
18 n
19
20 y
21 M
i
v
z
i
R
n
a
s
a
H
s
i
e
m
a
n
y
M
[122]: 22
22
[123]: for a in range(t-1,-1,-1):
print(a,S[a])
21 i
20 v
19 z
18 i
17 R
16
15 n
14 a
13 s
12 a
11 H
10
9 s
8 i
7
6 e
5 m
4 a
3 n
2
1 y
0 M
i
v
z
i
R
n
a
s
a
H
s
i
e
m
a
n
23
y
M
[126]: for a in S:
print(a)
M
y
n
a
m
e
i
s
H
a
s
a
n
R
i
z
v
i
[127]: S=S[-1::-1]
for a in S:
print(a,a)
i i
v v
z z
i i
R R
n n
a a
s s
a a
H H
24
s s
i i
e e
m m
a a
n n
y y
M M
[129]: n=S.upper()
n
[130]: n=S.title()
n
[131]: n=S.capitalize()
n
[132]: #find
S='Welcome'
print(S.find('l'))
25
2
[133]: print(S.find('e'))
[134]: print(S.find('el'))
-1
[137]: # Index
A='Samsung Apple Grapes'
print(A.index('p'))
[138]: print(A.index('p',11))
17
[139]: print(A.index('z'))
␣
---------------------------------------------------------------------------
,→
<ipython-input-139-938e4b9013b6> in <module>
----> 1 print(A.index('z'))
[140]: # isalpha
A='Samsung Apple Nokia'
print(A.isalpha())
False
26
[141]: # isalpha
z='Samsung'
print(z.isalpha())
True
[142]: # isdigit
A='12357'
print(A.isdigit())
True
[143]: # isdigit
A='Samsung Apple Nokia'
print(A.isdigit())
False
[144]: # isalnum
A='Samsung123'
print(A.isalnum())
True
[145]: # isalnum
A='Apple 123'
print(A.isalnum())
False
[146]: # isalnum
A='Samsung'
print(A.isalnum())
True
[147]: y=chr(65)
print(type(y),y)
<class 'str'> A
27
[148]: a=70
print(chr(a))
[149]: a='A'
print(ord(a))
65
[150]: a='Z'
print(ord(a))
90
[151]: a='f'
print(ord(a))
102
28
[156]: 'My name is Rizvi Hasan'
[158]: txt1= "My name is {a:^15} {b} and I'm a Data Scientist".
,→format(a='Hasan',b='Rizvi')
txt1
[159]: txt1= "My name is {a:>15} {b} and I'm a Data Scientist".
,→format(a='Hasan',b='Rizvi')
txt1
[160]: txt1= "My name is {a:<15} {b} and I'm a Data Scientist".
,→format(a='Hasan',b='Rizvi')
txt1
[161]: txt1= "My name is {a:10} {b:^10} and I'm a Data Scientist".
,→format(a='Hasan',b='Rizvi')
txt1
. it is mutable
. , seperated
. [...]
. a=[12,'app']
[162]: l=[12,'appl',1,2,3]
[163]: print(type(l))
<class 'list'>
[164]: print(l[3])
29
2
[165]: l2=[1,2,3,'A',[4,5,6,'B']]
[166]: print(l2[1])
[167]: print(l2[4][3])
[168]: print(l2[3])
[169]: print(l2[-1][2])
[170]: #Slicing
print(l2[0:2])
[1, 2]
[171]: l3=[1,2,3,3,4,5,'A',[1,2]]
print(l3[0:4])
[1, 2, 3, 3]
[172]: print(l3[3:])
[173]: l3
[2, 3, 5]
[175]: print(l3[-1::-2])
[[1, 2], 5, 3, 2]
[176]: print(l3[-2:-5:-1])
['A', 5, 4]
30
[177]: print(l3[-1::-1])
[178]: l=[10,2,3,4,5,6]
t=len(l)
t
[178]: 6
10
2
3
4
5
6
2
3
4
5
5
5
n=[2,3,1,4,5]
l=len(n)
l
[181]: 5
31
5
4
1
3
2
[183]: l=[12,23,24,25,26]
l
[185]: l
[187]: l
[188]: l2=[10,20,30,40,50]
l2.pop(4)
[188]: 50
[189]: l2
[190]: l2.pop(0)
[190]: 10
[191]: l2
[192]: l3=[1,2,3,4,12,3]
l3.remove(4)
[193]: l3
32
[193]: [1, 2, 3, 12, 3]
[194]: l3.remove(12)
[195]: l3
[195]: [1, 2, 3, 3]
[196]: l3.clear()
[197]: l3
[197]: []
[198]: l4=[1,2,3,4,5,6]
[199]: l4
[199]: [1, 2, 3, 4, 5, 6]
[200]: l4.clear()
[201]: l4
[201]: []
[202]: # update
A=[20,12,23,45,56]
A[0]=34 #change the value of 0 index with 34
[203]: A
. insert()
. append()
. extends()
[204]: l=[12,13,14,15]
l.insert(4,16) #(index, value need to be added)
[205]: l
33
[206]: l.append(20) # value of will be added
l
[207]: m=[17,18]
l.append(m)
[208]: l
[209]: l
l.extend(m) l
[210]: l=[]
for a in range(1,101):
l.append(a)
[211]: print(l)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62,
63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62,
63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
34
␣
---------------------------------------------------------------------------
,→
<ipython-input-213-663493c4badc> in <module>
----> 1 n=[h for z in range(1,101)] ## using list comprehension
2 print(n)
<ipython-input-213-663493c4badc> in <listcomp>(.0)
----> 1 n=[h for z in range(1,101)] ## using list comprehension
2 print(n)
print(n)
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42,
44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82,
84, 86, 88, 90, 92, 94, 96, 98, 100]
[5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
[8, 16, 24, 32, 40, 48, 56, 64, 72, 80]
[217]: s="Hello_World"
t=[a for a in s]
print(t)
['H', 'e', 'l', 'l', 'o', '_', 'W', 'o', 'r', 'l', 'd']
35
17 30. Count, Max, Min, Sort, Reverse & Index list function
[218]: l=[1,2,2,3,4,5,2,4,6,8,8,1,4,5,3]
l.count(2)
[218]: 3
[219]: l.count(3)
[219]: 2
[220]: m=max(l)
m
[220]: 8
[221]: l=["Hello","World","Welcome","Zebra"]
a=max(l)
a
[221]: 'Zebra'
[222]: b=min(l)
b
[222]: 'Hello'
[223]: l=[1,2,2,3,4,5,2,4,6,8,8,1,4,5,3]
l.sort()
[224]: l
[224]: [1, 1, 2, 2, 2, 3, 3, 4, 4, 4, 5, 5, 6, 8, 8]
[225]: a=[23,1,3,4,53,2,5,78,44,3,90,32]
a.sort()
a
[226]: a.reverse()
a
[227]: l.reverse()
l
36
[227]: [8, 8, 6, 5, 5, 4, 4, 4, 3, 3, 2, 2, 2, 1, 1]
[228]: l.index(5)
[228]: 3
[229]: a=[23,1,3,4,53,2,5,78,44,3,90,32]
a.index(78)
[229]: 7
[230]: l1=[1,2,3,4]
l2=[5,6,7,8]
for a,b in zip(l1,l2):
print(a,b)
1 5
2 6
3 7
4 8
[231]: a=[1,2,3,4,5]
b=['Jan','Feb','Mar','April']
for i,j in zip(a,b):
print(i,j)
1 Jan
2 Feb
3 Mar
4 April
[233]: t=len(l)
t
[233]: 4
37
10 3
20 4
30 77
40 88
[235]: '14'
[236]: l=n.split()
[237]: l
[237]: ['14']
l=[]
for a in range(1,4):
n=input('Enter the value' + str(a)+":-")
l.append(n)
[239]: print(l)
Stack Operation:-
- Push: Inserting an elements.
38
- Pop: Deletion an element(last element)
- Peek:Display the last element
- Display: Display list
- Exit
[240]: l=[]
while True:
c=int(input('''
1 Push Elements
2 Pop Elements
3 Peek Element
4 Display Stack
5 Exit
'''))
if c==1:
n=input("Enter the value:-");
l.append(n)
print(l)
elif c==2:
if len(l)==0:
print("Empty Stack")
else:
p=l.pop()
print(p)
print(l)
elif c==3:
if len(l)==0:
print("empty stack")
else:
print("Last stack value",l[-1])
elif c==4:
print("Display Stack",l)
elif c==5:
break;
else:
print('invalid operation')
1 Push Elements
2 Pop Elements
3 Peek Element
4 Display Stack
5 Exit
1
39
Enter the value:- 56
['56']
1 Push Elements
2 Pop Elements
3 Peek Element
4 Display Stack
5 Exit
1
Enter the value:- 89
['56', '89']
1 Push Elements
2 Pop Elements
3 Peek Element
4 Display Stack
5 Exit
145
invalid operation
1 Push Elements
2 Pop Elements
3 Peek Element
4 Display Stack
5 Exit
1
Enter the value:- 45
['56', '89', '45']
1 Push Elements
2 Pop Elements
3 Peek Element
4 Display Stack
5 Exit
2
45
['56', '89']
1 Push Elements
2 Pop Elements
3 Peek Element
4 Display Stack
40
5 Exit
3
Last stack value 89
1 Push Elements
2 Pop Elements
3 Peek Element
4 Display Stack
5 Exit
4
Display Stack ['56', '89']
1 Push Elements
2 Pop Elements
3 Peek Element
4 Display Stack
5 Exit
5
Queue operstions:-
1. Enqueue: Adds an item to the queue.
2. Dequeue: Removes an item to the queue.
3. Front: Get the front item from queue.
4. Rear: Get the last item from
[241]: l=[]
while True:
c=int(input('''
1 Push Elements
2 Pop first Element
3 Front Element
4 Last Element
5 Display Elements
6 Exit
'''))
if c==1:
n=input("Enter an Element");
l.append(n)
print(l)
41
elif c==2:
if len(l)==0:
print("Empty Queue")
else:
del l[0]
print("removing first element",l)
elif c==3:
if len(l)==0:
print("Empty Queue")
else:
print("First element is:-",l[0])
elif c==4:
if len(l)==0:
print('Empty queue')
else:
print("Last element is:-",l[-1])
elif c==5:
if len(l)==0:
print("Empty Queue")
else:
print("Elements are:-",l)
elif c==6:
break;
1 Push Elements
2 Pop first Element
3 Front Element
4 Last Element
5 Display Elements
6 Exit
1
Enter an Element 57
['57']
1 Push Elements
2 Pop first Element
3 Front Element
4 Last Element
42
5 Display Elements
6 Exit
1
Enter an Element 1
['57', '1']
1 Push Elements
2 Pop first Element
3 Front Element
4 Last Element
5 Display Elements
6 Exit
1
Enter an Element 12
['57', '1', '12']
1 Push Elements
2 Pop first Element
3 Front Element
4 Last Element
5 Display Elements
6 Exit
1
Enter an Element 14
['57', '1', '12', '14']
1 Push Elements
2 Pop first Element
3 Front Element
4 Last Element
5 Display Elements
6 Exit
2
removing first element ['1', '12', '14']
1 Push Elements
2 Pop first Element
3 Front Element
4 Last Element
5 Display Elements
6 Exit
3
First element is:- 1
43
1 Push Elements
2 Pop first Element
3 Front Element
4 Last Element
5 Display Elements
6 Exit
4
Last element is:- 14
1 Push Elements
2 Pop first Element
3 Front Element
4 Last Element
5 Display Elements
6 Exit
5
Elements are:- ['1', '12', '14']
1 Push Elements
2 Pop first Element
3 Front Element
4 Last Element
5 Display Elements
6 Exit
6
. Mutable
. Unorderd
. Key | Value
. {}
eg. d={'Name':'Python'}
[251]: d['Name']
[251]: 'Python'
44
[252]: d['Fees']
[252]: 3500
[253]: for n in d:
print(n)
print(d[n])
Name
Python
Fees
3500
Duration
3 Months
. get()
. keys()
. values()
. items()
. pop()
. dict()
. update()
. clear()
. del
[254]: d={'Name':'Python',
'Fees':3000,
'Duration':'2 Months'
}
[255]: n=d.get('Name')
n
[255]: 'Python'
[256]: f=d.get('Fees')
f
[256]: 3000
Name
Fees
45
Duration
Python
3000
2 Months
('Name', 'Python')
('Fees', 3000)
('Duration', '2 Months')
Name : Python
Fees : 3000
Duration : 2 Months
[262]: d
[263]: a=d.pop('Name')
d
[264]: a
[264]: 'Python'
[266]: d
[267]: d.update({'Fees':3500})
d
46
[268]: d.clear()
[269]: d
[269]: {}
Name : Python
Duration : 2 Months
[272]: d
[275]: print(course['C'])
[276]: print(course['C']['Fees'])
2000
47
[277]: for a,b in course.items():
print(a,b['Fees'],b['Duration'])
[278]: course['C']['Fees']=1800
[279]: course
eg. a=(20,30,40,50)
[280]: a=(20,30,40,50)
a
[281]: type(a)
[281]: tuple
[282]: a[1]
[282]: 30
[283]: b=('app',10,30)
type(b)
[283]: tuple
[284]: for c in a:
print(c)
20
30
48
40
50
␣
,→---------------------------------------------------------------------------
<ipython-input-285-7413bba6c627> in <module>
----> 1 for c in range(l):
2 print(c)
[ ]: for c in range(l):
print(a[c])
[ ]: t=(10,20,30,40)
l=len(t)
␣
,→ ---------------------------------------------------------------------------
<ipython-input-286-c91307ca034e> in <module>
----> 1 for a in range(l):
2 print(t[a])
49
20.6.1 Functions used in tuple
. Min
. Max
. Count
. Index
. Sum
[287]: l=(1,2,1,3,2,4,5,2,6,2,9)
type(l)
[287]: tuple
[288]: m=min(l)
m
[288]: 1
[289]: ma=max(l)
ma
[289]: 9
[290]: c=l.count(2)
c
[290]: 4
[291]: I=l.index(3)
I
[291]: 3
[292]: i1=l.index(9)
i1
[292]: 10
[293]: S=sum(l)
S
[293]: 37
[294]: x=sum(l,30)
x
[294]: 67
50
20.7 39. Set in python
. Unordered
. Mutable
. Unindex
. {} / set()
. unique element
[295]: s={10,20,30}
type(s)
[295]: set
[296]: s
[297]: for a in s:
print(a)
10
20
30
. set()
. add()
. pop()
. remove()
. clear()
. discard()
. update()
[298]: l=[10,20,30]
s=set(l)
s
[299]: type(s)
[299]: set
[300]: s.add(40)
[301]: s
51
[301]: {10, 20, 30, 40}
[302]: s.pop()
[302]: 40
[303]: s
[304]: s.remove(20)
s
[305]: s.discard(10)
[306]: s
[306]: {30}
[307]: s.clear()
[308]: print(s)
set()
[309]: l={1,2,3,4}
[310]: a=(5,6,7)
[311]: l.update(a)
[312]: l
[312]: {1, 2, 3, 4, 5, 6, 7}
### Function: it is a block of statements which can be used repetively in a program. . Simple
function . Function with arguments . Return type function
[313]: def abc(): # defining simple function
print("This is my simple function")
[314]: abc()
52
This is my simple function
[316]: a=15
b=-1
sum(a,b)
[318]: mul(110,2)
[319]: mul(5)
[321]: out=divi(20,10)
[322]: print(out)
2.0
[324]: s=squ(5)
[325]: s
[325]: 25
[327]: S=squ(5)
S
53
[327]: (25, 15)
Make a function in Python which take two numbers from user and perform add, sub
mul, div
[331]: def My_Mini_Calculator():
number_1 = float(input("Enter the first number: "))
number_2 = float(input("Enter the second number: "))
# Addition
result = number_1 + number_2
print("The sum is:", result)
# Subtraction
result = number_1 - number_2
print("The difference is:", result)
# Multiplication
result = number_1 * number_2
print("The product is:", result)
# Division
result = number_1 / number_2
print("The quotient is:", result)
54
number_2 = float(input("Enter the second number: "))
# Addition
add_result = number_1 + number_2
# Subtraction
diff_result = number_1 - number_2
# Multiplication
mult_result = number_1 * number_2
# Division
div_result = number_1 / number_2
return {
"Addition": add_result,
"Substraction": diff_result,
"Multiplication": mult_result,
"Division": div_result,
}
55
# Capitalize the first letter of the last name
formatted_last_name = last_name.capitalize()
here are some key points about lambda functions in Python, each point is a one-liner:
Lambda functions are small, anonymous functions defined with the lambda keyword.
They can take any number of arguments but can only have one expression.
The expression is evaluated and returned when the function is called.
Lambda functions do not require a return statement, the expression is implicitly returned.
They can be used wherever function objects are required, like inside functions like map(), filter(),
and reduce().
You can’t include statements like loops, if, or else in lambda functions; only expressions are allowed.
56
Lambda functions are useful for small tasks that are not reused throughout your code.
They can be assigned to variables and used like regular functions.
[335]: # lambda arguments: expression
add = lambda x, y: x + y
print(add(5, 3)) # Output: 8
[336]: # Define a lambda function that takes three arguments and returns their sum
add_three_numbers = lambda x, y, z: x + y + z
16
25
Hello World
even
60
57
[342]: add = lambda: int(input("Enter first number: ")) + int(input("Enter second␣
,→number: "))
print(add())
products = [
{'name': 'Laptop', 'price': 50000},
{'name': 'Mobile', 'price': 30000},
{'name': 'Ipad', 'price': 45000},
{'name': 'Desktop', 'price': 35000},
]
20.10 Recursion
Recursion refers to the programming technique in which a function defines itself by calling itself.
Here are a few highlights:
58
Recursion occurs when a function calls itself while providing a different input for each consecutive
call.
Base Case: To prevent unbounded recursion, every recursive function should have a base case,
which is a condition under which it stops invoking itself.
The execution context or state of each recursive call is different. The current values of a function’s
parameters and variables are placed onto the call stack when it calls itself.
Problem-Solving: Recursion is frequently used to solve problems that can be divided into smaller,
simpler problems of the same type.
Memory: Because recursive functions must retain stack frames for all recursive calls, they consume
more memory than iterative versions.
Efficiency: Because of the complexity of maintaining the stack, recursive functions can be less
efficient and can result in a stack overflow for deep recursion.
Readability: Despite potential inefficiencies, recursion can result in easier-to-read and write code
for certain issues, such as traversing tree-like data structures, sorting algorithms (such as quicksort
and mergesort), solving Tower of Hanoi, Fibonacci series, and so on.
Remember that recursion is a tool, and whether or not to utilise it depends on the particular
problem you’re attempting to solve. Some issues lend themselves nicely to recursive solutions,
while others may benefit from an iterative approach.
[356]: def recursive_sum(n):
# Base case
if n == 1:
return 1
# Recursive case
else:
return n + recursive_sum(n - 1)
print(recursive_sum(12))
78
The Fibonacci sequence is a set of numbers in which each number is the sum of the two numbers
before it. It usually starts with 0 and 1. In certain variants, it begins with two 1’s.
Here’s the beginning of the Fibonacci sequence:
0, 1, 1, 2, 3, 5, 8, 13, 21, ...
59
You can see the pattern:
0+1=1
1+1=2
1+2=3
2+3=5
3+5=8
...
Each number is the sum of the two numbers before it.
[358]: def fibonacci(n):
if n<=1:
return n
else:
return fibonacci(n-1)+fibonacci(n-2)
print(fibonacci(6))
my_fibonacci(7)
0
1
1
2
3
5
8
def my_fibonacci(n):
global cnt
if n <= 0:
return []
elif n == 1:
60
return [0]
elif n == 2:
return [0, 1]
else:
fibonacci_series = my_fibonacci(n - 1)
print(f"Step {cnt}: Our Fibonacci series up to n-1 terms =␣
,→{fibonacci_series}")
cnt += 1
next_term = fibonacci_series[-1] + fibonacci_series[-2]
print(f"Step {cnt}: Next term to add = {next_term}")
cnt += 1
fibonacci_series.append(next_term)
print(f"Step {cnt}: Our Fibonacci series after adding next term =␣
,→{fibonacci_series}")
cnt += 1
return fibonacci_series
21 Exception handling
61
TypeError: Raised when an operation or function is applied to an object of inappropriate type.
ValueError: Raised when a built-in operation or function receives an argument that has the right
type but an inappropriate value.
IndexError: Raised when a sequence subscript is out of range.
KeyError: Raised when a dictionary key is not found.
FileNotFoundError: Raised when a file or directory is requested but doesn’t exist.
IOError: Raised when an I/O operation (such as a print statement, the built-in open() function or
a method of a file object) fails for an I/O-related reason.
ImportError: Raised when an import statement fails to find the module definition or when a from
... import fails to find a name that is to be imported.
MemoryError: Raised when an operation runs out of memory.
OverflowError: Raised when the result of an arithmetic operation is too large to be expressed by
the normal number format.
AttributeError: Raised when an attribute reference or assignment fails.
SyntaxError: Raised when the parser encounters a syntax error.
IndentationError: Raised when there is incorrect indentation.
NameError: Raised when a local or global name is not found.
|
Role of Try and Except:
try block: The code within the try block contains the statements that may potentially raise an
exception. It allows you to specify the section of code that you want to monitor for exceptions.
except block: If an exception occurs within the try block, the corresponding except block(s) are
executed. The except block allows you to define the actions or code that should be executed when
a specific exception is raised. You can have multiple except blocks to handle different types of
exceptions.
The else block allows you run code without errors.
The finally block executes code regardless of the try-and-except blocks.
Use the raise keyword to throw (or raise) an exception.
22 User-defined Exceptions
By deriving a new class from the default Exception class in Python, we can define our own exception
types.
[361]: class MyCustomError(Exception):
pass
62
In the above code, MyCustomError is derived from the built-in Exception class. You can use this
in your code by using the raise statement.
[362]: raise MyCustomError("This is a custom error")
␣
,→---------------------------------------------------------------------------
<ipython-input-362-95d924fa6573> in <module>
----> 1 raise MyCustomError("This is a custom error")
try:
input_num = int(input("Enter a age: "))
if input_num < n:
raise WrongAge # calling your custom exception
else:
print("You can work")
except WrongAge:
print("Invalid Age: You are not allowed to work")
Enter a age: 24
You can work
23 Logging
Logging is a technique for monitoring events that take place when some software is in use.
For the creation, operation, and debugging of software, logging is crucial.
There are very little odds that you would find the source of the issue if your programme fails and
you don’t have any logging records.
63
Additionally, it will take a lot of time to identify the cause.
[375]: # first import the logging library
import logging
""" In the code above, we first import the logging module, then we call the
basicConfig method to configure the logging.
We set the level to DEBUG, which means that all logs of level
DEBUG and above will be tracked."""
logging.basicConfig(level=logging.DEBUG)
64
23.1 Debug
logging.basicConfig(level=logging.DEBUG)
add(1, 2)
[376]: 3
23.2 Info
logging.basicConfig(level=logging.INFO)
def login(user):
logging.info('User %s logged in', user)
login('Admin User')
23.3 Warning
logging.basicConfig(level=logging.WARNING)
def MyBalance(amount):
if amount < 40000:
logging.warning('Sorry you have Low balance: %s', amount)
MyBalance(10000)
23.4 Error
logging.basicConfig(level=logging.ERROR)
65
def LetUsDivide(n, d):
try:
result = n / d
except ZeroDivisionError:
logging.error('You are trying to divide by zero, which is not allowed')
else:
return result
LetUsDivide(4, 0)
logging.basicConfig(level=logging.CRITICAL)
def LetUsCheckSystem(sys):
if sys != 'OK':
logging.critical('System failure: %s', sys)
[381]: import os
[382]: import os
print(os.getcwd())
66
[383]: import os
import logging
# Set up logging
# Get a logger instance (this will fetch the root logger)
logger = logging.getLogger()
def LetUsCheckSystem(sys):
if sys != 'OK':
logging.critical('System failure: %s', sys)
67
print(addition(5, 7))
␣
---------------------------------------------------------------------------
,→
<ipython-input-384-592f3c84c557> in <module>
6 return result
7
----> 8 print(addition(5, 7))
<ipython-input-384-592f3c84c557> in addition(a, b)
2
3 def addition(a, b):
----> 4 pdb.set_trace() # Set a breakpoint here
5 result = a + b
6 return result
Math module
- math.ceil(a)
- math.fabs(x): Returns absolute value
- math.factorial(a)
- math.floor(a)
- math.fsum(a)
[385]: import math
x=150.5251
print(math.ceil(x))
151
[386]: y=-10
print(math.fabs(y))
10.0
68
[387]: x=4
print(math.factorial(x))
24
[388]: print(math.factorial(6))
720
[389]: z=12.526
print(math.floor(z))
12
[390]: Z=[10,25,52,52]
print(math.fsum(Z))
139.0
. Randint()
. Randrange()
. Randchoice()
[391]: import random
[392]: n=random.randint(0,10)
print(n)
[393]: n=random.randrange(1,25)
[394]: n
[394]: 7
[395]: l=[12,10,15,20]
random.choice(l)
[395]: 10
[396]: print(lc)
␣
---------------------------------------------------------------------------
,→
69
NameError Traceback (most recent call␣
last)
,→
<ipython-input-396-ffa623b2e61f> in <module>
----> 1 print(lc)
[397]: random.shuffle(l)
print(l)
[399]: print(x)
2023-08-11 03:32:08.831010
[400]: print(datetime.datetime(2023,8,9))
2023-08-09 00:00:00
[ ]:
[ ]:
[ ]:
[ ]:
[ ]:
[ ]:
[ ]:
[ ]:
[ ]:
70
[ ]:
[ ]:
[ ]:
[ ]:
[ ]:
[ ]:
[ ]:
[ ]:
[ ]:
[ ]:
[ ]:
[ ]:
[ ]:
[ ]:
[ ]:
[ ]:
[ ]:
[ ]:
[ ]:
[ ]:
[ ]:
[ ]:
71