0% found this document useful (0 votes)
8 views141 pages

Python Notes

Python is a high-level, dynamic, and open-source programming language introduced in 1991 by Guido Van Rossum. It supports both procedural and object-oriented programming, and features extensive libraries, platform independence, and easy syntax. The document covers Python's features, variables, identifiers, keywords, data types, and collections such as lists, tuples, sets, and dictionaries.

Uploaded by

lomota9265
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
8 views141 pages

Python Notes

Python is a high-level, dynamic, and open-source programming language introduced in 1991 by Guido Van Rossum. It supports both procedural and object-oriented programming, and features extensive libraries, platform independence, and easy syntax. The document covers Python's features, variables, identifiers, keywords, data types, and collections such as lists, tuples, sets, and dictionaries.

Uploaded by

lomota9265
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 141

PYTHON

INTRODUCTION 18/06/2024

Python is a high-level programming language. It is used to communicate with the


computers or with local machine to perform specific task.
Python was introduced in the year 1991 by GUIDO VAN ROSSUM.
FEATURES OF PYTHON
1. It is a high-level programming language.
2. It is simple to code and easy to learn.
3. It is a dynamic programming language.
4. It is an interpreter programming language.
5. It supports both procedural and oops concepts.
6. It is an open source.
7. It has extensive set of libraries.
8. It is a platform independent.
9. It is a portable programming language.
Note: Guido Van Rossum names this programming language as python because he was a
follower of a famous show called ‘Monty Python Flying Circus.’ There he picked the name
Python.
High-level language
High-level programming language enables the development of a python in a much more
user-friendly content.
Dynamic
The language does not require any predefined datatype for any variable as it is
interpreted by machine itself during the runtime.
Interpreter programming language
The process of converting the code line by line is called interpreter programming
language.
Open source
Here the source code is visible to the normal users and making it a freely …….. and
distributable.
Platform independent
It means the software that runs on different OS i.e., write once and run anywhere.
(WORA principle)
VARIABLES
Variable is a named memory location where the value is stored.
We name the memory location so that accessing the value present inside the memory shall be
easier.
Syntax: variable name = value E.g.: a = 10
Python, as it is a dynamically typed programming language, we will not specify the type of
data while assigning to a variable so that the variable can store any kind of data like int, float,
list etc.
Note: we can reinitialize the variable name n number of times.
IDENTIFIERS
Identifiers are the name that are given to identify the memory location.
There are certain rules to name the identifiers.
1. It should start with alphabets or underscore.
E.g.: a = 10, _ = 10, b1 = 10
2. It should not start with numbers but it can contain numbers.
E.g.: 1 = 10 → error
3. It should not start with special characters except underscore ( _ ).
E.g.: $ = 20 → error
4. Keywords should not be used as identifiers.
E.g.: if = 20 for = 20 → error

KEYWORDS 19/06/2024

Keywords are the predefined reserved words present in the python. In python there are
35 keywords in that the first 3 keywords are called as special keywords. The special
keywords are True, False, None. As we can use these 3 keywords to assign a value, we can
call it as special keywords.
In python there are 3 soft keywords like underscore ( _ ), case and match. These are called
soft keywords because they can be used as variable names also.
import keyword
kws=keyword.kwlist
print(kws)

['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']
[‘_’, ‘case’, ‘match’, ‘type’]
Note: a=10 a→stack memory 10→heap memory
Python’s memory is divided into 2 regions i.e., stack and heap. The stack is responsible for
storing the variables and function calls, whereas heap is responsible for sharing the objects.
Note: a=’python’ whenever we reinitialize a value for the variable python’s old value will be
deallocated, because python’s garbage collector runs during the program execution and when
the objects reference count reaches ‘0’ the memory for that value will be deallocated.

DATATYPE
Used to specify the type of data to be stored in a specified variables in python. We have 2
different types of datatypes.
1. Single value datatype
a. Numeric datatype → int, float, complex
b. Non numeric datatype → bool.
2. Multi value datatype
a. String, list, tuple, set, dictionary.

SINGLE VALUE DATATYPE


In this datatype we have numeric and non-numeric. Numeric datatype includes int, float, and
complex and non-numeric datatype includes bool.
All the single value datatypes are immutable in nature.
Immutable: Immutable datatype is nothing but once the object is created user can’t modify by
adding or updating or by removing the values from an existing data.

INT
This datatype stores the numeric value which doesn’t contain any decimal point.
E.g.: a=10
Print(a)
Print(type(a)) type( ): this function returns the type of the object
Print(id(a)) id( ): returns the identity or address of the object

FLOAT
This datatype which is used to store numeric values which contain decimal point.
E.g.: b=10.0
Print(type(b))
Print(id(b))

COMPLEX
In this datatype we have real and imaginary part and the imaginary is denoted by
character j. The character datatype is in type(a+bj).
E.g.: c=10+2j
Print(type(c))
Print(id(c))

BOOLEAN
This datatype consists of true and false.
E.g.: bo=false
Print(bo)
Note:
1. All the python files should be saved with .py extension.
2. If you want to comment lines, we can use the symbol #.
3. Whenever we comment the line in a code, python interpreter will not read the
commented line.
20/06/2024

INDEXING
Indexing is used to identify each and every block of the memory. In indexing we have
positive indexing and negative indexing.
POSITIVE INDEX:
Always starts from left hand side to right hand side. The length of the positive index is
from 0 to n-1. Where n is the length of the given sequence.
P Y T H O N
0 1 2 3 4 5→
E.g.: b=’PYTHON’
Print(b[1]) → y
Print(b[4]) → o
Print(b[1] [2]) → error → string out of range
NEGATIVE INDEX:
Negative index starts from right hand side to left hand side. The length of the negative
index is from -1 to -n. Where n is the length of the given sequence.
P Y T H O N
-6 -5 -4 -3 -2 -1 
E.g.: b=’PYTHON’
Print(b[-1]) → n
Print(b[-4]) → t
Print(b[-3]) → h
Note: Using indexing we can extract only a single character at a time.
MULTI VALUE DATATYPE
As the name suggest multi-value datatype it deals with collection of values or data
items. The different types of MVDT are string, list, set, tuple, dictionary.

STRING
Collection of homogenous and heterogenous type of elements. String can be enclosed
with ‘’ or “” or ‘” “’.
‘” “’ are called as docstring. It is used to comment multiple lines at a time.
It is immutable in nature. Supports indexing and slicing. Allows duplicated.
If we start a string with a single quote then it should end with single quote only.
The default value of string is a=’’
We can represent the string by the name str.
Varname = ‘’ or varname = “” or varname = ‘” “’
E.g.: s=’pyspiders’
Print(type(s))
Print(id(s))
The built-in functions for a string are
1. Upper(): this function converts the lower case characters to uppercase.
S= ‘pyspiders’ Print(s.upper()) → PYSPIDERS
2. Lower(): converts upper case to lower case character.
T=’HELLO’ print(t.lower()) → hello
3. Title(): this function converts only the first character in the each word into upper case.
S= ‘welcome to pyspiders’ print(s.title()) → Welcome To Pyspiders
4. Capitalize(): converts only the first character into upper case in a given string.
S= ‘welcome to pyspiders’ print(s.capitalize()) → Welcome to pyspiders
5. Casefold(): convert the string into lower case.
f=’HELLO’ print(f.casefold()) → hello
6. Startswith(): this function gives output in the form of Boolean. It will return true if the
string starts with a given character or else false.
S=’Pyspiders’
Print(s.startswith(‘P’)) → true
Print(s.startswith(‘j’)) → false
Print(s.startswith(‘p’)) → false
7. Endswith(): true if given string ends with specified character or else it will return false.
Print(s.endswith(‘n’)) → true
Print(s.endswith(‘N’)) → false
Print(s.endswith(‘r’)) → false
8. Join(): this function is used to join elements in a given sequence.
Str=’python’ x=’*’.join(str) or x=’’.join(str)
Print (x) → p*y*t*h*o*n
9. Split(): splits the given string with the specified separators and returns the output in the
form of list.
A= ‘pyspiders from hebbal’ a=str.split()
Print(a) → [‘pyspiders’, ‘from’, ‘hebbal’]
10. Replace(): this functions replaces old character with a specified new character for this
function we need to pas 2 arguments.
Syntax: replace (‘oldvalue’, ‘newvalue’)
E.g.: str=’python’ print(str.replace(‘p’, ‘j’))
11. Find(): this function returns index position of the first occurrence character.
E.g.: print(str.find(‘s’)) → 2
12. Count(): this function returns the occurrence of the given character.
E.g.: print(str.count(‘p’)) → 1 print(str.count(‘a’)) → 0

List String
Collection of heterogenous and homogenous Collection of characters
elements
Mutable in nature Immutable in nature
Can be represented by [ ] Represented by ‘ ‘, “ “
Default value for list is var = [ ] Default value for string is ‘’
Separated by comma Not separated by comma

Dict set
Collection of elements are stored in key- Unordered sequence of elements
value pairs
Mutable in nature, keys are immutable Mutable in nature but elements are
immutable
Duplicates are not allowed for keys Duplicates are not allowed
We can modify list by inserting, updating and We can’t modify the set
deleting
Default value for list is dict[key:value] Default value for list is s= set()
Separated by comma Not separated by comma

String Tuple
Collection of characters Collection of heterogenous and homogenous
elements
Represented by ‘’, “ “ Represented by ( )
No comma Separated by comma
Default value ‘’ Default value for list is var = ( )
21/06/2024

LISTS
List is a collection of homogenous and heterogenous type of elements. The elements
present inside the list are separated by commas (,). It is mutable in nature. It supports indexing,
allows duplicates. List is represented by a pair of square braces [ ].
E.g.: var = [v1, v2, v3, v4, v5]
The built-in functions for list are
• Insert ( ): using this function we can insert a new element for the specified position.
Syntax: var.insert(index position, index value)
E.g.: li=[1,4,2,5,7]
li.insert (2,9)
print(li)
• Append ( ): this function is used to add the element to the end of the list.
E.g.: li.append(3)
• Sort ( ): using this function we can arrange the elements in ascending order.
E.g.: li.sort()
If you want to arrange the elements in descending order we can make use of the
following syntax.
Syntax: var.sort(reverse=True)
E.g.: li.sort(reverse=True)
• Reverse ( ): using this function we can reverse the existing list.
E.g.: li.reverse()
• Pop ( ): this function remove the elements which is present in the last.
E.g.: li.pop()
We can remove particular index position also by passing the element as an argument to
the pop ( ).
E.g.: li.pop(4)
• Index ( ): using this function we can find the position of the given element.
E.g.: print(li.index(3))
• Count ( ): This function returns the number of times the given element present in the
list. E.g.: print(li.count(4))

TUPLE
Tuple is a collection of homogenous and heterogenous type of elements. It is
immutable in nature. We can represent tuple with parenthesis ( ). It supports indexing. It allows
duplicates. Tuple is faster than list. Default value for tuple is var = ( ).
E.g.: t = (1, 2, 4, ‘a’, ‘b’) a = ()
Print(type (a)) print(type(a))
Print (id(a))
D = ( 1, 2, 4, ‘a’, ‘b’)
Print(d.index(4)) print (d.index(1))
Difference between list and tuple
List Tuple
Mutable in nature Immutable in nature
Can be represented by [ ] Represented by ( )
We can modify list by inserting, updating and We can’t modify the tuple
deleting
Default value for list is var = [ ] Default value for list is var = ( )
List is slower than tuple Tuple is faster than list

22/06/2024

SET
Set is an unordered collection of the elements. We can represent set with { }. Set is mutable in
nature but the elements present inside the set is immutable in nature. Set doesn’t allow duplicate
values. Doesn’t support indexing. The default value for set is s = set ( )
e.g.: s = {2,5,’a’,1,3,’b’} {2,5,’a’,1,3,’b’, (1,2)} {2,5,’a’,1,3,’b’, [1,2]} error
s = {2,5,’a’} s.add(9) s.pop() s.pop(4) error s.remove(5)
List Set
Collection of homogenous and heterogenous Collection of unordered elements
type of elements
Can be represented by [ ] Represented by { }
Allow duplicates Doesn’t allow duplicates
Default value for list is var = [ ] Default value for set is s=set ( )
Support indexing Doesn’t support indexing

DICTIONARY
Dictionary is a collection of elements where elements are stored in the form of key value pair.
Key value pair is separated with a colon (:). Can be represented by { }. Mutable in nature but
the keys are immutable and values are mutable in nature. It doesn’t support indexing. In this
datatype keys do not allow duplicates but values allow duplicated. The default value is d = { }.
E.g.: di = {‘name’:’deepti’, ‘age’: 22, ‘place’: ‘bangalore’} di = { } print (type(d))
Dic = {‘bname’: ‘jsp’, ‘place’:’hebbal’, ‘place’: ’hrbr’} print (dic)
o/p →
dic={‘bname’: ‘jsp’, ‘place’:’hebbal’, place1:hrbr} →
dic={bname: jsp, place1:hebbal, addr:hebbal} →
dic = { ‘a’: 1, b: (1,2), c: [1,2]}
di={‘a’: 2, (1,2):2}
➢ Modifying the value
dic={‘bname’:’jsp’, ‘place’:’hebbal’,’addr’:’hebbal’}
dic[‘place’]=’banaswadi’
print(dic) → place will be replaced with banaswadi
➢ Inserting new key value pair
dic={‘bname’:’jsp’, ‘place’:’hebbal’,’addr’:’hebbal’}
dic[‘contactnum’]=13432 print(dic) →contact number is added to the dictionary.
➢ Retrieving the values and keys
dic={‘bname’:’jsp’, ‘place’:’hebbal’,’addr’:’hebbal’}
print(dic.get(‘place’))
print(dic.keys())
print(dic.values())
print(dic.items())
List Dictionary
Collection of homogenous and heterogenous Collection of elements where elements are
type of elements. stored in the form of key value pair.
Can be represented by [ ] Can be represented by {key : value}
Mutable in nature Mutable in nature but key is immutable and
values are mutable.
Support indexing Doesn’t support indexing
Allows duplicates Keys do not allow duplicates but values
allow duplicated.

24/06/2024

SLICING ****
In python slicing is used to extract a specific portion of a given sequence such as str, list and
tuple. In slicing we have 2 types 1) forward slicing 2) reverse slicing
Forward slicing
Syntax: [start index : end index : step]
Starting index: specifies the index of the first element that we want to include in a new
sequence. If the starting index is not mentioned then by default it will start from 0.
Ending index: It specifies the last element in the given sequence whenever we specify
the last element it will not include the last index value while displaying the output.
Step: an integer value which determines the increment between each index for slicing.
1) Forward slicing [lower value : higher value : +ve value]
In this type of slicing the starting index should be lesser than ending index and step
should be a positive integer.
E.g.: a=’pyspiders hebbal’
Print(a[0:5:1])→ (pyspi) print (a[3:8:])→ (pider)

Reverse slicing
Syntax: [higher value : lower value : -ve value]
In this type of slicing the starting index should be always greater than ending index and should
be negative value.
E.g.: print(a[4:1:-1]) →ips print (a[10:-1:-1])→ null
I. a=’python is great’
print(a[2:11:1]) → thon is g
print(a[:13:2]) → pto sge
print(a[::1]) → python is great
print(a[0::]) → python is great
print(a[12:1:-3]) →e h
print(a[1:0:2]) → null
print(a[10:1:-1]) → g si noht
print(a[::-1]) →

II. b=[cat, rat, dog, bat]


print(b[3:1:]) → null
print(b[1:4:1]) → rat, dog, bat
print(b[0::2]) → cat, dog
print(b[4:0:-1])→ bat, rat, dog
print(b[3:0:-2]) → bat, rat

III. c= (1, 2, 3, 4, ’a’)


print(c[1:4:2]) → 2, 4
print(c[4:1:-2]) → a, 3
print(c[2:4:]) → 3, 4
print(c[::-1]) → a, 4, 3, 2, 1

25/06/2024

TYPE CASTING
The phenomenon of converting one data type to another datatype is called as type
casting.
Syntax: var=data
Datatype(var)
• Integer: this datatype can be converted into float, complex, bool, and string.
E.g.: a=10
Print(float(a)) → 10.0
Print(complex(a)) → 10.0+0j
Print(bool(a)) → true
Print(str(a)) → 10
• Float: Float can be converted into int, complex, bool, str
E.g: a=10.0
Print(int(a)) → 10
Print(complex(a)) → 10.0+0j
Print(bool(a)) → true
Print(str(a)) → 10
• Complex: complex can be converted only into bool and str
E.g: a=10+1j
Print(bool(a)) → true
Print(str(a)) → 10+1j
• Bool: It can be converted into following data types
E.g: a=true
Print(float(a)) → 1.0
Print(complex(a)) → 1+0j
Print(int(a)) → 1
Print(str(a)) → true
• String: can be converted into list, tuple, set and bool
E.g.: a=’python’
Print(list(a)) → [‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’]
Print(set(a)) → (‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’)
Print(tuple(a)) → {‘t’, ‘y’, ‘p’, ‘h’, ‘o’, ‘n’}
Print(bool(a)) → true
• List: can be converted into str, tuple, set and bool
E.g: a=[1,2, ‘a’, ‘b’]
Print (str(a))
Print (tuple(a))
Print (set(a))
Print (bool(a))
• Tuple: str, list, bool, set
E.g.: a= {1,3,5,8}
Print (str(a)) →
Print (list(a))
Print (bool(a)) →true
Print (set(a))
• Set: str, tuple, list, bool
E.g.: a=(7, 2, 8, 5, 1)
Print (str(a))
Print (tuple(a))
Print (list(a))
Print (bool(a)) →true
• Dictionary:
E.g.: a={1:2, 3:4, 5:6}
Print (str(a)) → {1:2, 3:4, 5:6}
Print (tuple(a)) → (1,3,5)
Print (list(a)) → [1,3,5]
Print (set(a)) → {1,3,5}
Print (bool(a)) → true
Whenever we convert dict to list, tuple or set it will display only keys as an output.
If values should be displayed in the output then we can make use of the function values().
E.g.: print(list(a.values())) → [2, 4, 6]
Using item() we can display both key and values
E.g.: Print(tuple(a.items())) → ((1,2), (3,4), (5,6))
OPERATORS
Operators are used to perform operations between the operands. The different type of operators
in python are arithmetic, assignment, relational, logical, bitwise, membership identity.
1) Arithmetic operator includes the operators like +, -, *, /, //, %, **
I. ‘+’: Using this operator addition and concatenation
E.g.: a=10 b=12
Print(a+b) → 22
c=‘pyspiders’ d=’hebbal’
Print (c+d) → pyspidershebbal
Print([1,2]+[1,5])→ error
If you want to concatenate the operands then it should be of same data types.
A=[1:2, 2:3] B=[3:4, 5:6]
Print (A+B) → error
II. Subtraction: Using this operator we can subtract one operand with another operand.
E.g.: print(10-2) print(‘a’-‘b’)→ error
III. Multiplication using this operator we can repeat the operands for the given number
of times. E.g.: print(2*hello) print(12*4) print([1,2]*3)
Doesn’t work for set and dict.
IV. Division operator
▪ True division (/) wherever we use this operator it will give quotient as
an output and output will be in the form of float value.
E.g.: print(10/2)
▪ Floor division this operator gives quotient as an output and output will
be in the form of integer only if both numerator and denominator is
integer. If either numerator or denominator is float then output will be in
the form of float. E.g.: print(10//2)→5 print(10//3.3)→3.0 print
(10//3)→3
▪ Modulus this operator gives remainder as an output. E.g.:
print(10%2)→0 print(10%3)→1
V. Exponent (**) used as an exponential form. A**B. E.g.: print(2**10) →1024

2) Relational operator
Using this operator, we can compare one operand with another operand. Hence, it is
also called as comparison operator. It includes the operators like <, >, <=, >=, == and
!=
E.g.: print(a==b)→false print(a<=b)→true print(a<b)→true print(b>a)→ true
print(b>=a)→ true print (a!=b)→ true

3) Assignment operator
Using this operator we can assign values to variables. This operator includes +=, -=,
*=, /=, //=, %=, **=.
E.g.: a=100 a+=20 print(a)→ 120 a-=20 print (a)→ 80

