Full Python Notes
Full Python Notes
Day-1
Python
--- Guido Van Rossum is the person who created python programming language in the year 1991.
Programming Language : The language which is used communicate with the system.
Features of Python:
• It is scripted language.
Python Page 1
• It is multi-paradigm - A code can be written in multiple ways.
• It is open source.
Free to download and we can contribute the code for python.
numpy and pandas libraries are the examples of these.
• It is platform Independent.
What is Python?
--- It is high level , general purpose programming language.
Day-2
Library Functions:
They are functions which are predefined by the developer to perform specific task.
We can only access them but we cannot modify them.
Types:
• Keywords
• Inbuilt functions
• Operator / Special symbols
Python Page 2
• Operator / Special symbols
1) Keywords
--- They are universally standard words which are predefined by the developer to perform specific
task.
import keyword
keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue',
'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is',
'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
len(keyword.kwlist)
35
Proof:
a=10
a
10
a = True
a
True
a = False
a
False
a = None
a = if
SyntaxError: invalid syntax
a = and
SyntaxError: invalid syntax
Variable:
--- It is a container which is used to store the address of the value.
Or
It is a name given to memory location where we store the value.
Syntax:
Memory allocation:
Python Page 3
Memory allocation:
id():
--- It is used to get the actual address of the value stored in the memory.
Syntax:
a
10
id(a)
140722490471496
id(10)
140722490471496
Syntax:
Example 1:
Proof:
a,b,c = 10,20,30
a
10
Python Page 4
10
b
20
c
30
id(a)
140722490471496
id(b)
140722490471816
id(c)
140722490472136
Proof:
a,b,c,d=10,20,10,20
id(a)
140722490471496
id(c)
140722490471496
id(b)
140722490471816
id(d)
140722490471816
Python Page 5
Proof:
a,a,a=10,20,30
a
30
Reference count:
--- It will count the number of variables sharing the same value. When reference count becomes zero
It will deleted from memory and collected by garbage collector.
All the variables are identifiers but all the identifiers are not variables.
Rules of Identifier:
Proof:
if = 10
SyntaxError: invalid syntax
and = 10
SyntaxError: invalid syntax
True = 10
SyntaxError: cannot assign to True
Python Page 6
3) Identifier should not contain any special character except underscore( _ )
Special character = !@#$%^&*()_+{}:"<>,.?/|[]~`
Reason: All the special keywords are predefined with some task except underscore.
Proof
a_b = 10
a_b
10
ab_ = 10
ab_
10
_ = 10
_
10
a+b = 20
SyntaxError: cannot assign to expression here. Maybe you meant '==' instead of '='?
Proof:
a =10
Proof:
a = 10
a
10
a2 = 20
a2
20
_ = 30
_
30
Proof:
Python Page 7
Proof:
fvmsnvjdsjfljdsnjfkhdsKFNDSFJHDHFJDSJFdbfjjDFHjfhdskflkdjvlks = 10
fvmsnvjdsjfljdsnjfkhdsKFNDSFJHDHFJDSJFdbfjjDFHjfhdskflkdjvlks
10
a = 10
a
10
Day-3
Datatypes:
- It is going to specify the size and type of the value stored inside the variable.
1) Integer(int):
--- It is a real number without decimal point.
Default value : It is an initial value and they are internally equal to False.
Non-default value: The values except default values. They are internally equal to True.
Whenever we want to check the value is default or not we use bool() function.
Proof:
a = 10
Python Page 8
a = 10
type(a)
<class 'int'>
bool(a)
True
b=0
bool(b)
False
2) Float:
--- It is a real number with decimal point.
Proof:
a = 5.7
type(a)
<class 'float'>
bool(a)
True
b = 0.
c = 0.0
bool(c)
False
.
SyntaxError: invalid syntax
1.
1.0
.8
0.8
3) Complex:
--- It is combination of real and imaginary part.
Proof:
a = 2+3j
a
(2+3j)
type(a)
<class 'complex'>
bool(a)
True
b = 0j
bool(b)
Python Page 9
bool(b)
False
c = 3j+2
c
(2+3j)
d = 2+j3
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
d = 2+j3
NameError: name 'j3' is not defined
e = 2+3J
e
(2+3j)
g = 2+4i
SyntaxError: invalid decimal literal
4) Boolean:
--- It consists of only 2 values.
• True
• False
10>20
False
3>1
True
True + True
2
False + False
0
True + False
1
Multivalued Datatype:
5) String:
--- It is defined as the collection of characters enclosed by quotes('' ," " , ''' ''').
Syntax:
Python Page 10
Syntax:
a = 'good morning'
a
'good morning'
a = "good morning"
a
'good morning'
a = '''good morning'''
a
'good morning'
b = "Python's Coders are smart"
b
"Python's Coders are smart"
c = 'h1'
d = 'hi'
dfdsf
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
dfdsf
NameError: name 'dfdsf' is not defined
a = '''hi
hello
bye'''
a
'hi\nhello\nbye'
Memory allocation:
Indexing: The process of passing subaddress to the memory block is called Indexing.
Python Page 11
Types:
• +ve indexing (left to right)
• -ve indexing (right to left)
a = 'hello'
a[4]
'o'
a[-1]
'o'
a[4]='e'
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
a[4]='e'
TypeError: 'str' object does not support item assignment
6) List:
--- It is collection of homogeneous and heterogenous values enclosed by [].
homogeneous : [10,20,30,40]
heterogenous : [10,2.3,4+7j,True,'hello',[10,20]]
Syntax:
Python Page 12
a = [79.8,True,'hi',2+3j,'Star',[1,2,3]]
a[1]
True
a[4]
'Star'
a[4][3]
'r'
a[5]
[1, 2, 3]
a[5][1]
2
a = [79.8,True,'hi',2+3j,'Star',[1,2,3]]
a[1]
True
a[1]=False
a
[79.8, False, 'hi', (2+3j), 'Star', [1, 2, 3]]
Day-4
a=[10,20,30]
a.append(40)
a
[10, 20, 30, 40]
a.append(50)
a
[10, 20, 30, 40, 50]
• insert(): whenever we want to add the value to the particular index in the list.
syntax: var.insert(index,val)
l=[10,20,30]
Python Page 13
l=[10,20,30]
l.insert(1,40)
l
[10, 40, 20, 30]
l.insert(40)
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
l.insert(40)
TypeError: insert expected 2 arguments, got 1
a=[10,20,30]
a.insert(10,40)
a
[10, 20, 30, 40]
• pop(): To eliminate a value from the list when we know the index.
syntax: var.pop() ----- last value get removed
var.pop(index) ---- remove value based on index position.
a=[10,20,30,40]
a.pop()
40
a
[10, 20, 30]
a.pop(1)
20
a
[10, 30]
• remove(): used to eliminate a value from the list when we don’t know the index.
syntax: var.remove(val)
a=[10,20,30,40]
a.remove(30)
a
[10, 20, 40]
a.remove(30)
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
a.remove(30)
ValueError: list.remove(x): x not in list
a.remove(20)
a
[10, 40]
7) Tuple:
--- It is collection of homogeneous and heterogenous values enclosed by parenthesis ().
Syntax:
a = (10,)
type(a)
<class 'tuple'>
Memory allocation:
t = (10,2.3,2+3j,True,'hi',[10,20],(1,2))
Python Page 14
t = (10,2.3,2+3j,True,'hi',[10,20],(1,2))
t[3]
True
t[6]
(1, 2)
t[3]=False
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
t[3]=False
TypeError: 'tuple' object does not support item assignment
8) Set:
--- It is collection of homogeneous and heterogenous values enclosed by parenthesis {}.
Syntax:
a = [10,20,30,40]
a
[10, 20, 30, 40]
a = {10,20,30,40}
a
{40, 10, 20, 30}
s = {10,2.3,4+7j,True,'hi',(10,20)}
s
{'hi', True, 2.3, (4+7j), 10, (10, 20)}
s = {10,2.3,4+7j,True,'hi',[3,4],(10,20)}
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
s = {10,2.3,4+7j,True,'hi',[3,4],(10,20)}
TypeError: unhashable type: 'list'
a = [1,2,1,2]
Python Page 15
a = [1,2,1,2]
a
[1, 2, 1, 2]
a = (1,2,1,2)
a
(1, 2, 1, 2)
a = {1,2,1,2}
a
{1, 2}
Memory allocation:
s = {10,2.3,4+7j,True,'hi',(10,20)}
Inbuilt Functions:
a={10,20,30,40,50}
a
{50, 20, 40, 10, 30}
a.add(60)
a
{50, 20, 40, 10, 60, 30}
a
{50, 20, 40, 10, 60, 30}
a.remove(40)
a
{50, 20, 10, 60, 30}
a
{50, 20, 10, 60, 30}
Python Page 16
{50, 20, 10, 60, 30}
a.pop()
50
a
{20, 10, 60, 30}
a.pop()
20
a
{10, 60, 30}
a.pop()
10
a
{60, 30}
a.pop()
60
a
{30}
a.pop()
30
a
set()
Conclusion: Set is mutable datatype.
9) Dictionary:
--- It is a collection of key value pair which are enclosed by {}.
Syntax:
d = {1:1,2.3:2.3,2+3j:2+3j,True:True,'a':'a',(10,20):(10,20)}
d
{1: True, 2.3: 2.3, (2+3j): (2+3j), 'a': 'a', (10, 20): (10, 20)}
d = {1:1,2.3:2.3,2+3j:2+3j,True:True,'a':'a',(10,20):(10,20),[10]:[10]}
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
d = {1:1,2.3:2.3,2+3j:2+3j,True:True,'a':'a',(10,20):(10,20),[10]:[10]}
TypeError: unhashable type: 'list'
d={'a':1,'b':2,'c':3,'a':4}
d
{'a': 4, 'b': 2, 'c': 3}
Memory allocation:
Python Page 17
Memory allocation:
d = {1:1,2.3:2.3,2+3j:2+3j,True:True,'a':'a',(10,20):(10,20)}
a={10:20,2.3:7,(2+4j):[10,20],True:'a','hi':{10,20},(10,20):{'a':10}}
a
{10: 20, 2.3: 7, (2+4j): [10, 20], True: 'a', 'hi': {10, 20}, (10, 20): {'a': 10}}
a[(2+4j)]
[10, 20]
a[True]
'a'
a['hi']
{10, 20}
If we want to modify or add the value, we can use the syntax
var[key]=new_value
a={10:20,2.3:7,(2+4j):[10,20],True:'a','hi':{10,20},(10,20):{'a':10}}
a[(10,20)]
{'a': 10}
a[(10,20)]={'b':20}
a
{10: 20, 2.3: 7, (2+4j): [10, 20], True: 'a', 'hi': {10, 20}, (10, 20): {'b': 20}}
a[3.5]='hello'
a
{10: 20, 2.3: 7, (2+4j): [10, 20], True: 'a', 'hi': {10, 20}, (10, 20): {'b': 20}, 3.5: 'hello'}
Slicing:
--- The process of extracting the group of values from the collections.
Syntax:
Python Page 18
• Whenever we are traversing / extracting the values from right to lx`eft
Example:
s = 'India is best'
Proof:
s = 'India is best'
s[0:5:1]
'India'
s[9:13:1]
'best'
s[0:7:2]
'Idai'
s[7:12:2]
'sbs'
s[-9:-14:-1]
'aidnI'
s[-1:-5:-1]
'tseb'
s[-7:-14:-1]
'i aidnI'
s[-7:-14:-2]
'iadI'
s[-2:-7:-2]
'sbs'
Slicing shortcuts:
○ If SI is 0 or SI is -1
var[:EI+-1:updation]
○ If updation is +1
var[SI:EI:]
Proof:
Python Page 19
Proof:
s = 'India is best'
s[0:12+1:1]
'India is best'
s[::]
'India is best'
s[::-1]
'tseb si aidnI'
Day-5
Syntax:
Note:
• From SVDT to MVDT conversion only string is supported.
• From MVDT to SVDT conversion only bool is supported.
a = 10
float(a)
10.0
complex(a)
(10+0j)
complex(a,a)
(10+10j)
bool(a)
True
str(a)
'10'
list(a)
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
list(a)
TypeError: 'int' object is not iterable
tuple(a)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
tuple(a)
TypeError: 'int' object is not iterable
set(a)
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
set(a)
TypeError: 'int' object is not iterable
dict(a)
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
dict(a)
TypeError: 'int' object is not iterable
Python Page 20
2) Converting float to other datatypes:
a = 2.3
int(a)
2
float(a)
2.3
complex(a)
(2.3+0j)
complex(a,a)
(2.3+2.3j)
bool(a)
True
str(a)
'2.3'
list(a)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
list(a)
TypeError: 'float' object is not iterable
tuple(a)
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
tuple(a)
TypeError: 'float' object is not iterable
set(a)
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
set(a)
TypeError: 'float' object is not iterable
dict(a)
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
dict(a)
TypeError: 'float' object is not iterable
a = 2+3j
int(a)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
int(a)
TypeError: int() argument must be a string, a bytes-like
object or a real number, not 'complex'
float(a)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
float(a)
TypeError: float() argument must be a string or a
real number, not 'complex'
bool(a)
True
str(a)
'(2+3j)'
list(a)
Traceback (most recent call last):
Python Page 21
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
list(a)
TypeError: 'complex' object is not iterable
tuple(a)
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
tuple(a)
TypeError: 'complex' object is not iterable
set(a)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
set(a)
TypeError: 'complex' object is not iterable
dict(a)
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
dict(a)
TypeError: 'complex' object is not iterable
a= True
int(a)
1
float(a)
1.0
complex(a)
(1+0j)
complex(a,a)
(1+1j)
bool(a)
True
str(a)
'True'
list(a)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
list(a)
TypeError: 'bool' object is not iterable
tuple(a)
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
tuple(a)
TypeError: 'bool' object is not iterable
set(a)
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
set(a)
TypeError: 'bool' object is not iterable
dict(a)
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
dict(a)
TypeError: 'bool' object is not iterable
Python Page 22
5) Converting string to other datatypes:
a = 'hi'
int(a)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
int(a)
ValueError: invalid literal for int() with base 10: 'hi'
a = '78'
int(a)
78
float(a)
78.0
complex(a)
(78+0j)
complex(a,a)
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
complex(a,a)
TypeError: complex() can't take second arg if first is a string
complex(a,78)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
complex(a,78)
TypeError: complex() can't take second arg if first is a string
complex(78,a)
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
complex(78,a)
TypeError: complex() second arg can't be a string
bool(a)
True
list(a)
['7', '8']
tuple(a)
('7', '8')
set(a)
{'7', '8'}
dict(a)
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
dict(a)
ValueError: dictionary update sequence element #0 has length 1; 2 is required
a = [10,20]
int(a)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
int(a)
TypeError: int() argument must be a string,
a bytes-like object or a real number, not 'list'
float(a)
Traceback (most recent call last):
Python Page 23
a bytes-like object or a real number, not 'list'
float(a)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
float(a)
TypeError: float() argument must be a string
or a real number, not 'list'
complex(a)
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
complex(a)
TypeError: complex() first argument must be a string or a number, not 'list'
bool(a)
True
str(a)
'[10, 20]'
complex(a)
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
complex(a)
TypeError: complex() first argument must be a string or a number, not 'list'
tuple(a)
(10, 20)
set(a)
{10, 20}
dict(a)
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
dict(a)
TypeError: cannot convert dictionary update sequence element #0 to a sequence
a = ['ab',[10,20],(1,2)]
dict(a)
{'a': 'b', 10: 20, 1: 2}
a = (1,2,3)
int(a)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
int(a)
TypeError: int() argument must be a string,
a bytes-like object or a real number, not 'tuple'
float(a)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
float(a)
TypeError: float() argument must be a string or
a real number, not 'tuple'
complex(a)
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
complex(a)
TypeError: complex() first argument must be a string or a number, not 'tuple'
bool(a)
True
str(a)
Python Page 24
str(a)
'(1, 2, 3)'
list(a)
[1, 2, 3]
set(a)
{1, 2, 3}
dict(a)
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
dict(a)
TypeError: cannot convert dictionary update sequence element #0 to a sequence
a = ('hi',[1,2],(7,8))
dict(a)
{'h': 'i', 1: 2, 7: 8}
a = {1,2,3}
int(a)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
int(a)
TypeError: int() argument must be a string,
a bytes-like object or a real number, not 'set'
float(a)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
float(a)
TypeError: float() argument must be a string or
a real number, not 'set'
complex(a)
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
complex(a)
TypeError: complex() first argument must be a string or a number, not 'set'
bool(a)
True
str(a)
'{1, 2, 3}'
list(a)
[1, 2, 3]
tuple(a)
(1, 2, 3)
dict(a)
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
dict(a)
TypeError: cannot convert dictionary update sequence element #0 to a sequence
a = {'ab',(10,20)}
dict(a)
{'a': 'b', 10: 20}
d={'a':10,'b':20,'c':30}
int(d)
Traceback (most recent call last):
Python Page 25
d={'a':10,'b':20,'c':30}
int(d)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
int(d)
TypeError: int() argument must be a string,
a bytes-like object or a real number, not 'dict'
float(d)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
float(d)
TypeError: float() argument must be a string
or a real number, not 'dict'
complex(d)
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
complex(d)
TypeError: complex() first argument must be a string or a number, not 'dict'
bool(d)
True
str(d)
"{'a': 10, 'b': 20, 'c': 30}"
list(d)
['a', 'b', 'c']
list(d.values())
[10, 20, 30]
list(d.items())
[('a', 10), ('b', 20), ('c', 30)]
tuple(d)
('a', 'b', 'c')
tuple(d.values())
(10, 20, 30)
tuple(d.items())
(('a', 10), ('b', 20), ('c', 30))
set(d)
{'b', 'a', 'c'}
set(d.values())
{10, 20, 30}
set(d.items())
{('c', 30), ('b', 20), ('a', 10)}
dict(d)
{'a': 10, 'b': 20, 'c': 30}
Copy Operations:
--- The process of copying the content from one variable to another variable.
Objective : After copying the content we are doing modification for source variable and checking whether it is
affecting the destination variable or not.
Types:
Python Page 26
1) General Copy:
--- It will copy the variable space of one variable to another.
Syntax:
Memory allocation:
l = [10,2.5,'Code',[5.7,9j]]
p=l
l = [10,2.5,'Code',[5.7,9j]]
p=l
l
[10, 2.5, 'Code', [5.7, 9j]]
p
[10, 2.5, 'Code', [5.7, 9j]]
l[0]
10
l[0] = 55
l
[55, 2.5, 'Code', [5.7, 9j]]
p
[55, 2.5, 'Code', [5.7, 9j]]
id(l)
2100232167296
id(p)
2100232167296
Conclusion : Modification done with respect to source variable will affect the destination variable.
1) Shallow Copy:
--- It will copy the main memory layer of value space of one variable to another.
Syntax:
Memory allocation:
l = [10,2.5,'Code',[5.7,9j]]
p = l.copy()
Python Page 27
`
l = [10,2.5,'Code',[5.7,9j]]
p = l.copy()
l
[10, 2.5, 'Code', [5.7, 9j]]
p
[10, 2.5, 'Code', [5.7, 9j]]
id(l)
2971226709888
id(p)
2971278821696
l[1]
2.5
l[1]=15
l
[10, 15, 'Code', [5.7, 9j]]
p
[10, 2.5, 'Code', [5.7, 9j]]
l[3]
[5.7, 9j]
l[3][0]
5.7
l[3][0] = 6.0
l
[10, 15, 'Code', [6.0, 9j]]
p
[10, 2.5, 'Code', [6.0, 9j]]
id(l[3])
2971278690496
id(p[3])
2971278690496
Conclusion : Modification done with respect to linear collection of source variable will not affect the
destination variable but Modification done with respect to nested collection of source variable will affect the
destination variable.
2) Deep Copy:
--- It will copy the entire content of value space of one variable to another.
Python Page 28
Syntax:
Memory allocation:
l = [10,2.5,'Code',[5.7,9j]]
import copy
b = copy.deepcopy(l)
l = [10,2.5,'Code',[5.7,9j]]
import copy
b = copy.deepcopy(l)
l[1]
2.5
l[1]=5.9
l
[10, 5.9, 'Code', [5.7, 9j]]
b
[10, 2.5, 'Code', [5.7, 9j]]
id(l)
3025779802240
id(b)
3025779803200
l[3][1]
9j
l[3][1] = 2+3j
l
[10, 5.9, 'Code', [5.7, (2+3j)]]
b
[10, 2.5, 'Code', [5.7, 9j]]
id(l[3])
3025779524864
id(b[3])
3025779802944
Python Page 29
3025779802944
Conclusion : Modification done with respect to linear collection of source variable will not affect the
destination variable and Modification done with respect to nested collection of source variable will not
affect the destination variable.
Day-6
Operators:
--- They are the special symbols which is used to perform operations.
Types:
• Arithmetic Operator
• Logical Operator
• Relational Operator
• Bitwise Operator
• Assignment Operator
• Membership Operator
• Identity Operator
1) Arithmetic Operator :
• Addition(+):
For SVDT:
10+20
30
2.3+4.7
7.0
(2+4j) + (7+3j)
(9+7j)
True + False
1
17+9.2+(2+3j)+True
(29.2+3j)
For MVDT:
'hi' +'hello'
'hihello'
[10,20,30] + [40, 50]
[10, 20, 30, 40, 50]
(1,2,3)+(4,5,6)
(1, 2, 3, 4, 5, 6)
{1,2,3}+{4,5}
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
{1,2,3}+{4,5}
TypeError: unsupported operand type(s) for +: 'set' and 'set'
Python Page 30
TypeError: unsupported operand type(s) for +: 'set' and 'set'
{'a':10}+{'b':20}
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
{'a':10}+{'b':20}
TypeError: unsupported operand type(s) for +: 'dict' and 'dict'
• Subtraction(-):
For SVDT:
4-1
3
2.3 - 1.8
0.4999999999999998
(5+3j) - (3+7j)
(2-4j)
2.3 - 1.87
0.4299999999999997
2.3 - 1.8
0.4999999999999998
2.3 - 1.80
0.4999999999999998
True - False
1
For MVDT:
'hi'-'hello'
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
'hi'-'hello'
TypeError: unsupported operand type(s) for -: 'str' and 'str'
[10,20,30]-[10,20]
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
[10,20,30]-[10,20]
TypeError: unsupported operand type(s) for -: 'list' and 'list'
(10,20,30)-(10,20)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
(10,20,30)-(10,20)
TypeError: unsupported operand type(s) for -: 'tuple' and 'tuple'
{10,20,30}-{10,20}
{30}
{'a':10}-{'a':20}
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
{'a':10}-{'a':20}
TypeError: unsupported operand type(s) for -: 'dict' and 'dict'
• Multiplication(*):
For SVDT:
2+2+2+2+2+2+2+2
Python Page 31
For SVDT:
2+2+2+2+2+2+2+2
16
2*8
16
2.3 * 6.5
14.95
(2+3j) * (4+7j)
(-13+26j)
True * False
0
For MVDT:
a = 'hi' * 'hello'
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
a = 'hi' * 'hello'
TypeError: can't multiply sequence by non-int of type 'str'
'hi' * 3
'hihihi'
[10,20,30]*4
[10, 20, 30, 10, 20, 30, 10, 20, 30, 10, 20, 30]
(1,2,3)* 3
(1, 2, 3, 1, 2, 3, 1, 2, 3)
{1,2,3}*2
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
{1,2,3}*2
TypeError: unsupported operand type(s) for *: 'set' and 'int'
{'a':10}*2
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
{'a':10}*2
TypeError: unsupported operand type(s) for *: 'dict' and 'int'
6/3
2.0
3.3 / 1.7
1.9411764705882353
(2+3j) / (5+7j)
(0.41891891891891897+0.013513513513513507j)
True / False
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
True / False
ZeroDivisionError: division by zero
False / True
Python Page 32
False / True
0.0
'sakshi' / 'sakshi'
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
'sakshi' / 'sakshi'
TypeError: unsupported operand type(s) for /: 'str' and 'str'
6//3
2
2.3//1.7
1.0
2.3//1
2.0
(2+3j)//(2+3j)
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
(2+3j)//(2+3j)
TypeError: unsupported operand type(s) for //: 'complex' and 'complex'
True//True
1
True/True
1.0
○ Modulus (%):
--- It will give remainder as the answer and output will be displayed as it is.
10%3
1
2.3 % 4.5
2.3
(2+3j) % (2+3j)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
(2+3j) % (2+3j)
TypeError: unsupported operand type(s)
for %: 'complex' and 'complex'
True % True
0
2.3%4.6
2.3
Day-7
Proof:
2**3
Python Page 33
2**3
8
4.5 **2
20.25
(1+2j)**3
(-11-2j)
True **10
1
5**True
5
7**False
1
3.2 ** (2+3j)
(-9.626669455748416-3.490678328027451j)
2) Logical Operator :
○ Logical AND(and):When any one of the Operand is False, the result will be False.
Syntax:
Conditions to remember:
Proof:
3 and 7
7
0.0 and 9.8
0.0
2 and 0j
0j
[9.8] and 3.4
3.4
2 and 4 and 7
7
○ Logical OR(or):When any one of the Operand is True, the result will be True.
Syntax:
Python Page 34
Conditions to remember:
Proof:
'tea' or 'coffee'
'tea'
6 or 9
6
0 or 123
123
[] and ''
[]
[] or ''
''
78 or 34 or 5
78
67 and 23 or 89 and 45
23
Conditions to remember:
Proof:
Python Page 35
Proof:
not(3)
False
not('')
True
not(5j)
False
not(0.0)
True
• Equal to (==):
--- Used to check whether both the operands are same or not.
2 == 2.0
True
True == 1
True
3.4 == 4.5
False
[1,2,3] == (1,2,3)
False
{'a':20} == {'a':30}
False
[1,2,3] == [3,2,1]
False
{1,2,3,4} == {4,3,2,1}
True
Proof:
45 != 45
False
4!=9
True
'' != ' '
True
(1) != (1,)
True
• Greater than (>): It will not support for complex and dictionary.
--- Used to check whether the operand1 is greater than operand2 or not.
Python Page 36
• Greater than (>): It will not support for complex and dictionary.
--- Used to check whether the operand1 is greater than operand2 or not.
For MVDT :
ord('A')
65
ord('B')
66
ord('Z')
90
ord('a')
97
ord('b')
98
ord('z')
122
For Set : All the values of operand2 should be present in operand1, Then it will give True or it will give False.
Proof:
25 > 12
True
3.4 > 4.5
False
True > 1
False
'python' > 'abc'
True
ord('p')
112
ord('a')
97
'ABC' > 'abc'
False
'aBC' > 'abc'
False
[10,20,30] > [10,20,10]
True
[10,20,30] > [10,20,30]
False
(1,2,3,4) > (True,2,3,4.0)
False
{10,20,30,40}>{10,20}
Python Page 37
{10,20,30,40}>{10,20}
True
{10,20}>{10,20}
False
{10,20,30}>{10,20}
True
[10,20,30] >[10,20]
True
• Lesser than (<): It will not support for complex and dictionary.
--- Used to check whether the operand1 is lesser than operand2 or not.
For MVDT :
For Set : All the values of operand1 should be present in operand2, Then it will give True or it will give False.
Proof:
2 < 2.0
False
True < 1.7
True
'data' < 'engineer'
True
[10,20,30] < [10,20,10]
False
(12,24,56) < (12,335,456)
True
{12,True,'hello',0.0} <{'1','hello',3*4,False,78}
False
{12,True,'hello',0.0} <{1,'hello',3*4,False,78}
True
• Greater than or Equal to (>=): It will not support for complex and dictionary.
--- Used to check whether the operand1 is greater than or equal to operand2 or not.
Proof:
2>=2
True
Python Page 38
True
2.3 >= 1.9
True
False >= 0.0
True
False >= 0.000000008
False
'great'>='great'
True
{1,2,3}>{1,2,3}
False
{1,2,3}>={1,2,3}
True
[10,20,30]>=[30,10,20]
False
(1,2,7)>=(1,2,2*4-True)
True
• Lesser than or Equal to (<=): It will not support for complex and dictionary.
--- Used to check whether the operand1 is lesser than or equal to operand2 or not.
Proof:
Day-8
Python Page 39
○ Divide by 2 method.
bin(7)
'0b111'
bin(9)
'0b1001'
bin(12)
'0b1100'
• Bitwise AND(&):
Python Page 40
Proof:
3&8
0
15 & 21
5
11 & 18
2
• Bitwise OR(|):
Program:
3|8
11
15 | 21
31
Assignment : Take the rest of the previous bitwise and questions and do it for bitwise or.
• Bitwise NOT(~):
Proof:
~3
-4
~-12
11
Python Page 41
• Bitwise XOR(^):
Program:
3^8
11
15 ^ 21
26
Assignment : Take the rest of the previous bitwise and questions and do it for bitwise XOR.
Proof:
8 << 2
32
15 << 3
120
Python Page 42
• Bitwise right shift operator(>>):
Proof:
8>>2
2
15 >> 3
1
5) Assignment Operator(=):
---- It is used to assign the value to a variable.
Proof:
a = 10
a=a+3
a
13
a=a-3
a
10
a += 3
a
13
a -= 3
a
10
Python Page 43
7) Membership operator:
--- It is used to check if the value present inside the collection or not.
• in --- values present in collection. It returns True if the value is present inside the collection, else return
False.
• not in --- values not present in collection. It returns True if the value is not present inside the collection,
else return False.
45 not in [12,34,56]
True
p not in 'python'
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
p not in 'python'
NameError: name 'p' is not defined
'p' not in 'python'
False
'hl' not in 'hello'
True
'' not in 'python'
False
[] not in [10,20]
True
() not in (10,20)
True
[1] not in [1,2,3]
True
8) Identity Operator:
--- It is used to check whether both the operands are sharing the same address or not.
Types:
• is --- It will return True if both the operands are sharing the same address or else return False.
• is not --- It will return True if both the operands are not sharing the same address or else return False.
Proof:
a=10
b=20
c=10
a is b
False
a is c
True
b is c
False
a is not b x`
True
a is not c
False
b is not c
True
Day-9
• Input Statements:
--- We should never allow the user to modify the code instead just allow them to access the code.
Syntax:
Note: input() function will take input by default in the form of string.
If we want other datatype values like int, float, complex then we have to use type casting.
Python Page 45
Whenever we want to typecast to collection datatype they will store each character of string as a
value. In that condition use ,
• Output Statements:
--- Whenever we want to display the output in the screen we use this.
Syntax:
# Output Statement
'''
print(10,20,30,40)
print(10,20,30,40,sep='@')
print(10,20,30,40,sep='#',end='&') '''
Control Statements:
--- It is used to control the flow of execution.
Python Page 46
Conditional Statement:
--- It is used to control the flow of execution based on conditions.
1) Simple if:
--- It is a keyword which is used to check the condition and it will execute the True Statement Block
if the condition is True or else it will ignore the True statement block if the condition is False.
# Simple if
Python Page 47
n = int(input('Enter the number: '))
if n%3 ==0:
print(n**2)
'''
# program to check whether the number is 2 digit number
'''
n = int(input('Enter the number: '))
if n>9 and n<100:
print('2 digit number')
'''
'''
n = int(input('Enter the number: '))
if 9<n<100:
print('2 digit number')
'''
'''
n = int(input('Enter the number: '))
if 10<=n<=99:
print('2 digit number')'''
Day-10
2) if else:
--- Advance version of if. It is used to check the condition, if the condition is True it will execute the
True Statement block, or else It will execute the False Statement block.
Programs:
# elif
3) elif :
--- It is used to check the multiple conditions at a time. If the condition is True it will execute the
Statement block of that particular condition.
Python Page 49
Programs:
# elif
# Program to check whether the character is uppercase, lowercase, digit or special character
'''
ch = input('Enter the number: ')
if 'A'<=ch<='Z':
print(ch,' = Uppercase')
elif 'a'<=ch<='z':
print(ch,' = Lowercase')
elif '0'<=ch<='9':
print(ch,' = Digits')
else:
print(ch,' = Special Character') '''
4) Nested if:
--- condition inside another condition.
Python Page 50
Syntax: Flow diagram:
Programs:
# Nested if
# Login
un = input('Enter the username: ')
if un == username:
pw = input('Enter the password: ')
if pw == password:
print('Login Successful')
else:
print('Incorrect Password')
else:
print('Invalid Username')'''
Assignment :
• Find the greatest among 4 numbers
• Find the smallest among 4 numbers
Python Page 52
20 February 2025 18:46
Day-16
Control Statement:
--- It is used to control the flow of execution.
Types:
Conditional Statement:
--- It is used to control the flow of execution based on conditions.
1) Simple if:
--- It is a keyword which is used to check the condition and it will execute the statement block if
the condition is True or else it will ignore the statement block.
Programs:
# Simple if
2) if else:
--- It is used to check the condition and it will execute the True Statement block if the condition is
True else it will execute the False Statement block.
Programs:
# if else
Note:
abs (absolute function) - It will convert the negative numbers into positive numbers. If we
already have positive number it will keep as it is.
Day-17
3) elif:
--- Whenever we want to check the multiple conditions and to execute statement blocks of
each and every condition we use elif.
Programs:
# elif
# WAP to check whether the character is uppercase or lowercase or digits or special characters
'''
ch = input('Enter the character: ')
if 'A'<=ch<='Z':
print('character is uppercase')
elif 'a'<=ch<='z':
print('character is lowercase')
elif '0'<=ch<='9':
print('character is digit')
else:
print('character is special character')'''
# WAP to check whether the number is single digit or two digit or three digit or more than 3 digit.
'''
n = abs(int(input('Enter the number: ')))
if 0<=n<=9:
print('single digit')
elif 10<=n<=99:
print('two digit')
elif 100<=n<=999:
print('three digit')
else:
print('more than three digit')'''
4) Nested if:
--- Whenever it is necessary to check a condition before checking another condition we use Nested
if.
Programs:
# Nested if
Day-18
Looping Statement:
--- It is a control statement which will control the flow of execution by repeating the same task again
and again.
Types:
• While loop
• For loop
1) While loop:
Program concepts Page 6
1) While loop:
--- It is used to execute the same set of instructions again and again until the condition become
False.
Note:
○ Initialization
○ Updation
Programs:
# while loop
'''
n = int(input('Enter the number: '))
i=2
while i <= 50:
print(i)
i = i + 2'''
Day-19
# WAP to find the factorial of a given integer / to find the prod of n natural numbers.
# Example: 5! --- 5*4*3*2*1
# Example: product upto 5 --- 1*2*3*4*5
'''
n=5
prod = 1
while n>0:
prod = prod * n
n=n-1
print(prod)'''
'''
i=1
prod = 1
while i<=5:
prod = prod * i
i=i+1
print(prod)'''
ord('A')
65
ord('a')
97
chr(65)
'A'
chr(ord('A')+32)
'a'
chr(ord('B')+32)
'b'
chr(ord('C')+32)
'c'
chr(ord('a')-32)
'A'
chr(ord('b')-32)
'B'
Day-20
For loop:
--- It is self-iterative loop.
Advantage:
• It will allow us to use all the MVDT but in while loop it considers only string, list and tuple.
• No need of initialization and updation.
Range():
--- It is used to create a sequence of integers between the given value.
Syntax:
range(SV, EV+1,updation)
range(SV, EV-1,updation)
○ If updation == +1
range(SV, EV+-1)
○ If SV==0
range(EV+-1, updation)
range(1,10+1)
range(1, 11)
list(range(1,11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
tuple(range(1,11))
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
list(range(10,1-1,-1))
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
list(range(0,10+1,1))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list(range(10,0-1,-1))
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
list(range(10,-1,-1))
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Programs:
# For loop
# Practice programs
'''
for i in [10,2.3,6+7j,78]:
print(i)'''
'''
for i in (12,34):
print(i)'''
'''
for i in {17,3.4,78,32}:
print(i)'''
'''
for i in {'a':10,'b':20,'c':30}:
print(i)'''
'''
for i in 'sakshi':
print(i,end=' ')'''
'''
for i in range(1,6):
print(i) '''
# WAP to find the length of the collection without using len function.
'''
c = eval(input('Enter the collection: '))
count = 0
for i in c:
count+=1
print(count)'''
# WAP to check whether the string is palindrome or not without using slicing.
'''
s = input('Enter the string: ')
rev = ''
for i in s:
rev = i + rev
if rev == s:
print('palindrome')
else:
print('not palindrome')'''
Day-21
'''
t = eval(input('Enter the tuple: '))
out = {}
for i in t:
if type(i) == str:
out[i] = len(i)
print(out)'''
'''
l = eval(input('Enter the list: '))
out = {}
for i in l:
if type(i) == str:
out[i] = i[0]+i[-1]
print(out)'''
'''
s = input('Enter the string: ')
out = {}
for i in s:
if 'a'<=i<='z':
out[i] = chr(ord(i)-32)
elif 'A'<=i<='Z':
out[i] = chr(ord(i)+32)
Note:
○ Split() --- it is used to split each word present in the string
○ Join() --- it is used to join/merge the strings present inside the collection.
'''
s = input('Enter the string: ')
out = []
a = s.split()
for i in a:
out.append(i[::-1])
print(' '.join(out)) '''
'''
s = input('Enter the string: ')
out = []
a = s.split()
for i in a:
out.append(i[0]+i[-1])
print(' '.join(out)) '''
Day - 22:
Syntax:
Example:
for i in range(1,5):
for j in range(1,3):
print(i,j)
Strong Number: If the number is equal to the sum of the factorial of individual digits, then we
can call that number as Strong Number.
'''
l = eval(input('Enter the list: '))
out = {}
for i in l:
if type(i) == str:
vow = ''
for j in i:
if j in 'AEIOUaeiou':
vow += j
out[i] = vow
print(out) '''
#Assignment
# Get the following output.
'''
Input : [12, 'program',4+2j, False,'holiday']
Output : {'program' : 'prgrm', 'holiday' : 'hldy'} '''
#Assignment
# Get the following output.
'''
Input : [12, 'program',4+2j, False,'holiday']
Output : {'program' : 'PROGRAM', 'holiday' : 'HOLIDAY'} '''
Patterns:
--- Using Nested for loop to print some unique structure or pattern.
Programs:
for i in range(1,4):
print('*',end = ' ') '''
'''
***
***
***
for i in range(1,4):
for j in range(1,4):
print('*',end = ' ')
print() '''
'''
***
***
***
***
***
for i in range(1,6):
for j in range(1,4):
print('*',end = ' ')
print()'''
'''
*****
*****
for i in range(1,3):
for j in range(1,6):
print('*',end = ' ')
print() '''
'''
*
*
*
*
*
'''
'''
@
*@
**@
***@
****@
'''
'''
####$
###$&
##$&&
#$&&&
$&&&&
'''
'''
*****
* *
* *
* *
*****
'''
n = int(input('Enter the num: '))
for i in range(1,n+1):
for j in range(1,n+1):
if i == 1 or j == 1 or i == n or j ==n:
print('*',end = ' ')
else:
print(' ',end = ' ')
print()
'''
10000
01000
00100
00010
00001
'''
n = int(input('Enter the num: '))
for i in range(1,n+1):
for j in range(1,n+1):
if i ==j:
print('1',end = ' ')
else:
print('0',end = ' ')
print()
'''
* *
* *
*
* *
* *
'''
n = int(input('Enter the num: '))
for i in range(1,n+1):
for j in range(1,n+1):
if i == j or i+j == n+1:
print('*',end = ' ')
else:
print(' ',end = ' ')
print()
'''
*****
* *
* *
* *
*****
'''
n = int(input('Enter the num: '))
for i in range(1,n+1):
for j in range(1,n+1):
if i == 1 or j==1 or i==n or j==n:
print('*',end = ' ')
else:
print(' ',end = ' ')
print()
'''
*********
** * **
* * * * *
* *** *
*********
* *** *
* * * * *
** * **
*********
'''
n = int(input('Enter the num: '))
for i in range(1,n+1):
for j in range(1,n+1):
if i==1 or j==1 or i==n or j==n or i==j or i+j==n+1 or i==n//2+1 or j==n//2+1:
print('*',end = ' ')
else:
print(' ',end = ' ')
print()
Day-23
'''
12345
12345
12345
12345
12345
for j in range(1,n+1):
print(j,end = ' ')
print() '''
'''
11111
22222
33333
44444
55555
'''
1
12
123
1234
12345
'''
'''
23
23 24
23 24 25
23 24 25 26
23 24 25 26 27
'''
'''
5
54
543
5432
54321
'''
'''
5
54
543
5432
54321
'''
'''
* *
** **
* * *
* *
* *
'''
'''
* *
* *
* * *
** **
* *
'''
'''
**** * *
* * * *
* ** * * *
**** ** **
* * *
'''
for j in range(1,n+1):
if j == 1 or j == n or (i == j and i >= n//2+1 ) or (i+j==n+1 and i >= n//2+1):
print('*',end = ' ')
'''
****
*
***
*
****
'''
Assignment:
--- Print the first 4 letters in your name using patterns.
Day-24
Types:
• Break
• Continue
• Pass
1) Break:It is used to perform intermediate terminations in looping. This can be used only for
looping statement.
Task: Whenever the controller sees the keyword break it will immediately terminate the
loop.
Example:
'''
num = int(input('Enter the number: '))
for i in range(1,6):
print(i)
if i == num:
break '''
# Actual programs
# WAP to demonstrate guess the number game.
'''
sup = 784
while True:
n = int(input('Enter the number: '))
if n == sup:
print('Congrats you have guessed it')
break
elif n > sup:
print('Your guessed number is greater')
elif n < sup:
print('Your guessed number is lesser') '''
# WAP to check whether the given string is having only lowercase characters or not.
'''
s = input('Enter the string: ')
for i in s:
if not('a'<=i<='z'):
2) Continue : Whenever we want to stop the particular step/Iteration we use continue keyword.
# Example
'''
num = 3
for i in range(1,6):
if i == num:
continue
print(i) '''
# Actual programs
# WAP to extract all the integers from the list.
'''
l = eval(input('Enter the list: '))
out = []
for i in l:
if type(i) != int:
continue
else:
out.append(i)
print(out) '''
Functions:
--- It is a name given to a memory block, where the set of intructions are stored and performing
some particular task.
By creating a function for one time, we can use it for n number of times.
Types:
• Inbuilt Functions
• User defined functions.
Inbuilt Functions:
--- They are predefined functions.
• Utility function: It is used for every datatype / common for more than one datatype.
Example: id(), type(), bool()
Practical proof:
s = 'Coders'
s.upper()
'CODERS'
s = 'PytHoN'
s.lower()
'python'
s = 'GoOd EvEnInG'
s.swapcase()
'gOoD eVeNiNg'
s = 'PytHoN'
s.capitalize()
'Python'
s = 'Python is easy to learn and analyze'
s.title()
'Python Is Easy To Learn And Analyze'
s.capitalize()
'Python is easy to learn and analyze'
s = 'Python is easy'
s.split()
['Python', 'is', 'easy']
s = 'Coders'
'@'.join(s)
'C@o@d@e@r@s'
print('c','o','d','e','r','s', sep = '@')
c@o@d@e@r@s
s = 'Coders'
s.replace('o','a')
'Caders'
s.replace('Python','Java')
'Coders'
s = 'Python'
s.replace('Python','Java')
'Java'
s = 'Python'
s.index('t')
2
s = 'appa'
s.count('a')
2
ord('A')
65
chr(65)
'A'
s = 'appa'
'a'.join(s)
'aapapaa'
'a'.join(' appa')
' aaapapaa'
l = [30,20,10,50,40]
l.sort()
l
[10, 20, 30, 40, 50]
l.sort(reverse = True)
l
[50, 40, 30, 20, 10]
l = [30,20,'10',[50,20],40]
l.sort()
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
l.sort()
TypeError: '<' not supported between instances of 'str' and 'int'
l = [10,2.3,2+3j,True,'hi']
l.reverse()
l
['hi', True, (2+3j), 2.3, 10]
l = [10,2.3,2+3j,10,True,'hi',10]
l.count(10)
3
l.index(2+3j)
2
• Inbuilt functions on Tuple:
t = (10,20,30,40)
t.count(30)
1
t.index(20)
1
s1 = {12,3.4,2+4j,7,True}
s2 = {22,3.4,3+4j,9,False}
s1.union(s2)
{False, True, 3.4, 7, 9, 12, (2+4j), (3+4j), 22}
s1.intersection(s2)
{3.4}
s1
{True, 3.4, 7, 12, (2+4j)}
s1.difference(s2)
{True, 12, (2+4j), 7}
s1.clear()
s1
set()
a = {'a':10,'b':20,'c':30,'d':40,'m':'monkey'}
a.keys()
dict_keys(['a', 'b', 'c', 'd', 'm'])
a.values()
dict_values([10, 20, 30, 40, 'monkey'])
a.items()
dict_items([('a', 10), ('b', 20), ('c', 30), ('d', 40), ('m', 'monkey')])
a.pop('m')
'monkey'
a
{'a': 10, 'b': 20, 'c': 30, 'd': 40}
a.get('d')
New Section 1 Page 17
a.get('d')
40
a.get('c','b')
30
a
{'a': 10, 'b': 20, 'c': 30, 'd': 40}
a = {'a': 10, 'b': 20, 'c': 30, 'd': 40}
a.popitem()
('d', 40)
a = {'a': 10, 'b': 20, 'c': 30, 'd': 40}
a = {'a': 10, 'b': 20, 'c': 30, 'd': 40}
b = {'e': 10, 'f': 20}
a.update(b)
a
{'a': 10, 'b': 20, 'c': 30, 'd': 40, 'e': 10, 'f': 20}
b = {'e': 10, 'f': 20}
b.update({'a':10})
b
{'e': 10, 'f': 20, 'a': 10}
b = {'e': 10, 'f': 20}
b.clear()
b
{}
Syntax:
Note:
• Passing the arguments and the return value are not mandatory.
• Arguments --- It consists of required values to perform the operations
• def --- It is a keyword used to define / create a function.
• To execute the function, we have to call the function.
• return keyword is used to stop the execution.
Types:
Syntax:
# Example:
'''
def add():
a = int(input('Enter the number: '))
Memory allocation:
# Example:
'''
def add():
a = int(input('Enter the number: '))
b = int(input('Enter the number: '))
print(a+b)
add() '''
# Program
# WAP to convert the string to uppercase.
'''
def convert_up():
s = input('Enter the string: ')
out = ''
for i in s:
if 'a'<=i<='z':
out += chr(ord(i)-32)
else:
out += i
print(out)
convert_up() '''
Syntax:
Programs:
# Function with arguments and without return value
# Example:
# Program
# WAP to convert the string to uppercase.
'''
def convert_up(s,out):
for i in s:
if 'a'<=i<='z':
out += chr(ord(i)-32)
else:
out += i
print(out)
convert_up(input('Enter the string: '),'') '''
Syntax:
Program
# Example:
'''
def add():
a = int(input('Enter the number: '))
b = int(input('Enter the number: '))
return a+b
print(add()) '''
# Program
# WAP to convert the string to uppercase.
'''
def convert_up():
s = input('Enter the string: ')
out = ''
for i in s:
if 'a'<=i<='z':
out += chr(ord(i)-32)
else:
out += i
return out
print(convert_up()) '''
Syntax:
Programs:
# Example:
'''
def add(a,b):
return a+b
print(add(10,20)) '''
# Program
# WAP to convert the string to uppercase.
'''
def convert_up(s,out):
for i in s:
if 'a'<=i<='z':
out += chr(ord(i)-32)
else:
out += i
return out
print(convert_up(input('Enter the string: '),''))'''
Global Variable:
--- These variables are created in main space and this can be accessed and modified in the main
space but cannot be modified in method area.
a = 10
b = 20
def sam():
print(a+b)
print(a,b)
print(a,b)
sam()
b = 50
print(a,b)
a = 10
b = 20
def sam():
global a
print(a+b)
a = 30
print(a,b)
print(a,b)
sam()
b = 50
print(a,b)
Local Variable:
--- These variables are created in method area and this can be accessed and modified in the same
function but cannot be modified in the nested function.
a = 10
b = 20
def outer():
p = 100
q = 200
print(p+q)
def inner():
print(p,q)
inner()
p = 333
print(p,q)
a = 50
print(a,b)
outer()
• Packing:
--- It is a phenomenon of grouping the individual values in the form of collections to provide
security.
Note: We can do packing in all the collection, but our system will prefer to do packing in only
tuple datatype.
Reason: Tuple is the most secured datatype.
Types of Packing:
• Tuple/Single packing
• Dictionary/Double packing
Syntax:
# Tuple packing
'''
def pack(*t):
print(type(t))
print(t)
pack(10,20,30,40,50) '''
Syntax:
Note:
▪ Memory efficiency
▪ Increases performance
▪ Lighter and faster
• Unpacking:
--- The phenomenon of dividing the collection and storing each and every value present in
the collection to a unique variable.
Syntax:
# Unpacking
'''
def unpack(v1,v2,v3,v4):
print(v1,v2,v3,v4)
unpack(*'abcd') '''
'''
def unpack(v1,v2,v3,v4):
print(v1,v2,v3,v4)
unpack(*[10,20,30,40]) '''
'''
def unpack(v1,v2,v3,v4):
print(v1,v2,v3,v4)
unpack(*(10,20,30,40)) '''
'''
def unpack(v1,v2,v3,v4):
print(v1,v2,v3,v4)
unpack(*{10,20,30,40}) '''
'''
def unpack(v1,v2,v3,v4):
print(v1,v2,v3,v4)
unpack(*{'a':10,'b':20,'c':30,'d':40})
unpack(*{'a':10,'b':20,'c':30,'d':40}.values())
unpack(*{'a':10,'b':20,'c':30,'d':40}.items()) '''
'''
def unpack(v1,v2,v3,v4):
print(v1,v2,v3,v4)
unpack(*range(1,5)) '''
Types of arguments:
▪ Positional argument
▪ Default argument
▪ Keyword argument
▪ Variable length argument
1) Positional argument :
--- The arguments which are created in function declaration are called as Positional
argument.
Note:
• It is compulsory to pass the value
• Follow the same order.
def add(a,b):
print(a+b)
add(10,20)
2) Default argument :
--- They are present in function declaration, if the user is passing the default value then by
default it will take the value. If I pass the value then default value of the variable will be
replaced with new value.
# Default argument
'''
def add(a=0,b=0):
print(a+b)
add(10,20) '''
3) Keyword argument :
--- Passing the key-value pair as the value to the arguments. They are present in function call.
# Keyword argument
'''
def pack(**d):
print(type(d))
print(d)
pack(a=10,b='20',c=30,d=40) '''
Day-29
Recursion:
--- The phenomenon of calling the function by itself until the termination condition becomes
True.
Syntax:
Note: return keyword is used to stop the execution of the function. If it is having any result
in front of it it will display that or else it will just simply terminate the function.
Programs:
def fact(n):
if n==1 or n==0:
return 1
return n*fact(n-1)
print(fact(3))
Memory allocation:
# WAP to print
# 32123
'''
def sam(n):
print(n,end = ' ')
if n == 1:
return
sam(n-1)
print(n,end = ' ')
sam(3) '''
Memory allocation:
• Initialisation of all the required variables of looping should be done in function declaration.
• The termination condition should be written exactly opposite to the looping condition in the
form of if statement.
• Return the total result inside the termination condition.
• Logic of the program should be written as it is.
• Updation of looping variable should be done in recursive call.
'''
l = eval(input('Enter the list: '))
out = []
i=0
while i<len(l):
if type(l[i]) == str:
out.append(l[i][::-1] + l[i])
i+=1
print(out) '''
'''
def sam(l,out=[],i=0):
if i >= len(l):
return out
if type(l[i]) == str:
out.append(l[i][::-1] + l[i])
return sam(l,out,i+1)
print(sam(eval(input('Enter the list : ')))) '''
Assignment:
--- Take any 5 while loop program and convert them to recursion program
Day-30
Introduction to OOPS:
--- The concept which deals with class and objects are called OOPS.
Class: It is a container which is used to store the properties and functionalities of real-time
entity.
• Class creation:
• Object creation:
Syntax:
Types of Class:
• Inbuilt class --- All the datatypes are inbuilt class because they are predefined.
• User-defined class.
class Creation:
a = 10
b = 20
demo = Creation()
print(type(demo))
Output:
<class '__main__.Creation'>
Note: __main__ is representing that class is created by user / User Defined class.
Memory allocation:
class Creation:
a = 10
b = 20
Demo1 = Creation()
Bank.loc = 'Mumbai'
print(Bank.bname,Bank.loc,Bank.manager)
print(cus1.bname,cus1.loc,cus1.manager)
print(cus2.bname,cus2.loc,cus2.manager)
print('*'*50)
cus1.loc = 'Gujurat'
print(Bank.bname,Bank.loc,Bank.manager)
print(cus1.bname,cus1.loc,cus1.manager)
print(cus2.bname,cus2.loc,cus2.manager)
print('*'*50)
cus2.loc = 'Hyderabad'
print(Bank.bname,Bank.loc,Bank.manager)
print(cus1.bname,cus1.loc,cus1.manager)
print(cus2.bname,cus2.loc,cus2.manager) '''
• Modification done with respect to class will affect all the objects and also the class.
Reason: Objects are instance / copy of the class .
• Modification done with respect to one object will not affect the class and other objects.
Reason: Class are not depending on objects.
Day-31
States:
--- The properties or functionalities storing inside the class are called as States.
Types:
1) Generic State:
--- The properties or functionalities which will be common for each and every object we
create
is called as Generic State.
Example:
# Generic State.
'''
class School:
sname = 'JES'
loc = 'Hampi'
principal = 'Nandakumar'
timing = '9am - 4:30pm'
st1 = School()
print(School.sname,School.loc,School.principal,School.timing)
print(st1.sname,st1.loc,st1.principal,st1.timing)
'''
2) Specific State:
--- The properties or functionalities which will we create outside the class after the object
creation is called as Generic State.
Example:
Syntax :
Program:
# Constructor method
'''
class School:
sname = 'JES'
loc = 'Hampi'
principal = 'Nandakumar'
timing = '9am - 4:30pm'
def __init__(self,name,sid,age,bg):
self.name = name
self.sid = sid
Methods:
--- The function which we declare inside the class.
Types:
• Object method
• Class method
• Static method
1) Object method :
--- They are used to access and modify the object members
Syntax:
Programs
# Object method
'''
class School:
sname = 'JES'
loc = 'Hampi'
principal = 'Nandakumar'
timing = '9am - 4:30pm'
def __init__(self,name,sid,age,bg):
self.name = name
self.sid = sid
self.age = age
self.bg = bg
def display(self):
print(self.name,self.sid,self.age,self.bg)
def ch_age(self,new):
self.age = new
st1 = School('A',21,23,'B+ve')
st1.display()
st1.ch_age(25)
st1.display() '''
2) Class method :
--- They are used to access and modify the class members. We need to use 'cls' as an
argument to store the address of the class members and it is compulsory to use @classmethod
Syntax:
Program
class School:
sname = 'JES'
loc = 'Hampi'
principal = 'Nandakumar'
timing = '9am - 4:30pm'
@classmethod
def display(cls):
print(cls.sname,cls.loc,cls.principal,cls.timing)
@classmethod
def ch_time(cls,new,change):
cls.timing = new
cls.loc = change
st1 = School()
School.display()
School.ch_time('9am - 5pm','mausmi')
School.display()
3) Static method :
--- It is neither belongs to class members nor object members but it will acts as supportive
method for both class and objects.
Syntax:
class Boring:
name = 'Sakshi'
role = 'Irritator'
@staticmethod
def nonsense(a,b):
print(a+b)
st1 = Boring()
Boring.nonsense(10,20)
st1.nonsense(10,20)
OOPS concepts:
Inheritance:
--- The phenomenon of deriving the properties from one class to another class.
Types of Inheritance:
• Single level
• Multi-level
• Multiple
• Hierarchical
• Hybrid
Syntax:
Program :
#Single level
'''
class School:
sname = 'JES'
class College(School):
clgname = 'Sai Vidya'
HOD = 'Ranganath'
@classmethod
def display(cls):
print(cls.clgname,cls.HOD,cls.sname,cls.loc,cls.principal)
College.display()
'''
'''
class Bank:
bname = 'SBI'
loc = 'Koppa'
def __init__(self,name,phno,bal):
self.name = name
self.phno = phno
self.bal = bal
cus1 = Bank('A',947349534,500)
class Updated_Bank(Bank):
Founder = 'Sairam'
def __init__(self,addr,pan,name,phno,bal):
self.addr = addr
self.pan = pan
self.name = name
self.phno = phno
self.bal = bal
def display(self):
print(self.addr,self.pan,self.name,self.phno,self.bal)
cus2 = Updated_Bank('Gokarna',97374,'A',947349534,500)
cus2.display()
'''
The process of calling parent __init__ method inside the child __init__ method is called
Constructor chaining.
Syntax:
The process of calling the parent method inside the child method is called Method chaining.
Syntax:
Program :
class Bank:
bname = 'SBI'
loc = 'Koppa'
def __init__(self,name,phno,bal):
self.name = name
self.phno = phno
self.bal = bal
def disp(self):
print(self.name,self.phno,self.bal)
cus1 = Bank('A',947349534,500)
class Updated_Bank(Bank):
Founder = 'Sairam'
def __init__(self,name,phno,bal,addr,pan):
super().__init__(name,phno,bal)
self.addr = addr
self.pan = pan
def display(self):
super().disp()
print(self.addr,self.pan)
cus2 = Updated_Bank('Gokarna',97374,'A',947349534,500)
cus2.display()
2) Multi-level Inheritance:
--- Inheriting the properties from parent class to child class occurs in multiple level.
Syntax:
Proof:
# Multi-level Inheritance.
'''
class School:
sname = 'JES'
loc = 'Hampi'
princi = 'Nanda'
class College(School):
clgname = 'Sai'
HOD = 'Ranga'
class Masters(College):
uname = 'VTU'
founder = 'Bala'
@classmethod
def display(cls):
print(cls.uname,cls.founder,cls.clgname,cls.HOD,cls.sname,cls.loc,cls.princi)
Masters.display() '''
3) Multiple Inheritance:
Syntax:
Programs:
# Multiple Inheritance.
'''
class School:
sname = 'JES'
loc = 'Hampi'
princi = 'Nanda'
class College:
clgname = 'Sai'
HOD = 'Ranga'
class Masters(College,School):
uname = 'VTU'
founder = 'Bala'
@classmethod
def display(cls):
print(cls.uname,cls.founder,cls.clgname,cls.HOD,cls.sname,cls.loc,cls.princi)
Masters.display()
'''
4) Hierarchical Inheritance:
--- Inheriting properties from single parent to a multiple child.
Syntax:
class College(School):
clgname = 'Sai'
HOD = 'Ranga'
@classmethod
def disp(cls):
print(cls.clgname,cls.HOD,cls.sname,cls.loc,cls.princi)
class Masters(School):
uname = 'VTU'
founder = 'Bala'
@classmethod
def display(cls):
print(cls.uname,cls.founder,cls.sname,cls.loc,cls.princi)
College.disp
Masters.display()
'''
5) Hybrid Inheritance:
--- Combination of more than one type of inheritance.
Programs:
# Hybrid Inheritance.
class School:
sname = 'JES'
loc = 'Hampi'
princi = 'Nanda'
class College(School):
clgname = 'Sai'
HOD = 'Ranga'
@classmethod
def disp(cls):
print(cls.clgname,cls.HOD,cls.sname,cls.loc,cls.princi)
class Degree:
dname = 'BTech'
sub_code = '17DAA45'
class Masters(School,Degree):
uname = 'VTU'
founder = 'Bala'
@classmethod
def display(cls):
print(cls.uname,cls.founder,cls.sname,cls.loc,cls.princi,cls.dname,cls.sub_code)
College.disp()
Masters.display()
Day-33
Polymorphism:
--- It is a phenomenon of making the operator or method to perform two or more functionalities.
• Method Overloading
• Operator Overloading
1) Method overloading.
--- It is a phenomenon of making the method to perform two or more functionalities.
Example:
# Method Overloading.
'''
class Demo:
@staticmethod
def sam():
print('Good evening')
@staticmethod
def sam(a,b):
print(a+b)
@staticmethod
def sam(a,b,c):
print(a*b*c)
user = Demo()
user.sam(1,2,3)
user.sam(10,20) '''
Monkey Patching: The process of storing the address of the method in a variable so that the
variable can be used as a method. To execute that method we have to call that variable.
#Monkey Patching
'''
class Demo:
@staticmethod
def sam():
print('Good evening')
x = sam
@staticmethod
def sam(a,b):
print(a+b)
y = sam
@staticmethod
def sam(a,b,c):
print(a*b*c)
z = sam
user = Demo()
user.x()
user.y(10,20)
user.z(1,2,3) '''
2) Operator overloading.
--- It is a phenomenon of making the operator to perform two or more functionalities by
invoking the magic method.
Encapsulation:
--- The phenomenon of providing security to the data members or variables or methods stored
inside the class by restricting the user to access.
Access Specifiers : Members of the class which will inform the user whether they can access
them outside the class or not.
Types:
• Public
• Protected
• Private
1) Public: Members of the class that can be accessed and modified outside the class.
Syntax:
#Encapsulation
'''
# Public
class Demo:
a = 10
b = 20
def __init__(self,c ,d):
self.c = c
self.d = d
def display(self):
print(self.c,self.d)
def ch_c(self,new):
self.c = new
@classmethod
# Operator overloading.
'''
class A:
a = 10
b = 20
def __init__(self, c,d):
self.c = c
self.d = d
def display(self):
print(self.c + self.d)
ob1 = A(30,15)
ob2 = A('hi','hello')
ob1.display()
ob2.display() '''
Day-34
Syntax:
Program:
# Protected
class Demo:
_a = 10
_b = 20
def __init__(self,c ,d):
self._c = c
self._d = d
def _display(self):
print(self._c,self._d)
def _ch_c(self,new):
self._c = new