4) Logical operators
Includes ‘and’, ‘or’, ‘not’. Using this we combine together and evaluate them and form
of true or false.
I. and operator: and is used to verify if all the given condition satisfies then the
output will be true. If any one condition is false then the output id false.
Input Input Output
True True True
False False False
False True False
True False False
E.g.: print(a==b and b==c and c==a) print(a!=b and b = c)
In and operator if the condition is true then it will continue to check the
remaining condition until it finds the false condition
If the first condition is false then it will not check the remaining condition.
e.g.: print(10 and 20 and 30.5) print(10 and 20 and 30)

II. or operator
In this type of operator if any one given condition is true then the output will be
true.
Input Input Output
True True True
False False False
False True True
True False True
E.g.: a=10 b=20 c= 10 print(a==b or b==a or c==a)
A=100 b=10 c= 10 print(a!=b or b==a or c>=a) print(10 or 20 or 30.5)
print(10 or 0 or 30) print(0 or 20 or 30) print(0 or 0 or 30)

III. not operator


It will invert the results if the condition is true than the result is false. And if the
condition is false then result is true. E.g.: A=0 print(not(a))

28/06/2024
5) Bitwise operators are used to perform operation on individual bits of binary numbers
The different kinds of bitwise operators are & (and), |(or), ~(not), ^(xor), <<, >>.
5.1 Bitwise and operator (&): And operator returns the result bit 1 only if both the bits are
1. If any one of the bit is 0 then the result the bit is 0.
Input Input Output
0 0 0
0 1 0
1 0 0
1 1 1

E.g.: 10&14
5.2 Bitwise or operator ( | ): this operator returns the result bit as 1 if any one of the
operand value has a bit of 1. It returns the result bit as 0 only if both the operand bits
are 0.
Input Input Output
0 0 0
0 1 1
1 0 1
1 1 1

E.g.: 10|14 binary value for 10 is 1010 and for 14 is 1110


1010
1110
1110→ 14

E.g.: 97|68
1100001→97
1000100 →68
1100101 →101

E.g.: 42|39
101010 →42
100111 →39
101111→ 47

E.g.: 56|52
111000 →56
110100 →52
111100→ 60

5.3 Bitwise not operator (~): this operator inverts the individual bits. 0 becomes 1 and 1
becomes 0. ~n = -(n+1)
Print (~11)→ -12 print (~(-12))→ 11
5.4 Bitwise xor operator (^): this operator gives the result bit as 1 only if any one of the
operand bit is 1. But not for both.
Input Input Output 1010→10
0 0 0 1110→14
0 1 1 0100→4
1 0 1
1 1 0

5.5 Bitwise left shit operator (<<): in this operator the left operand value is moved towards
left by the number of bits specified in the right operand. In left shift operator the value is
gained. x*2n 10<<1 1010 → 10100(20)
5.6 Bitwise right shift operator (>>): in this operator the left operand is moved towards
right by the number of bits specified in the right operand. x/2n 10>>1
1010→ 0101(5)
10>>2 →2
16>>3 → 2
6>>1→ 3
29/06/24
6) Membership operator (in, not in): It is a special type of operator we use in python to
check a sequence like string list and tuple for membership. Using this operator, we can
check whether the value is present in a given object or not. It will display the output as
a Boolean form. The different types of membership operators are 1) in 2) not in
In: by using this operator we can check if a value is present in the given sequence or
not if the specified value is present in a given sequence, then it will display the output
as true or else false.
E.g.: a=’pyspiders’ print (‘a’ in a)→ False print (‘p’ in a)→ true print (‘I’ in a)→false
Not in: this operator returns true if the specified value is not present in a given sequence
or else false.
E.g.: print (‘x’ not in a)→true print (‘y’ not in a)→ false

7) Identity operator (is, is not): This operator is used to check the address of the given
object. The different types of identity operator are 1) is 2) is not.
Is: this operator returns true if the address of the objects is seen.
E.g.: a=10 b=10 print (a is b)→ true
a= ‘pyhton’ b= ‘python’ (a is b)→true
l=[1,2,3] li= [1,2,3] print(l is li)→ false.
Is not: this operator returns true if the object does not belong to same memory location.
E.g.: a=10 b=10 print (a is not b)→ false
a= ‘pyhton’ b= ‘pyspiders’ (a is not b)→true
l=[1,2,3] li= [1,2,3] print(l is not li)→ true.

CONTROL STATEMENTS
In python control flow is the order in which the block or code will execute. Control statements
are used to control the flow of executing of the program. The control flow of python program
is regulated by the following statements
1. Conditional statements
2. Looping statement
3. Transfer statements

1. Conditional statements: in python the conditional statements are also called as


selectional statements or decisional statements. The conditional statement allows a
program to check a given condition and executes instructions on which the condition is
true.
The different types of conditional statements are, if, if else, elif, matchcase (version 3.10 and
above).
I. If: Using this conditional statement, we can pass a condition if the given condition
is true then it will enter into the block of code. If the given condition is false then it
will come out of the if block.
-------
-------
If <condition>: true
---
---
-----

-------
-------
If <condition>: false
---
---
-----
----

If
<cond>---→false→stop
true
Statement

Stop

e.g.: age=24
if age>=18
print (‘person is eligible to work’)

age=14
if age>=18
print (‘person is eligible to work’)
print(‘out of the if block’)

If else: this statement is also called as default block or false statement block. If the ‘if’ condition
is false then only the execution flow will enter into else block of code. If the if condition is true
then it will not enter into else block of code.
-------
-------
If <condition>: true
---
---
-----
Else <condition>:
---
---
------
------

-------
-------
If <condition>: false
---
---
Else <condition>:
---
---
------
------

If <condition>---→false→statement→stop
|
true
|
Statement
|
Stop

e.g.: age=10
if age>=18
print(‘person is eligible to vote’)
else:
print(‘age is less than 18’)
print(‘out of if block’)

01/07/2024
Elif: this statement is used to conditionally execute the block of code if ‘if’ condition is false
then it will enter into elif block of code. We can pass multiple elif statements for one if
statement.
Syntax:
------
------
If <condition>: true
---
---
Elif<condition>:
---
---
Else:
---
---
------

------
------
If <condition>: false
---
---
Elif<condition>: true
---
---
Else:
---
---
------
------

------
------
If <condition>: false
---
---
Elif<condition>: false
---
---
Else:
---
---
------
------

If→false→elif condition→false
| | |
True true statements
| | |
Statement statements stop
| |
Stop stop

E.g.: color=’blue’
If color==’green’:
Print (‘color is green’)
Elif color==’red’
Print (‘color is red’)
Else
Print (‘color is green’)

Nested if: an if statement in another if statement is called as nested if. If the first ‘if’ statement
is true then only it will enter into the inner if statement.
If <condition>: true
If <condition>: true
----
----
Else:
---
---
Else:
---
---
------
------

If <condition>: true
If <condition>: false
----
----
Else:
---
---
Else:
---
---
------
------

E.g.: age=4
If age>=18
If age>=80
Print (‘person cannot drive’)
Else:
Print (‘person can drive’)
Else:
Print (‘person cannot drive’)

Matchcase: it is a conditional statement which is used for pattern matching. This statement
that matches the value of an expression against a set of patterns and execute the code block
associated with it. It is similar to switch case statements in other programming languages. This
match case statement was introduced in python 3.10 version as a new feature.

Syntax:
a=value
match a:
case 1:
---
---
---
Case 2:
---
---
Case _:(default case)
---
---
E.g.: city='Mumbai'
match city:
case 'Chennai':
print('Capital of TN')
case 'Hyderabad':
print('Capital of TS')
case 'Mumbai':
print('Capital of MH')
case 'Delhi':
print('Capital of the country')
case _:
print('Capital of KA')

1. Write a program to enter names of your 3 fav food items and store them in a list.
2. Write a program to find the greatest of 2 numbers.
3. Write a program to find the largest of 3 number.

02/07/2024
2. Looping statements: Looping statements are used to repeat a block of code. In
python we have 2 different loops 1) for loop 2) while loop.
a. For loop: used to iterate over a sequence like str, list, tuple, set and dictionary. We
can execute a set of statements for each element in a given sequence.
Syntax: for variable in sequence:
For loop → true→ for body→ for loop
|
False
|
Stop

E.g.: a=[1,2,3,4]
For i in a:
Print(i) print ( I, end=’ ‘)
Tracing
For 1 in a : true
Print(1)
For 2 in a : true
Print(2)
For 3 in a : true
Print(3)
For 4 in a : true
Print(4)
End=’ ‘: End parameter is used to indicate a white space but not a new line

S=’python’ o/p→ p y t h o n
For j in s:
Print (j, end=’ ‘)
For 1 in s:
Print(p)
For 2 in s:
Print(y)
For 3 in s:
Print(t)
For 4 in s:
Print(h)
For 5 in s:
Print(o)
For 6 in s:
Print(n)

Range(): this functions returns sequence of values from the given index. By default, the
starting value is 0. We can use negative value in the step.
Syntax: for variable in range (starting value, ending value, step)

E.g.: for i in range(1,5,1): for i in range (5)→0-4 will be displayed


Print(i)
o/p :
1
2
3
4
For i in range (5,1,-1):
Print(i)
o/p:
5
4
3
2
b. While loop: it is used to execute a block of statements repeatedly. When the
number of iterations is known in advance there we use while loop.
Whenever we are using while loop, there are 3 mandatory steps
1) Initializing the value
2) Condition
3) Increment / decrement
Syntax: var=value
While <condition>: true→statement
---
---
Statement:
---
---
While <condition>: false→out of the loop
---
---
Statement:
---
---
While condition→false→stop
|
True
|
Statement/ while body
E.g.: a=1
While a<=4;
Print(a)
A+=1
a=1
While 1<=4;
Print(1)
A+=1 →a=2
a=2
While a<=4;
Print(2)
A+=1 →a=3
a=3
While a<=4;
Print(3)
A+=1→a=4
a=4
While a<=4;
Print(4)
A+=1 →a=5
A=5
While a<=4;
Print(a)
A+=5→stop

3. Transverse statements: in python we have 2 transverse statement break and


continue.
a. Break: Break is used is used to end the particular block of code ……….whenever we
use break then the current loop is terminated and flow will continue with rest of the
code followed by that comes after the loop .
For i in range(1, 10):
If i==5
Break
Print(i)
For 1 in range (1,10) : true
If 1==5:false
Print (1)
For 2 in range (1,10) : true
If 2==5: false
Print (2)
For 3 in range (1,10) : true
If 3==5:false
Print(3)
For 4 in range (1,10) : true
If 4==5:false
Print(5)
For 5 in range (1,10) : true
If 5==5:true
Break

I=1
While i<=10:
Print(i)
If i>=4:
Break
I+=1
b. Continue: This statement is used inside the loop to skip over the current iteration of
the loop and move on to the next iteration. When the continue statement is executed
within a loop the code inside the loop will immediately stop execution and loop will
jump into the next iteration.
E.g.:
For i in range (1,5):
If i==3:
Continue
Print(i)
For 1 in range (1,5) : true
If 1==3:false
Print (1)
For 2 in range (1,5) : true
If 2==3: false
Print (2)
For 3 in range (1,5) : true
If 3==3:true
continue
For 4 in range (1,5) : true
If 4==3:false
Print(4)
For 5 in range (1,5) : true
If 5==5:true
Print(5)

03/07/2024
Number programs
1. Write a program to swap the number without using 3rd variable.
I. Logic a=10 b=5
A=a+b→10+5
B=a-b→15-5
A=a-b→15-10
A=5 b=10
2. Write a program to swap the values using 3rd variable.
3. Write a program to print the numbers in a given range. (using for loop)
4. Write a program to print even numbers in a given range using for loop.
A=1
B=6
for i in range(a,b+1):
if i%2==0:
print(i)

Tracing
For i in range (1,7):
If 1%2==0: →false
For i in range (1,7):
If 2%2==0: →true
Print(2)
For i in range (1,7):
If 3%2==0: →false
For i in range (1,7):
If 4%2==0: →true
Print(2)
For i in range (1,7):
If 1%5==0: →false
For i in range (1,7):
If 1%6==0: →true
Print(6)
o/p: 2, 4, 6

5. Write a program to print odd numbers in a given range.


A=1
B=6
for i in range(a,b+1):
if i%2==1:
print(i)

Tracing
For i in range (1,7):true
If 1%2==1:
Print(1)
For i in range (1,7):
If 2%2==1:false
For i in range (1,7):
If 3%2==1:true
Print(3)
For i in range (1,7):
If 4%2==1:false
For i in range (1,7):
If 5%2==1:true
Print(5)
For i in range (1,7):
If 6%2==1:false
o/p: 1, 3, 5

6. Write a program to find the factorial of a given number.


f=1
for i in range(1,a+1):
f=f*i
print(f)
Tracing
For i in range (1,5):
F=1*1
F=1
For i in range (1,5):
F=1*2
F=2
For i in range (1,5):
F=2*3
F=6
For i in range (1,5):
F=6*4
F=24
For i in range (1,5):
F=24*5
F=120
7. Write a program to find factors of a given number.
for i in range(1,a+1):
if a%i==0:
print(i, end=(' '))
Tracing
For 1 in range (1, 4):
If 3%1==0:true
Print(1)
For 2 in range (1, 4):
If 3%2==1: false
For 3 in range (1, 4):
If 3%3==0:true
Print(3)

8. Write a program to find the sum of the given numbers.


s=0
for i in range(1,a+1):
s=s+i
print(s)
Tracing
For 1 in range(1, 5):
S=0+1
S=(1)
For 2 in range(1, 5):
S=1+2
S=(3)
For 3 in range(1, 5):
S=2+3
S=6
For 4 in range(1, 5):
S=6+4
Print(10)

9. Write a program to find the product of first 4 natural numbers. (same as factorial)
f=1
for i in range(1,a+1):
f=f*i
print(p)
Tracing
For i in range (1,5):
F=1*1
F=1
For i in range (1,5):
F=1*2
F=2
For i in range (1,5):
F=2*3
F=6
For i in range (1,5):
F=6*4
F=24

10. Write a program to print a number in the given range in reverse order using for and
while loop.
for i in range(a,b,-1):
if a>b:
a-=1
print(i, end=(' '))
or
while (a>=b):
print(a, end=(' '))
a-=1
Tracing a=5 b=1
For i in range(5,1,-1)
If 5>1:
Print(5)
For i in range(5,1,-1)
If 4>1:
Print(4)
For i in range(5,1,-1)
If 3>1:
Print(3)
For i in range(5,1,-1)
If 2>1:
Print(2)

Using while statement

While(5>=1):
Print(5)
a-=1→ 4
While(4>=1):
Print(4)
a-=1→ 3
While(3>=1):
Print(3)
a-=1→ 2
While(2>=1):
Print(2)
a-=1→ 1
o/p: 5 4 3 2
04/07/2024
11. Write a program to check the given number is prime number or not.
For i in range(1,a+1):
If a%i==0:
Count+=1
If count==2:
Print(‘number is prime’)
Else
Print (‘not a prime number’)
Tracing
A=5
For 1 in range (1,6)
If 5%1==0: true
Count=1
For 2 in range (1,6)
If 5%2==0: false
For 3 in range (1,6):
If 5%3==0:false
For 4 in range(1,6):
If 5%4==0: false
For 5 in range(1,6):
If 5%5==0: true
Count=2
If count==2
Print(‘prime number’)

A=6
For 1 in range (1,6)
If 6%1==0: true
Count=1
For 2 in range (1,6)
If 6%2==0: true
Count=2
For 3 in range (1,6):
If 6%3==0:true
Count==3
For 4 in range(1,6):
If 6%4==0: false
For 5 in range(1,6):
If 6%5==0: false
For 6 in range(1,7)
If 6%6==0:true
Count=4
Else:
Print(‘The number is not prime.’)

12. Write a program to reverse the given number.


rev=0
while n!=0:
rem=(n%10)
rev=rev*10+rem
n=n//10
print(rev)
tracing
a=654
while 654!=0 true
rem=654%10
rev=0*10+4 rev=4
n=654//10 n=65
while 65!=0 true
rem=65%10
rev=4*10+5 rev=45
n=65//10 n=6
while 6!=0
rem=6%10
rev=65*10+4 rev=0
n=6//10 n=654

a=230
while 230!=0
rem=230%10 rem=0
r=0*10+0 r=0
n=230//10 n=23
while 23!=0
rem=23%10 rem=3
r=0*10+3 r=3
n=23//10 n=2
while 2!=0
rem=2%10 rem=2
r=3*10+2 r=32n
n=2//10 n=0
r=32
Reverse of 230 is 32.
13. Write a program to check if the given number is palindrome or not.
r=0
temp=a
while a!=0:
rem=(a%10)
r=r*10+rem
a=a//10
if temp==r:
print('the number is palindrome')
else:
print('not a palindrome')

Tracing
A=252
Temp=a
While 252!==0:
Rem=252%10 rem=2
R=0*10+2 r=2
A=252//10 n=25
While 252!==0:
Rem=25%10 rem=5
R=2*10+5 r=25
A=25//10 n=2
While 252!==0:
Rem=2%10 rem=0
R=25*10+2 r=252
A=2//10 n=0
Temp==r
palindrome

14. Write a program to check the given number is strong number or not.
Strong number is a special number where sum of the factorial of each digit is equal to
the given number.
s=0
t=a
while a!=0:
rem=a%10
f=1
for i in range(1,rem+1):
f=f*i
s=s+f
a=a//10
if t==s:
print('strong number')
else:
print('not a strong number')
Tracing
A=145
While 145>0:
Rem=145%10 rem=5
F=1
For 1 in range (1, rem+1) i.e., range(1,6)
f=1*1
for 2 in range (1,6)
f=1*2 f=2
For 3 in range (1,6)
f=2*3 f=6
for 4 in range (1,6)
f=6*4 f=24
for 5 in range (1,6)
f=24*5 f=120
sum=0+120 sum=120
a=145//10 a=14
While 14>0:
Rem=14%10 rem=4
F=1
For 1 in range(1,5):
f=1*1
for 2 in range (1,5)
f=1*2 f=2
For 3 in range (1,5)
f=2*3 f=6
for 4 in range (1,5)
f=6*4 f=24
sum=120+24 sum=144
a=14//10 a=1
While 1>0:
Rem=1%10 rem=1
F=1
For 1 in range(1,2)
f=1*1 f=1
sum=144+1 sum=145
a=1//10 a=0
if t==sum
strong number

ASSIGNMENT
1. Reverse the number 17221
X=int(input(‘enter the number’))
Rev=0
While x!=0:
Rem=x%10
Rev=rev*10+rem
X=x//10
Print(rev)

➢ Tracing
1. X=17221
Rev=0
While 17221!=0:
Rem=17221%10 rem=1
Rev=0*10+1 rev=1
X=17221//10 x=1722
2. X=1722
Rev=1
While 1722!=0:
Rem=1722%10 rem=2
Rev=1*10+2 rev=12
X=1722//10 x=172
3. X=172
Rev=12
While 172!=0:
Rem=172%10 rem=2
Rev=12*10+2 rev=122
X=172//10 x=17
4. X=17
Rev=22
While 17!=0:
Rem=17%10 rem=7
Rev=122*10+7 rev=1227
X=17//10 x=1
5. X=1
Rev=1227
While 1!=0:
Rem=1%10 rem=1
Rev=1227*10+1 rev=12271
X=1//10 x=0
6. X=0
Rev=12271
While 0!=0:false
Print(rev)

2. Palindrome 222

X=int(input(‘enter the number’))


Temp=x
Rev=0
While x!=0:
Rem=x%10
Rev=rev*10+rem
X=x//10
If temp==rev:
Print(‘palindrome’)
Else:
Print(‘not palindrome’)

➢ Tracing
1. X=222
Rev=0
Temp=x
While 222!=0:
Rem=222%10 rem=2
Rev=0*10+2 rev=2
X=222//10 x=22
2. X=222
Rev=2
While 22!=0:
Rem=22%10 rem=2
Rev=2*10+2 rev=22
X=22//10 x=2
3. X=222
Rev=22
While 2!=0:
Rem=2%10 rem=2
Rev=22*10+2 rev=222
X=2//10 x=0
4. X=222
Rev=222
While 0!=0: false
If temp==rev
Print(‘palindrome’)

3. Strong number 178, 40585


X=int(input(‘enter the number: ‘)
Temp=x
Sum=0
Rev=0
While x>0:
rem=x%10
fact=1
for i in range(1,rem+1)
fact=fact*i
sum=sum+fact
x=x//10
if temp==sum
print(‘strong number’)
else
print(‘not a strong number’)
Tracing
1. X=178
While 178>0
Rem=178%10 rem=8
Fact=1
For 1 in range(1,9)
Fact=1*1 fact=1
For 2 in range (1,9)
Fact=1*2 fact=2
For 3 in range(1,9)
Fact=2*3 fact=6
For 4 in range (1,9)
Fact=6*4 fact=24
For 5 in range(1,9)
Fact=24*5 fact=120
For 6 in range (1,9)
Fact=120*6 fact=720
For 7 in range(1,9)
Fact=720*7 fact=5040
For 8 in range (1,9)
Fact=5040*9 fact=45360

Sum=0+45360 sum=45360
X=178//10 x=17
2. X=17
While 17>0
Rem=17%10 rem=7
Fact=1
For 1 in range(1,8)
Fact=1*1 fact=1
For 2 in range (1,8)
Fact=1*2 fact=2
For 3 in range(1,8)
Fact=2*3 fact=6
For 4 in range (1,8)
Fact=6*4 fact=24
For 5 in range(1,8)
Fact=24*5 fact=120
For 6 in range (1,8)
Fact=120*6 fact=720
For 7 in range(1,8)
Fact=720*7 fact=5040
Sum=45360+5040 sum=50400
X=17//10 x=1
3. X=1
While 1>0
Rem=1%10 rem=1
Fact=1
For 1 in range(1,2)
Fact=1*1 fact=1
Sum=50400+1 sum=50401
X=1//10 x=0
4. X=0
While 0>0: false
Not a strong number

X=40585
While 40585>0
Rem=40585%10 rem=5
Fact=1
For 1 in range(1,6)
Fact=1*1 fact=1
For 2 in range (1,6)
Fact=1*2 fact=2
For 3 in range(1,6)
Fact=2*3 fact=6
For 4 in range (1,6)
Fact=6*4 fact=24
For 5 in range(1,6)
Fact=24*5 fact=120

Sum=0+120 sum=120
X=40585//10 x=4058
5. X=4058
While 4058>0
Rem=4058%10 rem=8
Fact=1
For 1 in range(1,9)
Fact=1*1 fact=1
For 2 in range (1,9)
Fact=1*2 fact=2
For 3 in range(1,9)
Fact=2*3 fact=6
For 4 in range (1,9)
Fact=6*4 fact=24
For 5 in range(1,9)
Fact=24*5 fact=120
For 6 in range (1,9)
Fact=120*6 fact=720
For 7 in range(1,9)
Fact=720*7 fact=5040
For 8 in range(1,9)
Fact=5040*8 fact=40320
Sum=40320+120 sum=40440
X=4058//10 x=405
6. X=405
While 405>0
Rem=405%10 rem=5
Fact=1
For 1 in range(1,6)
Fact=1*1 fact=1
For 2 in range (1,6)
Fact=1*2 fact=2
For 3 in range(1,6)
Fact=2*3 fact=6
For 4 in range (1,6)
Fact=6*4 fact=24
For 5 in range(1,6)
Fact=24*5 fact=120
Sum=40440+120 sum=40560
X=405//10 x=40
7. X=40
While 40>0
Rem=40%10 rem=0
Fact=1
For 1 in range(1,1)
Fact=1*1 fact=1
Sum=40560+1 sum=40561
X=40//10 x=4

8. X=4
While 4>0
Rem=4%10 rem=4
Fact=1
For 1 in range(1,5)
Fact=1*1 fact=1
For 2 in range (1,5)
Fact=1*2 fact=2
For 3 in range(1,5)
Fact=2*3 fact=6
For 4 in range (1,5)
Fact=6*4 fact=24
Sum=40561+24 sum=40585
X=4//10 x=0
X=0
While 0>0: false
Strong number
05/07/2024
15. Write a program to print prime number in a given range.
A=int(input(‘enter the number’)
For i in range(1,a+1):
Count=0
For j in range (1,i+1)
If i%j==0:
Count+=1
If count==2:
Print(i, end=(‘ ‘))
A=4
For 1 in range(1,5)
Count=0
For 1 in range(1,2)
If 1%1==0
Count=1
If count==2: false
For 2 in range(1,5)
Count=0
For 1 in range(1,3)
If 2%1==0
Count=1
For 2 in range(1,3)
If 2%2==0
Count=2
If count==2: true
Print(2)
For 3 in range(1,5)
Count=0
For 1 in range(1,4)
If 3%1==0
Count=1
For 2 in range(1,4)
If 3%2==0: false
For 3 in range(1,4)
If 3%3==0:
Count==2
If count==2:
Print(3)
For 4 in range(1,5)
Count=0
For 1 in range(1,5)
If 4%1==0
Count=1
For 2 in range(1,5)
If 4%2==0
Count==2
For 3 in range(1,5)
If 4%3==0: false
For 4 in range(1,5)
If 4%4==0
Count=3
If count==2: false

o/p: 2,3
16. Write a program to count number of digits in a given number.
c=0
while a>0:
a=a//10
c+=1
print(c)
Tracing
A=153
C=0
While 153>0
A=153//10 a=15
C=1
While 15>0
A=15//10 a=1
C=2
While 1>0
A=1//10 a=0
C=3
While 0>0: false
Print(3)

17. Write a program to check the given number is armstrong number or not.
sum=0
temp=a
c=len(str(a))
while a>0:
rem=a%10
sum=sum+rem**c
a=a//10
if temp==sum:
print('armstrong')
else:
print('not armstrong')
Tracing
A=153
C=3
While 153>0:
Rem=153%10 rem=3
Sum=0+3**3 sum=27
A=153//10 a=15
While 15>0:
Rem=15%10 rem=5
Sum=27+5**3 sum=152
A=15//10 a=1
While 1>0:
Rem=1%10 rem=1
Sum=152+1**3 sum=153
A=1//10 a=0
While 0>0: false
Print(‘armstrong’)
ASSIGNMENT
1. Prime number range from 1-8
N=8
For 1 in range (1,9):
Count=0
For 1 in range(1,2):
If 1%1==0:
Count+=1
If count==2: false
For 2 in range (1,9):
Count=0
For 2 in range(1,3):
If 2%1==0:
Count+=1 count=1
If 2%2==0:
Count+=2 count=2
If count==2:
Print(2)
For 3 in range (1,9):
Count=0
For 3 in range(1,4):
If 3%1==0:
Count+=1 count=1
If 3%2==0:
Count+=1
If 3%3==0:
Count+=2 count=2
If count==2:
Print(3)
For 4 in range (1,9):
Count=0
For 4 in range(1,5):
If 4%1==0:
Count+=1 count=1
If 4%2==0:
Count+=2 count=2
If 4%3==0:
Count+=2
If 4%4==0:
Count+=3 count=3
If count==2:false
For 5 in range (1,9):
Count=0
For 5 in range(1,6):
If 5%1==0:
Count+=1 count=1
If 5%2==0:
Count+=1
If 5%3==0:
Count+=1
If 5%4==0:
Count+=1
If 5%5==0:
Count+=2 count=2
If count==2:
Print(5)

For 6 in range (1,9):


Count=0
For 6 in range(1,7):
If 6%1==0:
Count+=1 count=1
If 6%2==0:
Count+=2 count=2
If 6%3==0:
Count+=3 count=3
If 6%4==0:
Count+=3
If 6%5==0:
Count+=3 count=3
If 6%6==0:
Count+=4 count=4
If count==2:false

For 7 in range (1,9):


Count=0
For 7 in range(1,8):
If 7%1==0:
Count+=1 count=1
If 7%2==0:
Count+=1
If 7%3==0:
Count+=1
If 7%4==0:
Count+=1
If 7%5==0:
Count+=1
If 7%6==0:
Count+=1
If 7%7==0:
Count+=2 count=2
If count==2:
Print(7)

For 8 in range (1,9):


Count=0
For 8 in range(1,9):
If 8%1==0:
Count+=1 count=1
If 8%2==0:
Count+=2 count=2
If 8%3==0:
Count+=2
If 8%4==0:
Count+=3 count=3
If 8%5==0:
Count+=3
If 8%6==0:
Count+=3
If 8%7==0:
Count+=3
If 8%8==0:
Count+=4 count=4
If count==2:false
Print(2,3,5,7)

2. Check if 9 is Armstrong number or not


A=9
B=a
C=0
Temp=a
Sum=0
While 9(a)>0:
A=9//10
C=1
While 9(b)>0:
Rem=9%10 rem=1
Sum=0+1**1 sum=1
B=9//10 b=0
While 0>0: false
temp==9
Armstrong number

3. Check if 143 is Armstrong number or not


A=143
C=0
Temp=a
Sum=0
C=len(str(a)) c=3
While 143>0:
A=143%10 a=3
Sum=0+3**3 sum=27
A=143//10 a=14
While 14>0:
A=14%0 a=4
Sum=27+4**3 sum=91
A=14//10 a=1
While 1>0:
A=1%0 a=1
Sum=91+1**3 sum=92
A=1//10 a=0
While 0>0: false
temp!=sum

Not armstrong number.

06/07/24
18. Write a program to print the Armstrong numbers in a given range.
for i in range(1,200):
sum=0
n=i
c=len(str(n))
while n>0:
rem=n%10
sum=sum+rem**c
n=n//10
if i==sum:
print(f'{i} is armstrong number')
19. Write a program to check a given number is a perfect number or not
Perfect number is the sum of the given number the proper factors excluding the given
number should be equal to the given number.
sum=0
t=a
for i in range(1,a):
if a%i==0:
sum=sum+i
if t==sum:
print('perfect number')
else:
print('not a perfect number')
Tracing
A=6
For 1 in range (1,6):
If 6%1==0:
Sum=0+1 sum=1
For 2 in range(1,6):
If 6%2==0:
Sum=1+2 sum=3
For 3 in range (1,6):
If 6%3==0:
Sum=3+3 sum=6
For 4 in range(1,6):
If 6%4==0:false sum=6
For 5 in range(1,6)
If 6%5==0: false sum=6
Print(6 is a perfect number)

20. Write a program to print the perfect number in the given range.
for j in range(1,100):
sum=0
n=j
for i in range(1,n):7
if n%i==0:
sum+=i
if sum==j:
print(f'{j} is perfect number')

21. Write a program to check the given number is a happy number or not
a=int(input('enter the number: '))
while a!=1 and a!=4:
sum=0
while a>0:
rem=a%10
sum=sum+rem**2
a=a//10
a=sum
if sum==1:
print('happy number')
elif sum==4:
print('not a happy number')
Tracing
A=7
While a!=1 and a!=4:
Sum=0
While 7>0:
Rem=7%10 rem=7
Sum=0+7**2 sum=49
A=7//10 a=0
A=49
While a!=1 and a!=4:
Sum=0
While 49>0:
Rem=49%10 rem=9
Sum=0+9**2 sum=81
A=49//10 a=4
While 4>0:
Rem=4%10 rem=4
Sum=81+4**2 sum=91
A=4//10 a=0
A=91
While a!=1 and a!=4:
Sum=0
While 97>0:
Rem=97%10 rem=7
Sum=0+7**2 sum=49
A=97//10 a=9
While 9>0:
Rem=9%10 rem=9
Sum=49+9**2 sum=130
A=9//10 a=0
A=130
While a!=1 and 130!=4:
Sum=0
While 130>0:
Rem=130%10 rem=0
Sum=0+0 sum=0
A=130//10 a=13
While 13>0
Rem=13%0 rem=3
Sum=0+3**2 sum=9
A=13//10 a=1
While 1>0:
Rem=1%10 rem=1
Sum=9+1**2 sum=10
A=10
While 10!=1 and 10!=4:
Sum=0
While 10>0:
Rem=10%10 rem=0
Sum=0+0**2 sum=0
A=10//10 a=1
A=1
While 1!=1 and 1!=4 : false
Stop
Print(7 is a happy number)

ASSIGNMENT
1. 26 is a happy number or not
While 26!=1 and 26!=4:
Sum=0
While 26>0:
Rem =26%10 rem=6
Sum=0+6**2 sum=36
A=26//10 a=2
While 2>0:
Rem=2%10 rem=2
Sum=36+2**2 sum=40
A=2//10 a=0
A=40
While 40!=1 and 40!=4:
Sum=0
While 40>0:
Rem=40%10 rem=0
Sum=0+0 sum=0
A=40//10 a=4
While 4>0:
Rem=4%10 rem=4
Sum=0+4**2 sum=16
A=4//10 a=0
A=16
While 16!=1 and 16!=4:
Sum=0
While 16>0:
Rem=16%10 rem=6
Sum=0+6**2 sum=36
A=16//10 a=1
While 1>0:
Rem=1%10 rem=1
Sum=36+1**2 sum=37
A=1//10 a=0
A=37
While 37!=1 and 37!=4:
Sum=0
While 37>0:
Rem=37%10 rem=7
Sum=0+7**2 sum=49
A=37//10 a=3
While3>0:
Rem=3%10 rem=3
Sum=49+3**2 sum=58
A=3//10 a=0
A=58
While 58!=1 and 58!=4:
Sum=0
While 58>0:
Rem=58%10 rem=8
Sum=0+8**2 sum=64
A=58//10 a=5
While 5>0:
Rem=5%10 rem=5
Sum=64+5**2 sum=89
A=5//10 a=0
A=89
While 89!=1 and 89!=4:
Sum=0
While 89>0:
Rem=89%10 rem=9
Sum=0+9**2 sum=81
A=89//10 a=8
While 8>0:
Rem=8%10 rem=8
Sum=81+8**2 sum=145
A=8//10 a=0
A=145
While 145!=1 and 145!=4:
Sum=0
While 145>0:
Rem=145%10 rem=5
Sum=0+5**2 sum=25
A=145//10 a=14
While 14>0:
Rem=14%10 rem=4
Sum=25+4**2 sum=41
A=14//10 a=1
While 1>0:
Rem=1%10 rem=1
Sum=41+1**2 sum=42
A=1//10 a=0
A=42
While 42!=1 and 42!=4:
Sum=0
While 42>0:
Rem=42%10 rem=2
Sum=0+2**2 sum=4
A=42//10 a=4
While 4>0:
Rem=4%10 rem=4
Sum=4+4**2 sum=20
A=4//10 a=0
A=20
While 20!=1 and 20!=4:
Sum=0
While 20>0:
Rem=20%10 rem=0
Sum=0+0 sum=0
A=20//10 a=2
While 2>0:
Rem=2%10 rem=2
Sum=0+2**2 sum=4
A=2//10 a=0
A=4
While 4!=1 and 4!=4: false

Print( 26 is not a happy number)

2. 23 is a happy number or not


While 23!=1 and 23!=4:
Sum=0
While 23>0:
Rem=23%10 rem=3
Sum=0+3**2 sum=9
A=23//10 a=2
While 2>0:
Rem=2%10 rem=2
Sum=9+2**2 sum=13
A=2//10 a=0
A=13
While 13!=1 and 13!=4:
Sum=0
While 13>0:
Rem=13%10 rem=3
Sum=0+3**2 sum=9
A=13//10 a=1
While 1>0:
Rem=1%10 rem=1
Sum=9+1**2 sum=10
A=1//10 a=0
A=10
While 10!=1 and 10!=4:
Sum=0
While 10>0:
Rem=10%10 rem=0
Sum=0+0 sum=0
A=10//10 a=1
While 1>0:
Rem=1%10 rem=1
Sum=0+1**2 sum=1
A=1//10 a=0
A=1
While 1!=1 and 1!=4: false

Print(23 is a happy number)

3. Range

07/07/24
1. 1121 strong number or not
Sum=0
A=1121
T=a
While 1121>0:
Rem=1121%10 rem=1
F=1
For 1 in range (1, 2)
f=1*1 f=1
sum=0+1 sum=1
a=1121//10 a=112
while 112>0:
rem=112%10 rem=2
f=1
for 1 in range (1,3):
f=1*1 f=1
for 2 in range (1,3)
f=1*2 f=2
sum=1+2 sum=3
a=112//10 a=11
while 11>0:
rem=11%10 rem=1
f=1
for 1 in range (1,2):
f=1*1 f=1
sum=3+1 sum=4
a=11//10 a=1
while 1>0:
rem=1%10 rem=1
f=1
for 1 in range (1,2):
f=1*1 f=1
sum=4+1 sum=5
a=1//10 a=0
if t==sum: false
not a strong number
1. 1634 → Armstrong number or not
A=1634
C=0
Temp=a
Sum=0
C=len(str(a)) c=4
While 1634>0:
rem=1634%10 rem=4
Sum=0+4**4 sum=256
A=1634//10 a=163
While 163>0:
rem=163%0 rem=3
Sum=256+3**4 sum=337
A=163//10 a=16
While 16>0:
rem=16%0 rem=6
Sum=337+6**4 sum=1633
A=16//10 a=1
While 1>0:
rem=1%10 rem=1
Sum=1633+1**4 sum=1634
While 0>0: true
Temp==sum

Armstrong number.

2. 36 is a happy number or not

While 36!=1 and 36!=4:


Sum=0
While 36>0:
Rem=36%10 rem=6
Sum=0+6**2 sum=36
A=36//10 a=3
While 3>0:
Rem=3%10 rem=3
Sum=36+3**2 sum=45
A=3//10 a=0
A=45
While 45!=1 and 45!=4:
Sum=0
While 45>0:
Rem=45%10 rem=5
Sum=0+5**2 sum=25
A=45//10 a=4
While 4>0:
Rem=4%10 rem=4
Sum=25+4**2 sum=41
A=4//10 a=0
A=41
While 41!=1 and 41!=4:
Sum=0
While 41>0:
Rem=41%10 rem=1
Sum=0+1**2 sum=1
A=41//10 a=4
While 4>0:
Rem=4%10 rem=4
Sum=1+4**2 sum=17
A=4//10 a=0
A=17
While 17!=1 and 17!=4:
Sum=0
While 17>0:
Rem=17%10 rem=7
Sum=0+7**2 sum=49
A=17//10 a=1
While 1>0:
Rem=1%10 rem=1
Sum=49+1**2 sum=50
A=1//10 a=0
A=50
While 50!=1 and 50!=4:
Sum=0
While 50>0:
Rem=50%10 rem=0
Sum=0+0 sum=0
A=50//10 a=5
While 5>0:
Rem=5%10 rem=5
Sum=0+5**2 sum=25
A=5//10 a=0
A=25
While 25!=1 and 25!=4:
Sum=0
While 25>0:
Rem=25%10 rem=5
Sum=0+5**2 sum=25
A=25//10 a=2
While 2>0:
Rem=2%10 rem=2
Sum=25+2**2 sum=29
A=2//10 a=0
A=29
While 29!=1 and 29!=4:
Sum=0
While 29>0:
Rem=29%10 rem=9
Sum=0+9**2 sum=81
A=29//10 a=2
While 2>0:
Rem=2%10 rem=2
Sum=81+2**2 sum=85
A=2//10 a=0
A=85
While 85!=1 and 85!=4:
Sum=0
While 85>0:
Rem=85%10 rem=5
Sum=0+5**2 sum=25
A=85//10 a=8
While 8>0:
Rem=8%10 rem=8
Sum=25+8**2 sum=89
A=8//10 a=0
A=89
While 89!=1 and 89!=4:
Sum=0
While 89>0:
Rem=89%10 rem=9
Sum=0+9**2 sum=81
A=89//10 a=8
While 8>0:
Rem=8%10 rem=8
Sum= 81+8**2 sum=145
A=8//10 a=0
A=145
While 145!=1 and 145!=4:
Sum=0
While 145>0:
Rem=145%10 rem=5
Sum=0+5**2 sum=25
A=145//10 a=14
While 14>0:
Rem=14%10 rem=4
Sum=25+4**2 sum=41
A=14//10 a=1
While 1>0:
Rem=1%10 rem=1
Sum=41+1**2 sum=42
A=1//10 a=0
A=42
While 42!=1 and 42!=4:
Sum=0
While 42>0:
Rem=42%10 rem=2
Sum=0+2**2 sum=4
A=42//10 a=4
While 4>0:
Rem=4%10 rem=4
Sum=4+4**2 sum=20
A=4//10 a=0
A=20
While 20!=1 and 20!=4:
Sum=0
While 20>0:
Rem=20%10 rem=0
Sum=0+0**2 sum=0
A=20//10 a=2
While 2>0:
Rem=2%10 rem=2
Sum=0+2**2 sum=4
A=2//10 a=0
A=4
Not a happy number

22. Write a program to check if the given number is perfect square number.
a=int(input('enter the number: '))
for i in range(1,10):
if i*i==a:
print(f'{a} the number a perfect square')
break
Tracing
N=4
For 1 in range(1,5)
If 1*1=4: false
For 2 in range(1,5)
If 2*2=4: true
Print()
Break

23. Write a program to check the given number is sunny number or not

a=int(input('enter the number: '))


s=a
for i in range(1,50):
if i*i==a+1:
print(f'{s} the number a sunny number')
else:
print(f'{s} is not a sunny number')
break
Tracing
A=3
S=a
For 1 in range(1,10):
If 1*1==3+1: false
For 2 in range(1,10)
If 2*2=3+1: true
Print(3 is a sunny number)

24. Write a program to check it the given number is Neon number or not.

a=int(input('enter the number: '))


sq=a*a
sum=0
while sq>0:
rem=sq%10
sum=sum+rem
sq=sq//10
if sum==a:
print(f'{a} is neon number')
Tracing
A=9
Sq=9*9 sq=81
While 81>0:
Rem=81%10 rem=1
Sum=0+1 sum=1
Sq=81//10 sq=8
While 8>0:
Rem=8%10 rem=8
Sum=1+8 sum=9
Sq=8//10 sq=0
While 0>0: false
Sum==a
Print(9 is a neon number.)

08/07/2024

25. Write a program to arrange the elements in ascending order using bubble sort.
a=[2,6,3,8,1]
temp=0
for i in range(0,len(a)-1):
for j in range(len(a)-1):
if a[j]>a[j+1]:
temp=a[j]
a[j]=a[j+1]
a[j+1]=temp
# a[j],a[j+1]=a[j+1],a[j]
print(a)
Tracing
For 0 in range (0,4)
For 0 in range(4):
If a[0]>a[1]:
A[0],a[1]=a[1],a[0]

For 1 in range(4):
If a[1]>a[2]:
A[1], a[2] = a[2], a[1]

For 2 in range(4):
If a[2]>a[3]:
A[3], a[2] = a[2], a[3]

For 3 in range(4):
If a[3]>a[4]:
A[3], a[4] = a[4], a[3]
Print(A)
[2, 3, 6, 1, 8]

For 1 in range (0,4)


For 0 in range(4):
If a[0]>a[1]:
A[0],a[1]=a[1],a[0]

For 1 in range(4):
If a[1]>a[2]:
A[1], a[2] = a[2], a[1]

For 2 in range(4):
If a[2]>a[3]:
A[3], a[2] = a[2], a[3]

For 3 in range(4):
If a[3]>a[4]:
A[3], a[4] = a[4], a[3]
Print(A)
[2, 3, 1, 6, 8]

For 2 in range (0,4)


For 0 in range(4):
If a[0]>a[1]:
A[0],a[1]=a[1],a[0]

For 1 in range(4):
If a[1]>a[2]:
A[1], a[2] = a[2], a[1]

For 2 in range(4):
If a[2]>a[3]:
A[3], a[2] = a[2], a[3]

For 3 in range(4):
If a[3]>a[4]:
A[3], a[4] = a[4], a[3]
Print(A)
[2, 1, 3, 6, 8]

For 3 in range (0,4)


For 0 in range(4):
If a[0]>a[1]:
A[0],a[1]=a[1],a[0]

For 1 in range(4):
If a[1]>a[2]:
A[1], a[2] = a[2], a[1]

For 2 in range(4):
If a[2]>a[3]:
A[3], a[2] = a[2], a[3]

For 3 in range(4):
If a[3]>a[4]:
A[3], a[4] = a[4], a[3]
Print(A)

[1, 2, 3, 6, 8]
For 4 range(0,4) : false

26. Write a program to sort the elements in desc order.


temp=0
for i in range(0,len(a)-1):
for j in range(len(a)-1):
if a[j]<a[j+1]:
temp=a[j]
a[j]=a[j+1]
a[j+1]=temp
# a[j],a[j+1]=a[j+1],a[j]
print(a)

27. Write a program for Fibonacci series of sequence 5


num=5
a1=0
a2=1
sum=0
for i in range(1,num):
print(sum)
a1=a2
a2=sum
sum=a1+a2
Tracing
For 1 in range (1,5):
Print(sum) →0
A1=1 a1=1
A2=sum a2=0
Sum=1+0 sum=1
For 2 in range (1,5):
Print(sum) →1
A1=0 a1=0
A2=sum a2=1
Sum=1+0 sum=1
For 3 in range (1,5):
Print(sum)→ 1
A1=1 a1=1
A2=sum a2=1
Sum=1+1 sum=2
For 4 in range (1,5):
Print(sum) → 2
A1=1 a1=1
A2=2 a2=2
Sum=2+1 sum=3

28. Write a program to write the first 3 even numbers from the given number.
a=int(input('enter the nun:'))
c=0
for i in range(a+1,a+7):
if i%2==0:
print(i)
Tracing
A=3
C=0
For 4 in range(4, 10)
If 4%2==0
Print(4)
For 5 in range(4,10)
If 5%2==0: false
For 6 in range (4,10)
If 6%2==0:
Print(6)
For 7 in range (4, 10)
If 7%2==0: false
For 8 in range(4,10)
If 8%2==0
Print(8)
For 9 in range (4, 10)
If 9%2==0: false
o/p: 4, 6, 8.
09/07/2024
STRING PROGRAMS
1. WAP to find vowels in a given string.
A= input(‘enter the string: ‘)
Vowels=’aeiouAEIOU’
For i in a:
If i in vowel:
Print(i)

Tracing
A=Punar
For P in Punar:
If P in vowels: false
For u in Punar:
If u in vowels:
Print(u)
For n in Punar:
If n in vowels: false
For a in Punar:
If a in vowels: true
Print(a)
For r in Punar:
If r in vowels: false
o/p: u, a

2. WAP to remove the duplicates present in the given string.


S=input(‘enter the string: )
Str=’ ‘
For i in s:
If i not in str:
Str+=i
Print(str)
S=books
For b in s:
If b not in str:
Str=’ ‘ + b
For o in s:
If o not in str:
str=b+o
for o in s:
if o not in str: false
for k in s:
if k not in str:
str=bo+k
for s in s:
if s not in str:
str=bok+s
print (boks)

3. WAP to reverse the given string


Str= input(‘enter the string: )
Rev=’ ‘
i= len(str)-1
While i>=0:
Rev+=str[i]
i-=1
print(rev)

str = python
rev =’ ‘
i=5
while 5>=0:
rev = ‘ ‘+n
i = 5-1 =4
while 4>=0:
rev = n + o
i = 4-1 =3
while 3>=0:
rev = no + h
i = 3-1 =2
while 2>=0:
rev = noh + t
i = 2-1 =1
while 1>=0:
rev = noht + y
i = 1-1 =0
while 0>=0:
rev = nohty + p
i = 0 -1 = -1
while -1>=0: false
print(nohtyp)

4. WAP to check the given string is palindrome or not. → MALAYALAM


Str = input (‘enter the string: ‘)
Rev = ‘ ‘
i=len(str)-1
while i>=0:
rev=rev+str[i]
i= -1
print (rev)
if str == rev:
print (f ‘{str} is palindrome’)
else:
print (‘not a palindrome’)
5. WAP to count the number of times the given character is present in given string.
s=input('enter the string: ')
count=0
char=input('enter the character: ')
for i in s:
if i==char:
count+=1
print('number of occurances in ', f'{char} is', count)

6. WAP to find the duplicates in a given string.


N = input (‘enter the string: ‘)
S= ‘’
For i in n:
C=0
For j in n:
If j not in s:
If i==j:
C+=1
If c>1:
S=s+1
Print(s)

10/07/2024
LIST PROGRAMS
1. Write a program to find all the elements from the given list.
Li= [1, 2, 3, 4]
For i in li:
Print(i)
Tracing
C=4
For 1 in li:
1
For 2 in li:
2
For 3 in li:
3
For 4 in li:
4
O/p: 1 2 3 4

2. WAP to find only even number from the list.


l=[2,3,5,3,1,8,4,2]
for i in l:
if i%2==0:
print(i)
Tracing
For 2 in l:
If 2%2==0:
Print(2)
For 3 in l:
If 3%2==0: false
For 5 in l:
If 5%2==0: false
For 3 in l:
If 3%2==0: false
For 1 in l:
If 1%2==0: false
For 8 in l:
If 8%2==0:
Print(8)
For 4 in l:
If 4%2==0:
Print(4)
For 2 in l:
If 2%2==0:
Print(2)
Print(2, 8, 4, 2)

3. WAP to print sum of all the elements from the given list.
L = [2,3,5,3,1,8,4,2]
C=len(l)
sum=0
for i in range(1,c):
sum+=i
print(sum)
Tracing
C=8
Sum=0
For 2 in range(1,8)
Sum=0+2
Print(2)
For 3 in range (1,8)
Sum=2+3
Print(5)
For 5 in range(1,8)
Sum=5+5
Print(10)
For 3 in range (1,8)
Sum=10+3
Print(13)
For 1 in range(1,8)
Sum=13+1
Print(14)
For 8 in range (1,8)
Sum=14+8
Print(22)
For 4 in range(1,8)
Sum=22+4
Print(26)
For 2 in range (1,8)
Sum=26+2
Print(28)
Total (28)

4. WAP to find the product of all the numbers from the given list.
l=[2,3,5,3,1,8,4,2]
p=1
for i in l:
p*=i
print(p)
Tracing
P=1
For 2 in l:
P=1*2
Print(2)
For 3 in l:
P=2*3
Print(6)
For 5 in l:
P=6*5
Print(30)
For 3 in l:
P=30*3
Print(90)
For 1 in l:
P=90*1
Print(90)
For 8 in l:
P=90*8
Print(720)
For 4 in l:
P=720*4
Print(2880)
For 2 in l:
P=2880*2
Print(5760)

5. WAP to print the sum of only the even numbers from the given list.
l=[2,3,5,3,1,8,4,2]
sum=0
for i in l:
if i%2==0:
sum+=i
print(sum)
Tracing
C=8
For 2 in l:
If 2%2==0:
Sum=0+2
Print(2)
For 3 in l:
If 3%2==0: false
For 5 in l:
If 5%2==0: false
For 3 in l:
If 3%2==0: false
For 1 in l:
If 1%2==0: false
For 8 in l:
If 8%2==0:
Sum=2+8
Print(10)
For 4 in l:
If 4%2==0:
Sum=10+4
Print(14)
For 2 in l:
If 2%2==0:
Sum=14+2
Print(16)
Print(2, 10, 14, 16)

6. WAP to remove the duplicates from the given list.


l=[2,3,5,3,1,8,4,2,3,1]
dl=[]
for i in l:
if i not in dl:
dl+=[i]
print(dl)
Tracing
For 2 in l:
If 2 not in dl:
dl=[] + [2]
print(2)
For 3 in l:
If 3 not in dl:
dl=[2] + [3]
print(2,3)
For 5 in l:
If 5 not in dl:
dl=[2,3] + [5]
print(2,3,5)
For 3 in l:
If 3 not in dl: false
For 1 in l:
If 1 not in dl:
dl=[2,3,5] + [1]
print(2,3,5,1)
For 8 in l:
If 8 not in dl:
dl=[2,3,5,1] + [8]
print(2,3,5,1,8)
For 4 in l:
If 4 not in dl:
dl=[2,3,5,1,8] + [4]
print(2,3,5,1,8,4)
For 2 in l:
If 2 not in dl: false
For 3 in l:
If 3 not in dl: false
For 1 in l:
If 1 not in dl: false

O/p: [2,3,5,1,8,4]

7. Reverse the given list.


l=[2,3,3,2,1]
li=[]
c=len(l)-1
while c>=0:
li=li+[l[c]]
c-=1
print(li)

using for loop


for i in range(c,-1,-1):
li=li+[l[i]]
print(li)
Tracing
C=5-1
While 4>=0:
Li=[]+l[4] li= [1]
C=c-1 c=3
While 3>=0:
Li=[1]+l[3] li= [1,2]
C=c-1 c=2
While 2>=0:
Li=[1,2]+l[2] li= [1,2,3]
C=c-1 c=1
While 1>=0:
Li=[1,2,3]+l[1] li= [1,2,3,3]
C=c-1 c=0
While 0>=0:
Li=[1,2,3,3]+l[0] li= [1,2,3,3,2]
C=c-1 c=-1

Print([1,2,3,3,2])

8. WAP to find the first maximum number from the given list. ****
L=[2,3,5,3,1,8,4,2]
m=0
for i in l:
if m<i:
m=i
print(m)
Tracing
M=0
For 2 in l:
If 0<2:
m=2
print(2)
For 3 in l:
If 2<3:
m=3
print(3)
For 5 in l:
If 3<5:
m=5
print(5)
For 3 in l:
If 5<3: false
For 1 in l:
If 5<1: false
For 8 in l:
If 5<8:
m=8
print(8)
For 4 in l:
If 8<4: false
For 2 in l:
If 8<2: false
Print(8)

9. WAP to find the second max number from the given list. ****
l=[1,5,2,8,6]
fmax=0
smax=0
for i in l:
if fmax<i:
fmax=i
print(f'{fmax} is the first maximun number')
for i in l:
if smax<i and fmax>i:
smax=i
print(f'{smax} is the second maximun number')
Tracing
Fmax=0
Smax=0
For 1 in l:
If 0<1:
Fmax=1
For 5 in l:
If 1<5:
Fmax=5
For 2 in l:
If 5<2: false
For 8 in l:
If 5<8:
Fmax=8
For 6 in l:
If 8<6: false
Fmax=8
For 1 in l:
If 0<1 and 8>1:
For 5 in l:
If 1<5 and 8>1:
smax=5
For 2 in l:
If 5<2 and 8>1: false
For 8 in l:
If 5<8 and 8>1: false
For 6 in l:
If 5<6 and 8>1:
Smax=6
Smax=6
FUNCTIONS
A function is a block of code organised by a set of instructions to perform a specific
task. Functions can be reused any number of times by calling the function. Functions can
enhance the code readability and it promotes the code reusability.
FUNCTION DECLARATION IN PYTHON
Syntax: def functionname( ):
----
----
----
Functionname( )→ function call

Def: def is a keyword used to declare the function and it is called as function definition.
Functionname: it is a name given to the function to identify the operation and also to call the
function.
Function call: a function can be called using its name. we can pass the valid values to the
parameters specified while defining the function.
E.g.: def wishes ( ):
Print(‘hi’)
Print(‘have a nice day’)
wishes ( )
Execution flow: whenever the function is called the control of the program goes to the
function definition. It executes all the code present inside the function after executing the
code the control of the program jumps to the next statement present after the function call.
ASSIGNMENT
1. WAP to print only the duplicates in a list.
N = [1,6,4,5,3,2,7,4,2,1]
Ul = []
For i in n:
C=0
For j in n:
If j not in ul:
If i==j:
C+=1
If c>1:
ul=ul[i+1]
Print(ul)

11/07/2024
E.g.: def sum(a,b)
Print(a+b)
Sum(2,5)

PARAMETERS: Parameters are the variables given to the function when the function is
declared. Parameters are separated by comma and we can declare any number of parameters.
If we create a function with parameter, we need to pass the corresponding values while
calling them.
Syntax: def functionname (var1, var2, var3):

ARGUMENT: an argument is a value given to the parameters.


Syntax: functionname (val1, val2, val3)
E.g.: def sum (a, b, c)
Print(a + b + c)
Sum(2,5) → error → missing argument

RETURN
In python return statement ends the execution of the function and returns the result to
the function call. The statement after the return statement will not be executed. Return
statement cannot be used outside the functions. If the return statement without any
expression, then it will return the output as None.
Syntax: def functionname():
---
---
Return
Functionname()
E.g.: def sum(a,b):
return(a+b)
c=sum(5,3)
print (c)→ 5
E.g.: def add(a,b):
print(a+b)
print(add(3,2)) → 5, none
E.g.: def sum(a,b):
return(a+b)
return(a-b) → will not be executed
c=sum(3,2)
print (c) → 5
E.g.: def mul (a,b):
X=a*b
return(a+b)
c=mul (2,12)
print (c)→ 24

TYPES OF FUNCTIONS

In python there are 2 types of functions:

1. Built-in functions
These are the predefined functions that can perform some specific tasks.
2. User-defined functions
The functions which are defined by the user to perform specific task, those we
call it is used defined functions. We can call the user-defined functions in 4 different
ways
I. Function without return and without arguments.
In this type of function while defining and calling the function we can’t
pass any arguments to the function and this type of function will not return any
value.
E.g.:
def sum ():
a=3
b=2
print(a+b)
sum ()

II. Function with return and without arguments


In this type of function user will not pass any arguments to the function
while defining or calling but whenever we call this type of function it will
return some value.
E.g.:
def sum():
a=4
b=7
return(a+b)
c=sum()
print (c)

III. Function without return and with arguments


For this type of function, it allows the user to pass the arguments while
calling it. But this type of function will not return any value when we call it.
E.g.:
def mul(a,b):
print(a*b)
mul(3,4)

IV. Function with return and with arguments


In this type of function user can pass the arguments while calling the
function and function returns some value. This type of user-defined function,
we call as fully dynamic function because it provides the maximum control to
the users.
E.g.:
def sub(x,y):
return(x-y)
r=sub(10,5)
print(r)

TYPES OF ARGUMENTS
In python we can pass the arguments in different ways like
1. Default arguments
2. Positional arguments
3. Keyword arguments
4. Variable-length arguments
Default arguments
Default arguments are the values that are provided while defining the function
assignment operator is used to assign the default values to the arguments. Default
arguments become optional in the function call.
If we provide a value to the default arguments during the function call it will override the
default values. The function can have any number of default arguments.
E.g.: 1
def add(x=3, y=5):
print(x+y)
add() → 8
E.g.: 2
def add(x=3, y=5):
print(x+y)
add(7,3)→ 10
E.g.: 3
def add(x=3, y=5):
print(x+y)
add(10) → 15
E.g.: 4
def add(x=3, y):
print(x+y)
add(10) → error → parameter without a default follows a parameter with default
E.g.: 5
def add(x=3, y):
print(x+y)
add(10,5) → error → parameter without a default follows a parameter with default
E.g.: 6
def add(x, y=5):
print(x+y)
add(10) → 15

Positional arguments
In this type of arguments during the function call the value passed through the
arguments should be in the order of parameter in function definition.
No. of parameters = no. of arguments
E.g.: 1
def sub (a,b)
print(a-b)
sub(10,3) → 7
E.g.: 2
def sub (a,b,c)
print(a-b-c)
sub(10,3) → error → missing argument

Keyword arguments
In this type of argument during the function call the values passed through the argument
along with the parameter. Here, the argument doesn’t need to be in the order of parameter that
is present in function definition.
E.g.: 1
def sum(a,b)
print(a+b)
sum (a=5, b=20) → 25

E.g.: 2
def sum(a,b)
print(a+b)
sum (b=5, a=20) → 25

E.g.: 3
def sum(a,b)
print(a+b)
sum (a1=5, b=20) → error
All the key word argument must match the parameter present in the function definition.

E.g.: 4
def sum(a,b,c)
print(a+b+c)
sum (a=5, b=20, 30) → error → positional argument follows keyword arguments

E.g.: 5
def sum(a,b,c)
print(a+b+c)
sum (30, a=5, b=20) → error → too many arguments for a
12/07/2024
Variable-length arguments
These are also called as arbitrary arguments whenever we don’t know the number of
arguments needed for the function then we have to go for arbitrary arguments. There are 2
types of arbitrary arguments
a. Arbitrary positional arguments (single packing or tuple packing or args)
b. Arbitrary keyword arguments (double packing or dictionary or kwargs)
Arbitrary positional arguments: this argument is represented by a single asterisk (*) is
placed before a parameter in the function definition which can hold n number of
parameters. This argument is also called as variable length positional arguments. This
argument will be wrapped into a tuple. Hence, it is called as tuple packing or single
packing.
E.g.: 1
def num (*n)
Print(n)
Num(1)
Num(1,2)
Num(1,4,2,8,3,2)

E.g.: 2
def num(b,*n):
print(n,b)
num(1,4,2,5,6) → (4,2,5,6) 1
E.g.: 3
def num(*n, b):
print(n,b)
num(1,4,2,5,6) → error

E.g.: 4
def num(*n,b=7):
print(n,b)
num(1,4,2,5,6) → (1,4,2,5,6) 7

E.g.: 6
def num(*n,b):
print(n,b)
num(1,4,2,5,b=6) → (1,4,2,5,6) 6
12/07/2024
Arbitrary keyword arguments: it is also called kwargs or double packing. In this type of
arguments, we can pass n number of keyword arguments ad it is represented by double
asterisk (**) which is placed before the parameter in function definition and it holds the
keyword variable length arguments and wrap the output in the form of key value pair.
Hence, it is called as dictionary packing.
E.g.: 1
def dicp(**n):
print(n)
dicp(a=2, b=3)
E.g.: 2
def dicp(d, **n):
print(d, n)
dicp(10, a=2, b=3)
E.g.: 3
def dicp(**n, d):
print(n, d)
dicp(a=2, b=3, 1) → error
E.g.: 4
def dicp(d=1, **n):
print(d, n)
dicp(a=2, b=3)

NOTE:
• Default argument should follow non-default arguments
• Default arguments are optional arguments
• No arguments should accept the values more than once.
• All the keyword arguments passed must matched with anyone of the parameter
present in the function definition and order is not important.
• After the arbitrary keyword argument, we can’t pass any other parameter.
1. WAP to swap a value without using third variable with argument and without return
value.
2. WAP to find some of the given number by using function with argument and with
return value.
3. WAP to check the given is prime or not by using function with argument and with
return value.
4. Strong number without return without argument
5. Armstrong number with return without argument

13/07/2024
SCOPE OF VARIABLES
Scope of variables is nothing but we can specify the area where we can access a
variable in python there are 2 types of variables.

1. Global variable
2. Local variable

GLOBAL VARIABLE:

If we declare a variable outside the function then it is called as global variable. We


can access this global variable inside the function as well as outside the function but we can’t
the modify this global variable inside a function.
E.g.: 1
A=10
Def gl():
Print(A)
gl()
print(A)

E.g.: 2
A=10
Def gl():
A=a+15
Print(A) → error
gl()
print(A)

LOCAL VARIABLE:

Whenever we declare a variable inside the function, we can call it as local variable we
can access this variable only within a function.
E.g.: 1
Def f1():
A=10
Print(A)
f1 ()

E.g.: 2
Def f1():
A=15
Print(A)
f1()
print(A) → error

GLOBAL KEYWORD:

To make a global variable available to the function so that we can perform required
modification and to access the local variable outside the function we can make use of the
‘global’ keyword.

We can declare the global keyword within a function before initializing a value.
E.g.: 1
A=10
Def f1():
global A
A=A+10
Print(A) →20
f1 ()
print(A) → 20

E.g.: 2
Def f1():
global A
A=15
Print(A)
f1()
print(A) → 15

E.g.: 3
Def f1():
A=10
global A
A=30
Print(A) → error
f1 ()

E.g.: 4
Def f1():
global x
x=111
Print(x) → 111
Def f2():
Print(x) →111
f1()
f2()

E.g.: 5
Def f1():
global x
x=111
Print(x)
Def f2():
Print(x) → error → x not defined
f2()
f1()

NESTED FUNCTIONS

A function within another function is called as nested function.


Syntax:
def outer ():
print(‘from outer function’)
def inner ():
print(‘from inner function’)
inner ()
outer()

NON-LOCAL KEYWORD:

This keyword is used only for the nested functions. If we want to do the modification for the
local variable from the upper scope then we can make use the keyword ‘nonlocal’.
E.g.: 1
def ofun ()
x=10
def infun()
nonlocal x
x=x+25
print(x)
infun()
ofun()

LAMBDA FUNCTION:
It is also called as anonymous function or one time execution function because for this
kind of function there is not identity or there is no function name for this lambda function.
Hence, we can’t call the function again and again we can declare these types of functions
with the keyword lambda. We can use this kind of function for instant use.
Syntax: var= lambda argument : expression
E.g.: 1
X= (lambda a,b:a+b) (2,3)
Print(x)

E.g.: 2
X= (lambda a,b:a+b)
Print(x(4,5))
Print(x(3,2))

a=(lambda a: a%2==0)(4)
print(a)

a=lambda a: a*a
for i in range (1,11):
print('the square of {} is {}' .format(i,a(i)))

li=[1,3,5,2,4]
def sqr(n):
return (n*n)
a=list(map(sqr,li))
print(a)

# using lambda
x=list(map((lambda a:a*a),(li)))
print(x)

15/07/2024

MAP ()

This function is a built-in function in python. Using this function, we can return the
result after applying a function to each and every element present in a given sequence. For
every element present in the given sequence apply some function and generate a new element
with required modification.
Syntax: Map (functionname, sequence)
E.g.: 1
Li=[2,3,4,5]
Def sq(n):
Return n*n
A=list(map(sq,li)
Print(A)

E.g.: 2
Li=[2,3,4,5,6]
L=[5,1,4,2,3]
A=list(map(lambda x,y:x+y, li,l))
Print(a) → [7,4,8,7,9]
E.g.: 3
Li=[2,3,4,5,6,4,2,7,4,2]
L=[5,1,4,2,3]
A=list(map(lambda x,y:x+y, li,l))
Print(a) → [7,4,8,7,9]

FILTER ()
Filter function is an in-built function in python. We can use this function to filter the
values from the given sequence based on some condition.
Syntax: filter (function, sequence)
Here the function argument is responsible to perform conditional check.
The function is applied to each and every element in the given sequence. If it returns true then
the element is selected by the filter.
E.g.: 1
li=[1,2,4,5,3,6]
def even (num)
if num%2==0:
return true
return false
x=tuple (filter (even, li))
Print(x)

REDUCE ()
Reduce function is a part of python’s functools module. It is used to apply a function
to all the elements in a given sequence so that reduce function reduces the given sequence
into a single element. Before using reduce function first we need to import functools.
Syntax: from functools import *
reduce (function, sequence)
E.g.: 1
From functools import *
Def mul(x,y)
Return x*y
A=reduce(mul, [1,2,3,4])
Print(a)

E.g.: 2
from functools import*
str=['python', 'java', 'sql', 'web']
def add(x,y):
return x+' '+y
a=reduce(add, str)
print(a)

E.g.: 3 → using lambda


from functools import*
str=['python', 'java', 'sql', 'web']
a=reduce((lambda x,y: x+' '+y), str)
print(a)

DIFFERENCE BETWEEN PRINT AND RETURN


PRINT RETURN
This function we can use n number of times. Can be used only once for one block of code
Without def we can use print Without def we can’t use return
It is used to print/display the result It is used to terminate the execution
We can’t store the result for further use We can store the result
After print we can write any number of After return we can’t write any statements
statements
19/07/2024

OOPS
OBJECT ORIENTED PROGRAMING SYSTEM
Oops is the one of the best ways to approach a standard functionality. Object oriented
programming is defined as a programming para diagram built on the concept of objects.
ADVATAGES OF OOPS
• By using oops we can organize the code in a proper way.
• We can avoid duplication of attribute, objects and other programable entities.
• To secure data and make data accessible to authorized one.
• To utilize memory and time by making processing faster.
• When there is no availability of in-built methods, we can create classes to perform
operations.

CLASS
Class is a template or a blueprint which defines the properties of an object. A class is a
fundamental way of python that gives the way for object-oriented programming. It is a user
defined type that can be accessed and used by creating an instance of that class. It has its own
data members and member functions. We can create a class to store user defined variables
and methods which can be used for n number of times.
To create a class, we can use the syntax: class classname:
Classname should always be in pascal case (it should start with upper case and should not
include any space, _ or special characters)
To join different words in single class name we can capitalize the name.
E.g.: 1. class Bank: 2. class BankOfBaroda:

OBJECT
Instance of class which describes its own data and properties. Objects are variables
that contain data and functions that can be used to manipulate the data.
Syntax:
class classname:
objectname=classname()

To access the class attributes using an object we can make use of dot notation.
E.g.: obj.attributes
The 4 main pillars of oops are
• Polymorphism
• Inheritance
• Encapsulation
• Abstraction
class Emp:
name=''
job=''
empno=0
sal=0
a1=Emp()
a1.name='Sam'
a1.job='Professor'
a1.empno=12432
a1.sal=4300

a2=Emp()
a2.name='Ash'
a2.job='Dean'
a2.empno=17374
a2.sal=4300

a3=Emp()
a3.name='Dan'
a3.job='Doctor'
a3.empno=12434
a3.sal=6400
print(a1.name, a1.job, a1.empno, a1.sal)
print(a2.name, a2.job, a2.empno, a2.sal)
print(a3.name, a3.job, a3.empno, a3.sal)

class Emp:
def __init__(self,name,age):
self.name=name
self.age=age
a1=Emp('Pradeep', 21)
a2=Emp('Deepak',26)
a3=Emp('Samiksha', 18)
print(a1.name,a1.age)
print(a2.name,a2.age)
print(a3.name, a3.age)

20/07/2024
CONSTRUCTORS
Constructors are a special type of method in python. The name of the constructor should
always be __init__ (self). It will be executed automatically at the time of object creation. It is
mainly used to declare and initialise the values to the variables. Constructor can take at least
one argument i.e., self. Using constructor is not mandatory. If we don’t provide any
constructor then python will execute the code by using default constructor.
TYPES OF CONSTRUCTORS
1. Default constructors
2. User defined constructors
There are 2 types of user defined constructors
a. Parameterised constructors
b. Non-parameterised constructors

1. DEFAULT CONSTRUCTORS
Whenever user doesn’t explicitly define a constructor within a class then python itself creates
a constructor internally during the compilation of the program is called as default constructor.
E.g.:
class Std:
def read(self,name,age):
self.name=name
self.age=age
print(self.name, self.age)
s1=Std()
s1.read('anu', 21)

a. PARAMETERISED CONSTRUCTOR
When the constructor accepts the parameter along with the self then it is called as
parameterised constructor.
E.g.:
class Std:
def __init__(self,name,age):
self.name=name
self.age=age
def display(self):
print(self.name, self.age)
s1=Std('Raja', 22)
s2=Std('anu', 21)
s1.display()
s2.display()
b. NON-PARAMETERISED CONSTRUCTOR
Whenever the constructor does not accept any parameters from the object and has only
one parameter i.e., self that type of constructor is called as non-parameterised constructor.
There is no necessary for non-parametrised constructor in python. It is up to the programmer
whether to include non-parameterised constructor in a class. This type of constructor is used
to when you want to initialise default values for an instance variable of an object.
E.g.:
class Nonp:
def __init__(self):
self.name='kavya'
self.age=20
n1=Nonp()
print(n1.name, n1.age)

class Std:
clgname='Pyspiders'
def __init__(self, name, id):
self.name=name
self.id=id
def display(self):
print('stdname is ',self.name, 'stdid is ', self.id, 'clg name is ',
self.clgname)

# print(Std.clgname)
@classmethod
def getcls(cls):
print(cls.clgname)
@staticmethod
def getavg(x,y):
print(x+y//2)
s1=Std('Punarvasu', 123)
s1.display()
s1.getcls()
s1.getavg(10,20)

22/07/2024

SELF
Self is a reference variable which always points to the current object. In python, for
class to refer to the current object, we should use self variable. The first argument to the
constructor and instance method should be always self. PVM is responsible to provide a
value for the self argument and it is not required to provide a value explicitly. By using self,
we can declare and access instance variables.
Syntax:
1. def __init__ (self):
2. def methodname (self):
TYPES OF VARIABLES IN OOPS
The different types of variables we can use inside and outside of the class are
1. Instance variables / object level variables
2. Static variables / class level variables
3. Local variables

1. INSTANCE VARIABLES
Instance variables are also called as object level variables. If the value of variables
varies from one object to another object the such type of variables we can call it as instance
variables. For every object a separate copy of instance variable will be created.
DECLARING INSTANCE VARIABLE
1. Inside the constructor by using self variable.
2. We can declare inside the instance method by using self variable
3. Outside of the class by using object reference variable.
E.g.:
class Std:
def __init__(self,a,b):
self.name=a
self.id=b
def read(self):
print(self.name, self.id)
ob=Std('anil', 1223)
ob.age=24
print(ob.__dict__) →{'name': 'anil', 'id': 1223, 'age': 24}
ob1=Std('sunil', 2341)
print(ob1.__dict__) → {'name': 'sunil', 'id': 2341}

MODIFYING INSTANCE VARIABLE:


• To modify instance variable present in constructor we can directly make use of object
reference.
• To modify instance variable which are present in instance method we should create a
class method and using object call method then in very next step we have to modify
the variables by referring to that particular object.
• Can modify instance variables outside of the class by using object reference variables,
we need to create an object and call that method.
E.g.:
class Exp:
def __init__(self):
self.a=10
self.b=20
self.c=30
def m1(self):
self.d=40
def m2(self):
self.e=50
o1=Exp()
o1.m1()
o2=Exp()
o2.m2()
o2.x=100
o2.y=150
print(o1.__dict__)
print(o2.__dict__)

We can delete an instance variable.


I. To delete the instance variable within a method we can make use of the syntax
Del self.variablename
II. To delete the instance variable outside the class we can make use of the syntax
Del objectreference.variablename
E.g.:
class Exp:
def __init__(self):
self.a=10
self.b=20
self.c=30
def delete(self):
del self.a
o1=Exp()
o1.delete()
del o1.c
print(o1.__dict__)

24/07/2024
2. STATIC VARIABLES
Static variable is also called as class level variable. If the value of variable doesn’t vary from
object to object, then such type of variables, we can declare inside a class but outside the
method scope.
We can access static variables by classname or by object reference.
It is recommended to use classname to the static variables which makes it easy to recognise.
Declaring static variable:
• We can declare static variables inside a class.
• We can declare a static variable within a constructor with classname.variable
• We can declare inside the instance method by using classname.variable
• Inside the class method by using cls or classname
• Inside static method by using classname
• From outside the class by using classname

E.g.: 1
class Exp:
a=10
def __init__ (self):
Exp.b=20
def m1 (self):
Exp.c=30
@classmethod
def m2 (cls):
cls.d=40
Exp.e=50
@staticmethod
def m3():
Exp.f=60
e=Exp()
e.m1()
e.m2()
Exp.m2()
Exp.m3()
Exp.g=70
Print(Exp__dict__)

E.g.: 2
class Pyspi:
a=10
def __init__ (self)
self.a=20
e=Pyspi()
print(Pyspi.a) → a=10
print(e.a) → a=20

E.g.: 3
class Pyspi:
a=10
def __init__ (self)
Pyspi.a=20
e=Pyspi()
print(Pyspi.a) → 20
print(e.a) → 20

E.g.: 4
class Pyspi:
a=10
def __init__(self):
Pyspi.a=25
@classmethod
def c1(cls):
cls.a=15
Pyspi.a=40
e=Pyspi()
e.c1()
print(Pyspi.a)
print(e.a)

E.g.: 5
class Pyspi:
a=10
def __init__(self):
# del Pyspi.a
e=Pyspi()
e.c1()
del Pyspi.a
print(Pyspi.__dict__)
# print(e.a)

E.g.: 6
class Py:
a=10
def __init__(self):
self.b=20
def read():
print(60)
p1=Py()
p2=Py()
Py.a=111
p1.b=222
print(p1.a, p1.b)
print(p2.a, p2.b)
Py.read()
Output
111 222
111 20
60
23/07/2024
3. LOCAL VARIABLE
Local variables or temporary variables. In order to meet the requirements, we need to declare
the temporary variables. We can declare local variables inside the method.
These variables are not associated with either self or cls. When we call the methods for
execution these, we can use these variables for certain operations.
These variables we cannot access outside the method.
E.g.: 1
class Exp:
def m1(self):
a=321
print(a)
def m2(self):
b=321
print(b)
ob1=Exp()
ob1.m1()
ob1.m2()

E.g.: 2
class Exp:
def method (self):
x=10
print(x)
ob=Exp()
ob.method()

Accessing local variable from one method to another method


E.g.: 3
class Exp:
def method (self):
global x
x=10
print(x)
def m2(self):
print(x)
ob=Exp()
ob.method()
ob.m2()

REQUIREMENT FOR BANK APPLICATION


Welcome to Pyspi bank
Enter the cust name:
Choose option
1. Deposit
a. Deposit→ old balance + current deposit
2. Withdraw
a. Current balance → current balance – withdraw
3. Exit
4. If cust choose wrong option it should display a msg ‘choose valid option’

METHODS
Methods are functions that are associated with an object or a class in python programming.
They are used to perform specific task on the data stored within objects or classes.
Methods in python are used to define the behaviour of the python objects.
Using this we can break down the complex tasks into more manageable task. Methods
improves the readability and maintainability of the code.
SYNTAX:
def methodname ()
----

TYPES OF METHODS
There are 3 types of methods in python programming
1. Instance method
2. Class method
3. Static method

1. INSTANCE METHOD
Associated with an instance of a class and can modify the data stored within the
instance. Instance methods are defined within a class definition and are called instance of the
class using dot notation (.). self is the first argument we can declared for instance method.
In general, when any method consists of instance variables then it is called as instance
method.
SYNTAX:
def methodname(self)
self.variable=’ ‘

2. CLASS METHOD
The method which includes the class variables are called as class method. We can create a
class method by using a decorator @classmethod. For class method we should provide cls as
a first argument at the time of method declaration. We can access class method using class
name or object reference.
SYNTAX:
@classmethod
def methodname(cls):
cls.variable=’ ‘
classname.variable=’ ‘

3. STATIC METHOD
Static methods are instances of class. They do not take either self or cls as a parameter and we
cannot access the instance variables or class variables in static methods.
To define a static method, we must use a decorator @staticmethod before declaration of
method.
Static methods are also called as utility methods. As they are often used to perform the
independent functions and doesn’t depend on any data of class.
They can be used to perform calculations or some operations related to the class but not
dependent on it.
SYNTAX:
@staticmethod
def methodname()
----
E.g.:
class Std:
clgname='Pyspiders'
def __init__(self, name, id):
self.name=name
self.id=id
def display(self):
print('stdname is ',self.name, 'stdid is ', self.id, 'clg name is ',
self.clgname)

# print(Std.clgname)
@classmethod
def getcls(cls):
print(cls.clgname)
@staticmethod
def getavg(x,y):
print(x+y//2)
s1=Std('Punarvasu', 123)
s1.display()
s1.getcls()
s1.getavg(10,20)

DIFFERENCE BETWEEN METHOD AND CONSTRUCTOR


METHOD CONSTRUCTOR
Method name can be anything. Name should be always __init__
Method will be executed if we call the Constructor will be executed automatically
method. when we create an object.
For one object method can be called any For one object constructor will execute only
number of times. once.
Within a method we can write a business It is used to declare and initialise instance
logic. variables.

DIFFERENCE BETWEEN METHOD AND FUNCTION

ACCESSING ONE CLASS MEMBERS TO ANOTHER CLASS


We can access one class members to other class members in 2 ways.
1. Is-A relation
2. Has-A relation

1. IS-A RELATION
It is also called as aggregation.
If we want to extend the existing functionality with some more additional functionalities then
we should prefer IS-A relation. If we don’t want to extend any functionality of parent class
then we can use HAS-A relation.
In IS-A relation there are different ways to access or modify any class member by inheriting
them in other class.
2. HAS-A RELATION
It is also called as composition without the container object there is no chance of existing
contained object because container and contained objects are strongly associated. Hence it is
called as composition or HAS-A relation.
Container object → parent class contained object → child class
E.g.:
class Emp:
def __init__(self,name,sal):
self.name=name
self.sal=sal
def display(self):
print(self.name, self.sal)
class SalInc:
def inc(x):
x.sal=x.sal+500
x.display()
e1=Emp('Ash', 20000)
SalInc.inc(e1)

EXECUTION FLOW
1. E1=Emp() → Initializes the value
2. SalInc.inc(e1) → e1 is called inside SalInc class
3. In def inc() → sal will be incremented
4. X.display() → print(values)
25/07/2024
INNER CLASS OR NESTED CLASS
If a class is present inside another class, then this class is called as inner class or nested class.
Syntax:
class outer:
--
--
class inner:
---
---
Inner class is always depending on outer class. Inner class can’t exist without an outer class
existence.
E.g.:
Class Outer:
Class Inner:
Def m1 (self):
Print(‘hi’)
I=Outer()
O=i.Inner()
o.m1()

Without existing one type of object if there is no chance of existing another type of object
then we should go for inner class.
E.g.:
class Person:
def m1(self):
self.name=input('name: ')
self.date=self.Dob()
self.Dob.m2('24/04/1997')
class Dob:
def m2(date):
print(date)
p=Person()
p.m1()

GARBAGE COLLECTOR
If we want to delete any variables or methods or classes we can use Garbage collector.
In python, GC is always enabled by default and python virtual machine will perform the
garbage collection implicitly. Whenever we create multiple objects to the class if it is not
necessary to keep all of the objects, we can delete them. The deleted members of the class
will go to the garbage collector and it will destroy it permanently. When we don’t delete any
unused variables or objects manually then if the object or variable has a 0 reference then also
the garbage collector collects them automatically.
import gc
print(gc.isenabled()) → true
gc.disable()
print(gc.isenabled()) → false
gc.enable()
print(gc.isenabled()) → true

DESTRUCTOR
Destructor is a special method before destroying an object GC always calls the
destructor to perform clean-up activities. Once the destructor’s execution is completed then
the GC automatically destroy the object. Destructor will not destroy it will only clean-up the
object. Defined with __del__.
26/07/2024

INHERITANCE
The process of deriving a new class from an existing class is called as inheritance.
By using this inheritance, we can inherit the properties of the existing to a new class and this
new class we can call as derived class or sub class or child class.
The existing class is called as super class or parent class or base class because these classes
which are not derived from any other classes.
ADVANTAGES OF INHERITANCE
• It improves the code reusability i.e., there is no need to write the same code again and
again.
• Using inheritance, we can inherit the features of other class and also, we can add
some additional features to the child class.
• By using the concept of inheritance, the program will be more concised and structured
so that it makes it easy to read and improves the readability of the code.
The different types of inheritance in python are
1. Single level inheritance
2. Multi-level inheritance
3. Multiple inheritance
4. Hierarchical inheritance
5. Hybrid inheritance

1. SINGLE LEVEL INHERITANCE


Single level inheritance is the basic inheritance of all the types of inheritance in python. In
this type of inheritance, we can derive a single sub class from the single parent class or the
existing class. The child will take or inherit all the properties of parent class. It can also add
its own method and attributes of the parent class.
SYNTAX:
class parent:
pass
class child(parent):
pass
E.g.:
class Parent:
def m1(self):
print('I’m from parent class')
class Child(Parent):
def m2(self):
print('I’m from child class')
#v1=Parent()
#v1.m1()
v2=Child()
v2.m2()
v2.m1()
• Assignment
class Mobile:
def __init__(self, processor, color):
self.color=color
self.processor=processor
class OnePlus(Mobile):
def __init__(self,processor, color, price):
super().__init__(processor, color)
self.price=price
def m1(self):
print(self.processor, self.price, self.color)
a1=OnePlus('android', 'green', '30000')
a1.m1()

27/07/2024
CONSTRUCTOR CHAINING
Constructor chaining is the process of calling one constructor from another constructor. This
will be useful when we want to invoke multiple constructors one after the another by
initializing an instance.
Constructor chaining is useful when we are working with inheritance. When an instance of a
child class is initialised the constructors of all the parent class are first invoked and then in
the last the constructor of the child class is invoked. We can achieve a constructor chaining in
2 ways i.e.,
1. Using super ( )
2. By using classname

1. By using super () method we can invoke a parent class constructor from child class.
SYNTAX:
super().__init__ (var1, var2)

2.
SYNTAX:
classname.__init__ (self, var1, var2)

E.g.:
class Animals:
def __init__(self, tail, color):
self.color=color
self.tail=tail
class Cat(Animals):
def __init__(self, tail, color, walk):
# Animals.__init__(self, tail, color)
super().__init__(tail, color)
self.walk=walk
def m1(self):
print(self.color, self.tail, self.walk)
a1=Cat('tail', 'black', 'catwalk')
a1.m1()

MULTI-LEVEL INHERITANCE
In this type of inheritance, a new class is derived from a parent class which is derived from
another parent class. The new class or child class can inherit all the properties and method of
both parent classes or existing class.
SYNTAX:
class Grandparent:
Pass
class Parent (Grandparent):
Pass
class Child (Parent):
pass

Superclass → Grandparent
Intermediate → Parent
Subclass → Child

E.g.:
class Animals:
def __init__(self, legs, type):
self.legs=legs
self.type=type
class Canine(Animals):
def __init__(self, legs, type, tail):
super().__init__(legs, type)
self.tail=tail
class Dog(Canine):
def __init__(self, legs, type, tail, breed):
super().__init__(legs, type, tail)
self.breed=breed
def s1(self):
print(self.legs, self.type, self.tail, self.breed)
c1=Dog('4legs','Animal','tail present', "Huskey")
c1.s1()
class Animal:
def __init__(self, name):
self.name=name
def display(self):
return self.name
class Dog(Animal):
def sound(self):
return 'bowbow'
class Streetdog(Dog):
def run(self):
return 'runs too fast'
d1=Streetdog('snoopy')
print(d1.display())
print(d1.sound())
print(d1.run())

class Fb:
def m1(self):
print('Facebook by meta')
class Insta(Fb):
def m2(self):
print('Instagram by meta')
class Threads(Insta):
def m3(self):
print('Threads by meta')
s1=Threads()
s1.m1()
s1.m2()
s1.m3()
s2=Insta()
s2.m1()
s2.m2()
s3=Fb()
s3.m1()

MULTIPLE INHERITANCE
E.g.:
class Youtube:
def __init__(self, reels):
self.reels=reels
class Insta:
def __init__(self, follow):
self.follow=follow
class Threads(Youtube,Insta):
def __init__(self, reels, follow, msgs):
Youtube.__init__(self,reels)
Insta.__init__(self,follow)
# super() is applied only for 1st not for 2nd parent
self.msgs=msgs
def show(self):
print(self.reels,',', self.follow, ',', self.msgs)
c1=Threads('shorts', 'followers and following', 'msgs')
c1.show()

SYNTAX:
class Parent1:
pass
class Parent2:
pass
class Child (Parent1, Parent2):
pass

• ASSIGNMENT
Class qsp, pyspi, jspi → Single, multi, multiple using constructor chaining.

28/07/2024
MULTIPLE INHERITANCE
It is type of inheritance in which a new class derived from two or more existing class.
The new class inherits all the attributed and methods of the multiple parent class.
SYNTAX: A B
class Parent: Parent Parent1
pass C
class Parent1: Child
pass
class Child (Parent, Parent1):
pass

In multiple inheritance the inheritance takes place from right to left that is right most class
will be inherited first and then the left most class will be inherited in the last.
For multiple inheritance we can use super method only for the immediate parent.
E.g.:
class Person:
def __init__ (self, name):
self.name=name
def display (self):
return self.name
class Emp:
def __init__ (self, salary):
self.salary=salary
def salm (self):
return self.salary
class Manager (Person, Emp):
def __init__ (self, name, salary):
super (). __init__ (name)
Emp __init__ (self, salary)
ob=Person (‘Sunil’, 100000)
print(ob.display())
print(ob.salm())

HIERARCHICAL INHERITANCE
Hierarchical inheritance in this type of inheritance single parent class derives multiple child
classes all the child classes inherit all the properties and method of parent class.
The child class can also add their properties and method to the class.
SYNTAX:
class Parent: Parent
pass A

class Son (Parent)


pass B C D

class Daughter (Parent) Child1 Child2 Child3


pass

E.g.:
class Father:
fname=’Ambani’
def display (self):
print (‘I am from father Ambani class’)
class Son (Father):
def read (self):
print (“son’s name is”, self.fname)
class Daughter (Father):
def show (self):
print (“Daughter’s name is “, self.fname)
ob=Son()
ob.read()
ob1=Daughter()
ob1.show()

HYBRID INHERITANCE
In this type of inheritance, we can use more than 1 from of inheritance.
E.g.:
class A: A
def m1 (self):
print (‘from method A’)
class B(A): B(A) C(A)
def m2 (self):
print (‘from method B’)
class C (A): D(B, C)
def m3 (self):
print (‘from method C’)
class D (B, C):
def m4 (self):
print (‘from method D’)
ob=B ()
ob.m2()
ob.m1()
ob1=D ()
ob1.m2()
ob1.m3()

POLYMORPHIM
Polymorphism is derived from a Greek word where poly means many and morphism means
forms.
In Python polymorphism is having the ability of an object to take many forms.
1. 10+10 → 20
2. ‘good’ + ’morning’ → ‘good morning’

In the above example the + operator perform arithmetic operation and the same + operator
performs concatenation between the strings.
len (‘python’) → 6 → it will not count no. of characters in a string
len C [1,2,’a’, ‘b’, 3] → 5 → it will count the number of items in the given list
len C {‘a’:’b’, 1:2} → 2 → it will count the number of keys in the given dict
We can achieve polymorphism in two ways
1. Overloading
2. Overriding

1. OVERLOADING
In python we can perform overloading in three ways
a. Operator overloading
b. Method overloading
c. Constructor overloading
29/07/2024
Overloading is a mechanism which takes place while compilation. In python, compilation
takes place implicitly hence we actually don’t have overloading in python. While compilation
only the definitions get stored in heap, it will update and create the most recent methods only.
If you try to overload the method it will raise type error. To overcome, the conflicts of
overloading we can make use of
1. Magic methods
2. Single dispatch
3. Multiple dispatch

OPERATOR OVERLOADING
1. Magic method
Magic methods are the special methods in python which can be represent by __
double underscore at both prefix and suffix of the method name. Magic methods are
most commonly used for operator overloading.
E.g.: for arithematic
__add__()
__sub__()
__div__()
__floordiv__()
__mul__()
__pow__()

E.g.: for assignment


__iadd__()
__isub__()
__idiv__()
__ifloordiv__()
__imul__()
__ipow__()
E.g.: relational operators
Less than → __lt__()
Greater than → __gt__()
equal to → __eq__()
not equal to → __neq__()
greater than equal to → __ge__()
Less than equal to → __le__()

Magic methods are not invoked directly but invocations happen internally in the class on
certain operations.
E.g.:
class Textbook:
def __init__ (self, pages):
self.pages=pages
def __add__ (self, x):
return self.pages+x.pages
b1=Textbook(300)
b2=Textbook(200)
print(b1+b2)

Whenever we perform operator overloading it internally invokes magic methods when we use
plus operator for the objects in Textbook class the method is going to overload and the add
method return value and that value will be the output of ob1 + ob2. ob1 value is always
assigned to self and ob2 value is always assigned to second argument.
E.g.: for more than 2 objects
class Textbook:
def __init__ (self, pages):
self.pages=pages
def __str__ (self):
return ‘the number of pages: ‘+ str(self.pages)
def __add__ (self, x):
sum= self.pages+x.pages
b=Textbook(sum)
return b
b1=Textbook(300)
b2=Textbook(200)
b3=Textbook(400)
b4=Textbook(400)
print(b1+b2+b3+b4)
30/07/2024
METHOD OVERLOADING
Method overloading is nothing but creating multiple methods with the same name but passing
different parameters. Using method overloading we can perform different operations with the
same method name.
In python, it doesn’t support method overloading as other programming languages. If you
want to overload the method with different parameters or arguments it will work for the latest
method.
E.g.:
class Mo:
def add (self, a):
print(a)
def add (self, a, b):
print(a,b)
def add (self, a, b, c):
print(a,b,c)
ob=Mo()
ob.add(3,5,1)
ob.add(2,4) → error

We can achieve method overloading by using single dispatch and multiple dispatch
1. Single dispatch
Single dispatch is a method decorator from functools module. We can use it
for restricting the data type of parameters to avoid overriding. Only the first parameter
can be registered in the function or method definition. It will check the datatype of the
parameter and executes specific method accordingly.
E.g.:
from functools import singledispatch, singledispatchmethod
class Ex:
@singledispatchmethod
def add(self, a):
print(a)
@add.register(int)
def x(self,a):
print(a+25)
@add.register(float)
def x(self,a):
print(a+25)
@add.register(complex)
def x(self,a):
print(a+10)
ob=Ex()
ob.add(10)
ob.add(20)
ob.add(20+1j)

2. Multiple dispatch
Multiple dispatch is a package of preferred installer program (pip). Before using we have to
install it by using a command pip install multipledispatch. From this package we can use a
dispatch decorator to read multiple parameters. Number of parameters of main method should
match all the methods else it will overload the method with matching number of parameters.
While decorating if we give same type of arguments always for the main function to execute.
All methods should have same name else it will raise error called mismatched error.
E.g.:
from multipledispatch import dispatch
class Mo:
@dispatch(int,int)
def add(self, a, b):
print(a+b)
@dispatch(int,float)
def add(self, a, b):
print(a+b)
@dispatch(float,int)
def add(self, a, b):
print(a+b)
@dispatch(float,float)
def add(self, a, b):
print(a+b)
ob=Mo()
ob.add(5,6)
ob.add(4,6.2)
ob.add(2.4,4.7)
ob.add(2.5,7)

CONSTRUCTOR OVERLOADING
Constructor overloading is nothing but defining multiple constructors within a class while
each constructor is taking a different set of parameters. If you want to achieve constructor
overloading then we have to import dispatch from multipledispatch.
E.g.: 1
class Co:
def __init__ (self,a):
print (a)
def __init__ (self, a, b):
print (a, b)
def __init__ (self, a, b, c):
print (a, b, c)
ob=Co (2,5,3)
ob=Co (3,1) → error → missing 1 positional argument

*In this above example constructor overloading will work for latest constructor. Using
dispatch, we can achieve this constructor overloading for all the defined constructor.

E.g.: 2
from multipledispatch import dispatch
class Co:
@dispatch(int)
def __init__ (self,a):
print (a)
@dispatch(float, int)
def __init__ (self, a, b):
print (a, b)
@dispatch(int, float, float)
def __init__ (self, a, b, c):
print (a, b, c)
ob=Co (10)
ob=Co (12.2, 16)
ob=Co (1,7.0, 25.6)
ob=Co (3, 2.4) → error no signature found for __init__ : <int, float>

METHOD OVERRIDING
In python, method overriding change the implementation of a method in the child
class which is defined in the parent class. Using inheritance we can achieve the mechanism of
method overriding. Method overriding avoids the duplication of codes and it allows the code
for adding some additional functionalities. Method overriding can’t be done in one class
hence, we need to inherit or derive a child class from parent class.
E.g.:
class Vehicles:
def display(self):
print('runs on fuel')
def show(self):
print('it has 4 wheels')
class Bike(Vehicles):
def show(self):
# super(). show() → old property and new property.
print('it has 2 wheels')
abc=Bike()
abc.display()
abc.show()
31/07/2024

ENCAPSULATION
It is a process of wrapping up of variables and methods into a single entity. So that it provides
a security by hiding the data from the outside of the class.
NEED OF ENCAPSULATION/ ADVANTAGES
Encapsulation allows us to restrict the accessing of variables and methods directly. It prevents
the data modification by creating private data member or private method inside the class.
ACCESS MODIFIERS
Access modifiers are used to restrict the access of variables and methods outside the class. In
python we can achieve this in three ways.
1. Public access modifier
2. Protected access modifier
3. Private access modifier

1. PUBLIC ACCESS MODIFIER


Public member of a class can be access within a class, within a child class and outside the
class.
E.g.: accessing variables within class
class Abc:
def __init__(self):
self.x=50
def m1 (self):
print(self.x)
ob=Abc()
ob.m1()

E.g.: within child class


class Abc:
def __init__(self):
self.x=50
class Xyz(Abc):
def m1 (self):
print(self.x)
ob=Xyz()
ob.m1()

E.g.: outside the class


class Abc:
def __init__(self):
self.x=50
ob=Abc()
print(ob.x)
01/08/2024
E.g.: Accessing methods within the class
class Abc:
def m1 (self):
print('public class')
def show(self):
self.m1()
ob=Abc()
ob.show()

E.g.: Within child class


class Abc:
def m1 (self):
print('public class')
def show(self):
self.m1()
class Xyz(Abc):
def show(self):
self.m1()
ob=Xyz()
ob.show()

E.g.: outside the class


class Abc:
def m1 (self):
print('public class')
def show(self):
self.m1()
ob=Abc()
ob.show()

2. PROTECTED ACCESS MODIFIERS


Protected members of a class can be access within a class and within a child class. But we
can’t access them outside the class. In python the protected members don’t work according to
their functionality. It can be represented with _ (single underscore).
E.g.: data member within class
class Abc:
def __init__(self):
self._x=50
def m1 (self):
print(self._x)
ob=Abc()
ob.m1()

E.g.: data member within a child class


class Abc:
def __init__(self):
self._x=50
class Xyz(Abc):
def m1 (self):
print(self._x)
ob=Xyz()
ob.m1()

E.g.: Outside the class


class Abc:
def __init__(self):
self._x=50
ob=Abc()
print(ob._x)

3. PRIVATE ACCESS MODIFIERS


Private members of a class can be accessed only within a class. We can’t access private
members outside the class and inside the child class.
We can represent private member by prefix with __ (double underscore).
E.g.: data members within a class
class Abc:
def __init__(self):
self.__x=50
def m1 (self):
print(self.__x)
ob=Abc()
ob.m1()

E.g.: within a child class


class Abc:
def __init__(self):
self.__x=50
class B(Abc):
def m1 (self):
print(self.__x)
ob=B()
ob.m1() → error → B object has not attribute __x

E.g.: Outside the class


class Abc:
def __init__(self):
self.__x=50
ob=Abc()
print(ob.__x) → error

E.g.: method within a class


class Abc:
def __m1 (self):
print('private class')
def show(self):
self.__m1()
ob=Abc()
ob.show()

E.g.: method within a child class


class Abc:
def __m1 (self):
print('private class')
def show(self):
self.__m1()
class B(Abc):
def show(self):
self.__m1()
ob=B()
ob.show() → error

E.g.: outside the class


class Abc:
def __m1 (self):
print('private class')
ob=Abc()
ob._Abc__m1()

E.g.:
class Std:
def __init__(self, name, regno, marks):
self.name=name
self._regno=regno
self.__marks=marks
def show(self):
print('name is ',self.name)
print('regno is ',self._regno)
print('Marks is ',self.__marks)
s1=Std('Raj', 123, 400)
s1.show()
print(s1.name)
print(s1._regno)
print(s1.__marks) → error

GETTER SETTER METHOD


Setter method is used to set the value to the private member. We can set the value with the
method declaration.
Syntax:
def methodname(self, var):
self. __variable=var
can use → classname. __variable=var

Getter is used to retrieve a value of the private member with the help of method declaration.
Syntax:
def methodname(self):
return self. __variable

E.g.:
class Std:
def __init__(self,name, regno, marks):
self.name=name
self._regno=regno
self.__marks=marks
def dis(self):
print(self.name, self._regno, self.__marks)
def setter(self, marks):
Std.__marks=marks
def get(self):
return Std.__marks
s1=Std('kavya', 123, 60)
s1.setter(60)
print(s1.name, s1._regno, s1.get())

DATA MANGLING or NAME MANGALING


These are used to access private members outside the class and also to access the class
attributes that does not have any sub classes and it is represented by a prefix with single
underscore for the class name and followed by the private variable or method.
E.g.:
class Ex:
def __init__(self):
self.__x=10
ob=Ex()
print(ob._Ex__x)

02/08/2024

ABSTRACTION
Abstraction is the process of hiding the implementation and showcasing only the
functionality.
In python, to achieve abstraction we need to import abstract method and abstract base class

ABTRACT METHOD
Whenever we don’t know the implementation but still, we can declare a method such type of
methods is called as abstract method.
Abstract method is only declaration but there is no implementation.
In python we can declare abstract method by using the decorator @abstractmethod
If you want to use abstract method first, we have to import abstract method from abc module
E.g.:
from abc import *
class Vehicle:
@abstractmethod
def method(self):
pass
ob=Vehicle()

ABSTRACT CLASS
Whenever the implementation of a class is not complete, such type of partially implemented
class is called as abstract class.
Every abstract class in python should be a child of ABC class
E.g.:
from abc import *
class Vehicle(ABC):
def method(self):
pass
ob=Vehicle()

NOTE:
1. The advantages of declaring abstract method in parent class is that we can provide the
guidelines to the child class such that which method should be compulsorily have
their implementation.
2. If a class contains only abstract method, then creation of object is possible for that
particular class (It should not be abstract class).
E.g.:
from abc import *
class Vehicle:
@abstractmethod
def method(self):
pass
ob=Vehicle()

3. We can create an object if the class is abstract class but it should not contain abstract
method.
E.g.:
from abc import *
class Vehicle (ABC):
def method(self):
pass
ob=Vehicle()

4. If a class contains at least one abstract method then if we extend and ABC class then
creation of instance is not possible (Instantiation is not possible).
E.g.:
from abc import *
class Vehicle (ABC):
@abstractmethod
def method(self):
pass
ob=Vehicle() → error → can’t instantiate abstract class without an implementation for
abstract method.
5. If we are creating a child class of abstract of class then for every abstract method of
parent class, compulsorily, we have to provide implementation in the child class.
E.g.:
from abc import *
class Vehicle(ABC):
@abstractmethod
def noofwheels(self):
pass
class Bus(Vehicle):
def noofwheels(self):
return 6
h1=Bus()
print(h1.noofwheels()) → 6

6. If we don’t provide implementation for abstract method in the child class then child
class will also become abstract and we can’t create an object for the child class also.
E.g.:
from abc import *
class Vehicle(ABC):
@abstractmethod
def noofwheels(self):
pass
class Bus(Vehicle)
pass
h1=Bus()
print(h1.noofwheels()) → error → can’t instantiate abstract class without implementation of
abstract method

7. If a class contains multiple abstract methods, then for all the abstract method child is
responsible for the implementation.
E.g.:
from abc import *
class Vehicle(ABC):
@abstractmethod
def noofwheels(self):
pass
@abstractmethod
def method(self):
pass
class Bus(Vehicle):
def noofwheels(self):
return 6
def method(self):
return 0
h1=Bus()
print(h1.noofwheels()) → 6
print(h1.method()) → 0

8. If a class contains abstract method and non-abstract method then the child is
responsible to create an implementation for only the abstract method.
E.g.:
from abc import *
class Vehicle(ABC):
@abstractmethod
def noofwheels(self):
pass
def method(self):
pass
class Bus(Vehicle):
def noofwheels(self):
return 6
h1=Bus()
print(h1.noofwheels()) → 6

INTERFACE
If an abstract class contains only abstract methods such type of abstract class we can call as
interface.
Interface acts as a service requirement specification (SRS) if we don’t know anything about
implementation and we just have requirement specification then we should go for interface.
E.g.:
from abc import *
class Vehicle(ABC):
@abstractmethod
def noofwheels(self):
pass
@abstractmethod
def method(self):
pass
@abstractmethod
def m1(self):
pass

Important questions
Introduction (theory)
• Keywords
• Variable declaration initialization
• Immutable and mutable
• List and tuple
• Slicing
Control statements
• For and while difference
• Programming MCQ’s
Functions (programs)
• Palindrome
• Armstrong no
• Prime in range
• Bubble sort
• Fibonacci using recursion or generator
• First max and second max
• First min and second min
• Strong no
• Neon
• Swapping with 3rd variable and without 3rd variable
String
All programs

• Def
• Execution flow
• Lambda
• Reduce, filter, map
• Type of arguments
• scope of variables

OOPS (theory)
4 pillers

08/08/2024

Questions
WAPP to create a class called person with name dob and country and implement a method to
calculate the age.
WAPP to create a class called shopping cart which includes methods for adding and removing
items and calculate the total price.
Create a class called calculator with methods of adding subtracting multiply and divide.
WAPP to create a class which represents circle which includes methods to calculate the area
and perimeter.

WAPP to create a class called bank which includes methods for managing customer account
and transactions.
09/08/2024
MODULES
A group of or a collection of variables functions and classes are saved as one file, that file is
called as modules.
Modules helps in reusing the code instead of writing the same code in different files. Modules
makes the program more readability. To use code from one module to another module we can
make use of import or from keyword. We can import the module in the following ways.
1. Import modulename
2. Import modulename as aliasname
3. From modulename import functionname
4. From modulename import *
There are different types of modules
1. User defined module
2. Built-in modules
USER DEFINED MODULES
These are the modules created by users in order to reuse the code.
E.g.: cal.py file
a=100
b=200
def add(x,y):
print(x+y)
print('performing addition')
def sub(x,y):
print(x-y)
print('performing subtraction')
def mul(x,y):
print(x*y)
print('performing multiplication')

Importing into another file in 4 ways


1. Import modulename
import cal
cal.add(3,6)
cal.sub(4,1)
cal.mul(3,2)

2. Import modulename as aliasname


import cal as c
c.add(3,6)
c.sub(4,1)
c.mul(3,2)

3. From modulename import functioname


from cal import mul
mul(3,2)
add(3,4) → error

4. From modulename import *


from cal import *
add(3,6)
sub(4,1)
mul(3,2)

10/08/2024
BUILT-IN MODULES
These are the modules which are already present in python libraries, we need not create a
code manually just we can import and we can use the module.
The different types of built in modules are
Math module, Random module, OS module, Time module, Operator module, etc…

MATH MODULE
Math module is used to perform mathematical operations like number functions
representation function, power and log arithmetic function, trigonometric functions, etc…
constants are pi, nan, inf, tau.
From math import *
Print(ceil(35.2)) → gives succeeding value
Print(floor(23.5)) → preceding value
Trunc →it gives preceding value of an integer

Power functions
Print(sqrt(4)) → 2.0
Print(cbrt(8)) →2.0
Print(pow(4,2)) → 16.0
Print(exp(2)) → 7.431
Print(cos(45))
Print(sin(30))
RANDOM MODULE
This module is used to generate a random value.
1. random (): Using this function, we can generate floating values within a range of 0
and 1. It will not include 0 and 1. Directory to check the modules present we can use
print(dir(random))
from random import *
print(random()) → 0.345 → 0.231
for i in range(4):
print(random()) → prints 4 floating values each time

2. randint(): using this function we can generate integer values for this function we have
to pass 2 arguments and it includes the given range while displaying the output.
from random import *
print(randint(2,8))
for i in range(4):
print(randint(0,9),end='') → 2432 → 7281 → 8572 → 0319 → 9352

3. randrange(): generates integer values in a given range.


from random import *
for i in range (4):
print(randrange(1,8))
print(randrange(1,10,3)) → 3 is step

4. uniform(): using this function it generates a floating value in a given range.


from random import *
for i in range (4):
print(uniform(1,5)) → 4.61843276 → 2.2423567

5. choice(): this function generates random elements from a given sequence.


from random import *
li=['a','r','v','g','e']
for i in range(3):
print(choice(li)) → r v g → e a r → g g r

OS MODULE
Provides a function for communicating with the operating system.
1. getcwd(): to know the current working directory. Displays the path of the current
directory. (cwd – current working path).
E.g.: print(getcwd())
2. mkdir(): using this function we can create only one directory at a time.
E.g.: mkdir('newmodule')
3. makedirs(): using this function we can create multiple directories at a time
E.g.: makedirs('new/n1')
4. rmdir(): using this function we can remove a single directory at a time. Whenever we
use this function for the multiple directories then it will remove only a single directory
which is created latest.
E.g.: 1→ rmdir('newmodule')
E.g.: 2→ rmdir('new/n1') → removes only n1 directories
5. removedirs(): using this function we can remove multiple directories at a time.
E.g.: removedirs('new/n1')
6. rename(): using this function we can change the directory name and for this function
we need to pass 2 arguments arg1 is old directory name arg2 is new directory name.
E.g.: rename(‘newmodule’ , ‘nm’)
7. system(): to run other programs from the current program we use system function.
E.g.: system (‘notepad’)

12/08/2024
TIME MODULE
Time module provides a function to perform time related operations such as to display the
current time or current year or sleep for a specified no of seconds.
E.g.:
from time import *
print(localtime())

hr=localtime().tm_hour
min=localtime().tm_min
sec=localtime().tm_sec
print(f'{hr}:{min}:{sec}')

Sleep(): this function is used to delay the execution of the current program for the given
number of seconds.
E.g.:
print('before sleep')
sleep(10) → 10 seconds delay
print('after sleep')

OPERATOR MODULE
E.g.:
from operator import *
print(add(10,3))
print(sub(5,2))
print(mul(3,6))
print(mod(20,2))
print(divmod(10,2))
print(floordiv(20,4))
print(pow(2,3))

FILE HANDLING
File: file is a storage medium which is used to store a small amount of data.
File handling: it is the process of performing operations on the files such as reading, writing
and append.
We can perform file handling for 3 different files
1. text file
2. CSV file → comma separated values
3. Binary file
TEXT FILE: in text files data is stored in the form of ASCII or Unicode. Each character
occupies one byte of space.
E.g.: a=’123abc _@’ → will occupy 9 bite of space.
It is readable and understandable by users.
To perform any file handling operations on a text file, we have to follow 3 steps.
1. Open the file
2. Perform some operations
3. Close the file
OPEN (): whenever the user wants to read or write to a file we need to open the file first
hence, we are using open function to open the file.
Syntax: var=open(‘filename/path’ , mode)
E.g.: F=open(‘x.py’,’r’)
Filename: it is used to specify which file to be opened.
Mode: it specifies whether user wants to read or write or append the file.

FILE HANDLE:
var=open(‘filename/path’ , mode)
Here variable holds the reference of the file opened
All operations are performed through the variable. Variable is also called file object.
It is just an identifier and it can be name as required
CLOSE FILE
Var.close()
Close(): this function pushes all the changes to the file once we close the file we can’t
perform any operations for the closed file.
If we don’t close the file system resource will be wasted and sometimes, we may get error
E.g.:
f=open(‘ex.py’,’r’)
print(f.read())
f.close()

MODES
1. Read → r, r+
2. Write → w, w+
3. Append → a, a+
Read mode (r, r+): using this mode user can only read the data present in the existing file. If
the user tried to read from the file which does not exists then it will throw the error as
FileNotFoundError. the different operations we can perform in the read mode are
1. read(): it will read entire data present in the given file.
2. readline(): this function by default it will always read the first line of the file.
3. readlines(): it will read the entire data line by line and it should be present in the form
of list.
4. readlines()[]: it will read particular line from the given file.
s=open('modules\cal.py', 'r')
print(s.read())
print(s.readline())
print(s.readline(3))
print(s.readlines())
print(s.readlines()[5])
print(s.readable())
s.close()
print(s.closed)

13/08/2024

1. WAP to count the number of characters in a text file


2. WAP to count the lines in a given text file.
3. WAP to count the words in a given text file.
4. WAP to count the alphabets, digits, spaces and special character in a given file.
5. WAP to count the alphabets, digits, spaces and special character in a given line.
6. WAP to count the vowels and consonants in a given text file.
7. WAP to count the vowels and consonants in each line of a given text file.
8. WAP to count words containing vowels in a file

14/08/2024
Write mode (w): Using this mode user can write the data for the specified file. This mode
overrides the existing data present in the given file. If the specified file doesn’t exist then it
will create the file and then write the data.
Syntax: var= open(‘filename’,’w’)
E.g.:
a= open(‘x.py’,’w’)
a.write(‘tomorrow is no holiday’)
a.close()

Append mode (a): Using this mode data will be added at the last. Append will not override
the data in the given file. If the file does not exist then the data will be appended.
Syntax: var= open(‘filename’,’a’)
E.g.:
a= open(‘x.py’,’a’)
a.write(‘tomorrow is no holiday’)
a.close()

Exclusive mode (x): it will create a new file and write the data for newly existing file. If we
try to write the data for the existing file it will always throw an error called FileExistsError.
Syntax: var= open(‘newfilename’,’x’)
E.g.:
a= open(‘z.py’,’x’)
a.write(‘tomorrow is no holiday’)
a.close()

r+ mode: using this mode we can read the file and write the data into the file. Reading and
writing both the operations can be performed only for existing file.
Syntax: var= open(‘filename’,’r+’)
E.g.:
a= open(‘x.py’,’r+’)
a.read()
a.write(‘tomorrow is no holiday’)
a.close()
w+ mode: using this mode user can write and read the file. In this mode the data present in
the file will be overridden by the new data then we can read the data. w+ mode can be used
for both existing file and not existing file.
Syntax: var= open(‘filename/newname’,’w+’)
E.g.:
a= open(‘x.py’,’w+’)
a.read()
a.write(‘tomorrow is no holiday’)
a.close()

a+ mode: this mode is used to append the data and read the data. In this type of more data
will not be overridden and it will append the data with the previous data.
Syntax: var= open(‘filename/newname’,’a+’)
E.g.:
a= open(‘x.py’,’a+’)
a.read()
a.write(‘tomorrow is no holiday’)
a.close()

The various properties of the file object are


1. Var.mode: Using this we can check the mode of the specified file. → print(a.mode)
2. Readable(): using this function user can check whether the given file is readable or
not. We get output in the form of Boolean expression i.e., true or false
E.g.:
a= open(‘x.py’,’r+’)
a.read()
print(a.readable())
a.close()

3. Writable(): using this function we can check whether the file is writable or not. If the
file is writable it will give the output as true or else false.
4. Closed: in order to check whether the file is closed or not we use ‘closed’. If the file is
closed it will give the output as true or else false.
E.g.:
a=open(‘x.py’,’r+’)
a.read()
print(a.closed) → false
a.close()
print(a.closed) → true
5. with(): this function works with open () to open the file and this function will close
the file automatically once we come out of the with block.
Syntax:
with open (‘filename’, ‘mode’) as aliasname:
--
--

6. tell(): this function is used to know the current position of the curser. → var.tell()
7. seek(): used to change the position of the curser to the specific position. →var.tell(arg)
E.g.:
with open ('text.py', 'w') as p:
p.write('hi hello')
print('beforeseek curser position is at: ', p.tell())
p.seek(5)
p.write('happy')
print('afterseek curser position is at: ', p.tell())
print(p.closed) → false
print(p.closed) → true

15/08/2024
CSV FILES (Comma separated values)
CSV is a way to store the data in a tabular format which can be used for spread sheets and
data bases. To represent the csv file we should declare a file with ( .csv) extension.
In order to perform file handling operations. First, we need to import a module called csv
module. This module includes various methods to perform different operations.
import csv
WRITING TO CSV FILES
The csv modules provides a function called csv.writer() to write to csv file.
Syntax:
import csv
with open (‘filename.csv’,’w’) as f:
csv.writer(f)

READING A CSV FILE


The csv module provides a function csv.reader() to read a csv file.
Syntax:
import csv
with open (‘filename.csv’,’r’) as f:
csv.reader(f)
E.g.: write a employees data using csv file.
import csv
with open('emp1.csv', 'w', newline='') as f:
w=csv.writer(f)
w.writerow(['eno', 'ename', 'sal', 'dno'])
num=int(input('enter the number of employees: '))
for i in range(num):
eno=int(input('enter the emp number: '))
ename=input('enter the name of the emp: ')
sal=int(input('enter the sal of employee: '))
dno=int(input('enter the deptno of employee: '))
w.writerow([eno, ename, sal, dno])
print('successful')

E.g.: reading employees data using a csv file


import csv
with open('emp1.csv','r') as f:
s=list(csv.reader(f))
for i in s:
for j in i:
print(j,end=' ')
print()

BINARY FILES
These are the type of files which stores the information in the format in which the
information is present in the memory.
E.g.: images, compiled file and videos
In order to handle these binary files, we should follow 3 steps
1. open the file
2. perform the operation
3. close the file

Open the file: in order to perform any operation first we have to open the file.
Syntax: var=open(‘filename.dat’,mode)
Syntax: with open (‘filename.dat’,mode) as aliasname:
The different modes in binary files are rb, wb, ab, r+b, w+b, a+b
If you want to perform file handling operations in python then we have to import a module
called pickle.
PICKLE IN PYTHON
Pickle is used to perform read and write operations for python objects into a file.
In pickle we have different types of functions like dump() and load().
dump(): this function is used to write an object to binary file.
Syntax: pickle.dump(‘pythonobject’, ‘filename’)
This function converts python object to binary or machine-readable object.
load(): this function converts machine readable format to human readable form and using this
function we can read an object from the file.
Syntax: pickle.load(‘filename’)
E.g.:
import pickle
li=[1,2,4,5,'a','b']
x=open('abc.dat','wb')
pickle.dump(li,x)
x.close()

E.g.:
import pickle
x=open('abc.dat','rb')
print(pickle.load(x))
x.close()

16/08/2024

EXCEPTION HANDLING
In python there are 2 types of errors
1. syntax error
2. runtime error
SYNTAX ERROR
The error occurs because of invalid syntax such type of errors are considered as syntax error.
Programmer is responsible to correct this type of syntax errors. Once all the syntax errors are
corrected then only program execution will start.
E.g.:
A=10
B=20
If a>b
Prin(‘a’)
Else:
Prit b → syntax error

RUNTIME ERROR
These are called as exceptions. While executing the program at runtime if something goes
wrong because of end user input, memory problems, etc… then we can call it as runtime
error.
Exception handling is applicable only for run time error but not for syntax error.
EXCEPTION
An unwanted and an unexpected event that disturbs the normal flow of a program is called as
exception.
E.g.: Zero division error, Filenotfound error, Type error, File exists error, Value error, etc…
EXCEPTION HANDLING
Defining an alternate way to continue the rest of the program normally is called as exception
handling.
Exception handling doesn’t mean the repairing or correcting of an exception rather finding an
alternative way.
The main objective of exception handling is providing a graceful termination of an
application i.e., it should not block the code so that user doesn’t miss out on anything. It is
highly recommended to handle the exceptions.
PYTHON EXCEPTION HIERARCHY
All exceptions in python are a class and all exception classes or child class of base exception
either directly or indirectly. Hence, base exception class is the root of python exception
hierarchy.

Base exception

Exception System exit Generator exit Keyboard interrupt

Attribute error Arithmetic Name Lookup OS Type Value


error error error error error
Zero division Index Filenotfound
error error error

Floating point Key Interrupt


error error error

Overflow Permission
error error

Timeout error

In python we can handle the exceptions in 2 ways.


1. Default exception handling
2. Customized exception handling
DEFAULT EXCEPTION HANDLING
Every exception in python is an object for every exception type the corresponding class is
available. Whenever an exception occurs python virtual machine will create the
corresponding exception object and it will search for handling code.
If handling code is available then it will execute and the rest of the code will be executed
normally.
If handling code is not available then pvm will terminate the program abnormally and print
the corresponding exception information and rest of the code will not execute. To prevent the
abnormal termination, we should handle the exception explicitly by using try and except
blocks.
CONTROL FLOW IN TRY EXCEPT BLOCKS
Within a try block if anywhere an exception is raised then rest of the try block will not
execute. Even though the user handled the exception. Else inside the try bock we have to take
only the risky code and length of the try block should be less as much as possible.
In addition to try block there may be chance of raising exception inside except block and
finally block.
If any statement which is not a part of try block, then it is raising an exception, then it will
always terminate abnormally.
E.g.: 1
Try:
Print(‘statement1 from try block’)
Print(‘statement2 from try block’)
Except:
Print(‘from except block’)
Print(‘outside try except block’)

Output:
Statement1 from try block
Statement2 from try block
Outside try except block

E.g.: 2
Try:
Print(‘statement1 from try block’)
Print(10/0)
Print(‘statement2 from try block’)
Except:
Print(‘from except block’)
Print(‘outside try except block’)

Output:
Statement1 from try block
From except block
Outside try except block

E.g.: 3
Try:
Print(‘statement1 from try block’)
Print(10/0)
Print(‘statement2 from try block’)
Except ZeroDivisionError as msg:
Print(‘from except block’, type(msg)
Print(‘outside try except block’)

Output:
Statement1 from try block
From except block <class ZeroDivisionError>
Outside try except block

E.g.: 4
Try:
Print(‘statement1 from try block’)
Print(10/0)
Print(‘statement2 from try block’)
Except ValueError as msg:
Print(‘from except block’, type(msg)
Print(‘outside try except block’)

Output:
Error → ZeroDivisionError → 10/0
TRY WITH MULTIPLE EXCEPT BLOCK
The way of handling an exception varies from exception to exception. Hence, for every
possible exception type we can take separate except block. Try with multiple except block is
also possible.
Syntax:
Try:
--
--
Except exception handler1:
--
--
Except exception handler2:
--
--

E.g.:
Try:
a=int(input(‘enter a: ‘)
b=int(input(‘enter b: ‘)
Print(a/b)
Print(‘hi’)
Except ZeroDivisionError as msg:
Print(‘from except block’, type(msg)
Except ValueError as v:
Print(‘from except block’, type(v)
Print(‘outside try except block’)

Output: 1
If a=10 and b=5
2
Hi
Outside try except block

Output: 2
If a=10 and b=0
From except block <class ZeroDivisionError>
Outside try except block

Output: 3
If a=10 and b=abd
From except block <class ValueError>
Outside try except block
19/08/2024
If try with multiple except block is available order of this except block is important.
The PVM always considers from first to last until matched exception is identified.

SINGLE EXCEPT BLOCK CAN HANDLE MULTIPLE DIFFERENT EXCEPTIONS.


E.g.:
try:
a=int(input('enter a: '))
b=int(input('enter b: '))
print(a/b)
except (ZeroDivisionError, ValueError) as msg:
print('from except block', type(msg))

Whenever we pass multiple exception handlers then all the exception handlers should be
present within a parenthesis. If handling code is same for multiple exception then instead of
taking different except blocks, we can take single except block that can handle all those
exceptions.
DEFAULT EXCEPT BLOCK
We can use default except block to handle any type of exceptions. If default block is defined
then compulsorily it must be at the last. Otherwise, we will get syntax error.
E.g.:
try:
a=int(input('enter a: '))
b=int(input('enter b: '))
print(a/b)
except ZeroDivisionError as msg:
print('from except block', type(msg))
except:
print('from default except block')

E.g.:
try:
a=int(input('enter a: '))
b=int(input('enter b: '))
print(a/b)
except:
print('from default except block')
except ZeroDivisionError as msg:
print('from except block', type(msg))
Output: Syntax error

E.g.: with base exception


try:
a=int(input('enter a: '))
b=int(input('enter b: '))
print(a/b)
except BaseException:
print('from base exception') → this will execute
except ZeroDivisionError as msg:
print('from except block', type(msg))
except ValueError:
print('from except block', type(ValueError))
print('outside try except block'
20/08/2024
Various possible combinations of except block.
1. except ZeroDivisionError:
2. except (ZeroDivisionError):
3. except ZeroDivisionError as z:
4. except (ZeroDivisionError) as z:
5. except (ZeroDivisionError, ValueError):
6. except (ZeroDivisionError, ValueError) as zv:
Invalid declarations of except block.
1. except (ZeroDivisionError as z):
2. except ZeroDivisionError, ValueError:
3. except (ZeroDivisionError, ValueError as zv):

FINALLY BLOCK
It is not recommended to place a clean-up code inside the try block because there is no
guaranty for execution of every statement inside the try block. It is not recommended to place
a clean up code inside the except block because if there is no exception then except block will
not be executed.
Finally block will be executed no matter if the try block raises an exception or not and this
will be useful to close the objects and to clean up the resources.
Syntax:
Try:
--
--
Except:
--
--
Finally:
--
--
E.g.: 1
try:
print(‘try’)
except:
print(‘except’)
finally:
print(‘finally’)
output:
try
finally

E.g.: 2
try:
print(‘try’)
print(10/0)
except:
print(‘except’)
finally:
print(‘finally’)
output:
try
except
finally
E.g.: 3
try:
print(‘try’)
print(ten/1)
except ZeroDivisionError:
print(‘except’)
finally:
print(‘finally’)
output:
try
finally
error

USER DEFINED OR CUSTOMIZED EXCEPTION


Whenever user defined and raise an exception explicitly to indicate that something went
wrong such type of exceptions are called as user defined exceptions. In this exceptions PVM
is not responsible for the any kind of exceptions. In python we can define a customized
exception by creating a new class which is derived from the built in exception class.
Syntax:
class Classname(Exception):
pass
try:
--
--
except Classname:
--
--

raise is the key word which is used to raise the exception explicitly based on used
requirement.
E.g.: 1
class InvalidAge(Exception):
pass
num=18
try:
age=int(input('enter the age: '))
if age<num:
raise InvalidAge
else:
print('elegible to vote')
except InvalidAge:
print('exception occured: not elegible to vote')

E.g.: 2
class BalanceException(Exception):
pass
def checkbalance():
money=10000
withdraw=int(input('enter the amount to withdraw'))
try:
balance=money-withdraw
if balance<=1500:
raise BalanceException
print(balance)
except BalanceException:
print('insufficient balance')
checkbalance()

21/08/2024
ASSERTION
Used to evaluate an expression or to check the condition. To perform assertion, we can make
use of the keyword assert. Assertion checks the condition. If the condition is true then it will
print the specified output. If the condition is false then it will throw an error called
AssertionError.
E.g.: 1
def avg(score):
assert score!=0, 'list is empty'
return sum(score)/len(score)
s1=[]
print('the avg is: ', avg(s1)) → list is empty

E.g.: 2
def avg(score):
assert score!=0, 'list is empty'
return sum(score)/len(score)
s2=[3,5,1,3]
print('the avg is: ', avg(s2))
s1=[]
print('the avg is: ', avg(s1))

E.g.: 3
try:
n=5
assert n%2==0, 'it is not a even number'
print('even number')
except Exception as e:
print('error',e)

DECORATORS
Decorators are the functions that takes another function as an argument and extends the
functionality without modifying the existing code.
We can represent the decorators by using a special character @.
We should always write the additional functionality code before the original code. Between
the original code and additional functionality code we can use @ decoratorname.
E.g.: original code
def division(t,s):
return t/s
print(division(10,2)) → 5.0
print(division(6,2)) → 3.0
print(division(10,0)) → ZeroDivisionError

E.g.: with the additional functionality


def decor(func):
def inner(c,a):
if a==0:
print('denominator value cant be 0')
else:
return c/a
return inner
@decor
def division(t,s):
return t/s
print(division(10,2))
print(division(6,2))
print(division(10,0))

DECORATOR CHAINING
Applying more than one decorator within a function is called as decorator chaining. In this
execution flow starts from top to bottom.
E.g.:
def decor1(func):
def inner(name):
print('from decor1')
func(name)
return inner
def decor2(func):
def inner(name):
print('from decor2')
func(name)
return inner
@decor1
@decor2
def exp(name):
print('hi', name)
exp('Vasu')

COMPREHENSION
Comprehension is the process of creating a new sequence from the existing sequence.
The different types of comprehensions are
1. list comprehension
2. set comprehension
3. dictionary comprehension
4. generator comprehension
It is an easy way of creating an object sequence by applying expression or condition.
List comprehension: creating a new list from an existing list is called as list comprehension.
Syntax: v=[var for var in sequence] or [var for var in sequence condition]

E.g.: 1
l=[3,2,1,6,4]
li=[i*i for i in l]
print(li)
Each time variable i will read one value from the sequence after reading the value it will
apply an expression (i*i) after that it will store the result in the form of list.
E.g.: 2
l=[3,2,1,6,4]
li=[i for i in l if i%2==0]
print(li)

Dictionary comprehension: creating a new dictionary sequence from an existing sequence.


Syntax: v={key: value for var in sequence}
E.g.: 1
dct=[2,4,1,5,3]
d={i: i*i for i in dct}
print(d)

E.g.: 2
dct=[5,4,3,2,1]
di=[1,2,3,4,5]
d={i: j for i, j in zip(dct, di)}
print(d)
In python zip() is used to create a dictionary by combining 2 sequences.
Set comprehension: creating a new set from an existing sequence.
E.g.:
s=[1,2,3,4]
si={i+5 for i in s}
print(si)

Generator comprehension: it is a one-line specification for defining a generator whenever


we use this comprehension it will generate an object and create an address for the particular
object.
E.g.:
g=[1,2,3,4,5]
t=(s-1 for s in g)
print(list(t))
print(tuple(t))
print(type(t))

22/08/2024
GENERATORS
Functions which generate the value in a sequence. Generator functions return a generator
object which acts as an iterator.
To represent generator, we can make use of keyword yield. We can define a generator
function using the def keyword but instead of return statement we can make use of yield
statement. Yield keyword is used to produce a value from the generator. When the generator
function is called it doesn’t execute the function body immediately instead it returns a
generator object that can be iterated over to produce the values.
E.g.:
def gen():
yield 'a'
yield 'b'
yield 'c'
g=gen()
print(next(g))
print(next(g))
print(next(g))

print(next(g)) → StopIterationError

Advantages of using generators in python


• Python generators are more efficient than loops for large data sets as they produce
values one after the other instead of storing them in memory before returning the
output.
• As generator produce the values one by one rather than storing them in list or other
data structures, they also require less memory and can process large database where
without using ram.
• Using generators is time saving as they do not need to wait for the entire sequence to
be generated before returning them.

WAP to generate first 5 natural numbers.


def fst():
for i in range(1,6):
yield i
s=fst()
for j in range(5):
print(next(s))
or
def fst():
s=1
while s<6:
yield s
s+=1
s=fst()
for i in range(5):
print(next(s))

WAP to start count down with a delay


from time import *
def cnt():
n=5
while n>=0:
yield n
n-=1
s=cnt()
for i in range(6):
print(next(s))
sleep(1)
or
from time import *
def cnt(n):
while n>0:
yield n
n-=1
s=cnt(5)
for i in s:
print(i)
sleep(1)

WAP to generate a Fibonacci series of 5

ITERATOR
Iterator is an object that contains countable number of values. An iterator is used to iterate
over an iterable objects like list tuple or sets. Iterator objects which implements an iterator
protocols which consists of a magic methods like __iter__ and __next__.
An iterator is commonly used to loop through the objects of a sequence. Iterator will be faster
and have better memory efficiency.
__iter__(): it returns the iterator object itself. And if required it also performs some
initialization.
__next__(): it returns the next item in the sequence on reaching the end and insubsequent
calls it must raise a StopIteration.
E.g.:
l=[1,2,3,4,5]
v=iter(l)
p1=next(v)
print(p1) → 1
p2=next(v)
print(p2) → 2
p3=next(v)
print(p3) → 3
p4=next(v)
print(p4) → 4
p5=next(v)
print(p5) → 5
p6=next(v)
print(p6) → StopIteration
or
l=[1,2,3,4,5]
v=l.__iter__()
p=v.__next__()
print(p)

RECURSION
Process of calling the function itself. Such functions are called as recursive functions. To
perform recursion, we have to use base case and recursive case.
Base case: base case is the condition to stop the recursion.
Recursive case: this is also called as general case. The case in recursive definition in which
method is calling itself. Whenever the programmer doesn’t provide the base case then it will
print the output as Recursion error.
E.g.:
def wish():
print(‘hi’)
wish() → recursion error
wish()

1. WAP to find the factorial of the given number using recursion.


def fact(n):
if n==0 or n==1:
return n
else:
return n*fact(n-1)
print(fact(5))

2. WAP to find Fibonacci series of sequence 5.


def fib(num):
if num<=1:
return num
else:
return fib(num-1)+fib(num-2)
for i in range(6):
print(fib(i),end=' ') → 0, 1, 1, 2, 3, 5

Explanation:
Iteration 1: i = 0
fibonacci(0) is called.
Since 0 <= 1, it returns 0.
Output: 0

Iteration 2: i = 1
fibonacci(1) is called.
Since 1 <= 1, it returns 1.
Output: 1

Iteration 3: i = 2
fibonacci(2) is called.
The else clause is executed because 2 > 1.
It returns fibonacci(1) + fibonacci(0).
fibonacci(1) is called and returns 1 (since 1 <= 1).
fibonacci(0) is called and returns 0 (since 0 <= 1).
Result: 1 + 0 = 1
Output: 1

Iteration 4: i = 3
fibonacci(3) is called.
The else clause is executed because 3 > 1.
It returns fibonacci(2) + fibonacci(1).
fibonacci(2) is called.
It returns fibonacci(1) + fibonacci(0).
fibonacci(1) is called and returns 1.
fibonacci(0) is called and returns 0.
Result: 1 + 0 = 1
fibonacci(1) is called and returns 1.
Result: 1 + 1 = 2
Output: 2

Iteration 5: i = 4
fibonacci(4) is called.
The else clause is executed because 4 > 1.
It returns fibonacci(3) + fibonacci(2).
fibonacci(3) is called.
It returns fibonacci(2) + fibonacci(1).
fibonacci(2) is called.
It returns fibonacci(1) + fibonacci(0).
fibonacci(1) is called and returns 1.
fibonacci(0) is called and returns 0.
Result: 1 + 0 = 1
fibonacci(1) is called and returns 1.
Result: 1 + 1 = 2
fibonacci(2) is called.
It returns fibonacci(1) + fibonacci(0).
fibonacci(1) is called and returns 1.
fibonacci(0) is called and returns 0.
Result: 1 + 0 = 1
Result: 2 + 1 = 3
Output: 3
Final Output:
The outputs from the loop are: 0, 1, 1, 2, 3.

23/08/2024
3. WAP to print python for 3 times using recursion.
def txt(n):
if n>0:
print('python')
txt(n-1)
txt(3)

4. WAP to print 5 to 1 in reverse order using recursion.


def revers(s):
if s==0:
return 0
else:
print(s)
revers(s-1)
revers(5)

5. WAP to count the number of digits using recursion.


def cnt(n):
if n==0:
return 0
else:
return 1+cnt(n//10)
print(cnt(3345))

6. WAP to generate only the string with odd length in the given list. [dog, cat, lion, goat,
rat, tiger] using generator.
l=['dog', 'cat','lion', 'rat', 'tiger']
def odd(l):
for i in l:
if len(i)%2==1:
yield i
for j in odd(l):
print(j)

7. WAP to fetch prime number from 1 to 20 using filter


def prime(n):
if n>1:
for i in range(2, n):
if n%i==0:
break
else:
return 'num is prime'
l=list(range(1,20))
print(list(filter(prime,l)))

You might also like