0% found this document useful (0 votes)
40 views159 pages

Notes Pythom Anits Mech r20 Sllbus by Phani

Uploaded by

tulasisatya108
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views159 pages

Notes Pythom Anits Mech r20 Sllbus by Phani

Uploaded by

tulasisatya108
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 159

Feature: 4: Python is Cross Pla orm Programming Language:

Pla orm = Opera ng System


An applica on is running on Windows Pla orm
An applica on is running on UNIX pla orm
An applica on is running on LINUX Pla orm
An applica on is running on Android pla orm
An applica on is running on MAC-OS
Cross pla orm = Mul ple pla orms (or) mul ple opera ng systems.
Python programming language can run on all mul ple pla orms.
Feature: 5: Python is Open-sourced Programming Language and it is
Free-ware programming language:
What is open-sourced programming language?
Ans: Source-code is open to public or all. So that everyone can u lise
the benefits of programming language.
What is “Free-ware” programming language?
Ans: If anyone is able to download programming language freely then
that programming language is called as “Free-ware” programming
language. So that we need not to pay single rupee for Free-ware
programming languages. Python can be downloaded freely. So, Python
is free ware prog. Lang.
6th Feature: Python is procedure oriendted programming language as
well as object oriented programming language:
What is procedure-oriented programming language?
Ans: (i) Procedure-oriented programming language is a collec on of
procedures or func on.
For Example: Addi on () func on will perform “addi on” opera on.
Subtrac on () func on will perform “Subtrac on” opera on.
In banking applica on, “Transfer funds ()” func on will transfer funds
from your account to another account.
ii) Procedure oriented programming language are used to develop
“Single user applica ons”
iii) Single user applica on: Only one user can operate the applica on
then that applica on is called as single user applica on.
Examples of “Single user applica ons:”
a) Calculator
b) Paint
c) Notepad etc………
With python, we can develop “single user applica ons”
b) Object oriented programming Language:
i) It is used to develop “Mul ple user applica ons”
ii) Mul -user applica on: More than one user can operate the
applica on then that type of applica on is called as “Mul -user
applica on”
iii) Examples of Mul -user applica ons:
a) Facebook
b) Twi er
c) Whatsapp
d) Youtube etc….
So, we can develop mul -user applica ons with python.
7th Feature: Python is modular programming language:
Python Library = collec on of packages
Package = collec on of modules
Module = Collec on of func ons
Func on = Collec on of statements or set of instruc ons.
8th feature: Python is dynamic typed programming language:
i.e., programmer doesn’t need to declare any data type, the data type
will be taken automa cally based on ini alized value. if we ini alize
numerical value it will dynamically take as int.
9th feature: Python is interpreter-based programming language
Compiler based programming Interpreter based programming
language language
In compiler based prog lang, Example: PYTHON
program will get first compile, In case of interpreter-based
once compila on is completed, programming language,
then only it will execute en re interpreter (execu on engine)
program. It means here it will will compile and execute the
divided into two steps: code line by line like below:
1. Compila on: Doing by Python interpreter
compiler. Program
2. Execu on: Is doing by Line1-Compile and execute
execu on engine. Line2-Compile and execute
Example for compiler based prog Line3-compile and execute
lang: C, C++, JAVA, C#
In this process, when we compile Observa on:
a program it will produce
collec on of files, which In this case code is compiling an
consume lot of memory. execu on line by line, due to that
Ex: if we compile ‘c’ program it reason it is not producing any
will produce following files suppor ng files, which will not
(i) .bak (back up file) consume more memory.
(ii) .obj (it will contain
machine understandable
code)
(iii) .exe (It will contains
executable code)

10th Feature: Python is an embedded programming language:


Embedded = integrated/combined/mixed
Python coding can be embedded or mixed with other languages code.
Python+java = Jython
Python+c = Cpython
Python+.net = Iron python
Python + Hadoop = pydoop
Python +spart = pyspark

Installa on:

STEPS TO INSTALL PYTHON SOFTWARE ON OUR SYSTEMS

Step-1: open www.python.org website

Step-2: Select windows op on from Downloads menu

Step-3: Click on Latest Python 3 Release – python 3.11.4

Step-4: Click on windows installer (64-bit)

Step-5: Click on Downloaded file (file name: python-3.11.4-amd64)

Step-6: Click on Add Python 3.11 to PATH

Step-7: Click on install now and click on Yes bu on

Now you will see “Setup was successful”


Keywords or Reserved words:
Python has a set of keywords that are reserved words that cannot be used as
variable names, function names, or any other identifiers:

Keywords Description

This is a logical operator which returns true if both the operands are
and
true else returns false.

This is also a logical operator which returns true if anyone operand


or
is true else returns false.

This is again a logical operator it returns True if the operand is false


not
else returns false.

if This is used to make a conditional statement.

Elif is a condition statement used with an if statement. The elif


elif
statement is executed if the previous conditions were not true.

Else is used with if and elif conditional statements. The else block is
else
executed if the given condition is not true.
Keywords Description

for This is used to create a loop.

while This keyword is used to create a while loop.

break This is used to terminate the loop.

as This is used to create an alternative.

def It helps us to define functions.

lambda It is used to define the anonymous function.

import This is used to import a module.

Identifiers:
Python Identifier is the name we give to identify a variable, function,
class, module or other object. That means whenever we want to give
an entity a name, that's called identifier.
Identifier is a user-defined name given to a variable, function, class,
module, etc.

Variables
A python variable is a symbolic name that is reference or pointer to an
object. Once an object is assigned to a variable, you can refer to the
object by that name. But the data itself is s ll contained within the
object.
The most commonly used methods of construc ng a mul word
variable name are the following three examples.
1. Camel case
Ex:- mightyMechanicalEngineering
2. Pascal case - Iden cal to camel case except the first word is also
capital
Ex:- MightyMechanicalEngineering
3. Snake case – mighty_mechanical_engineering
Comments:
Single line comments
Mul line comments
Indenta on:
 Indenta on means spaces at the beginning of code line.
 Python uses indenta on to indicate a block of code.
 In other languages the indenta on in code is only for readability, the
indenta on in python is very imp.
 Python will give error if you skip the indenta on. No of spaces is upto
programmer. But it should at least one.

Note:
We should use same no of spaces for all lines in same block of code.
No of spaces is user choice. Even one space, it will work
What is Statement in Python
A Python statement is an instruction that the Python interpreter can execute.
There are different types of statements in Python language as Assignment
statements, Conditional statements, Looping statements, etc. The token character
NEWLINE is used to end a statement in Python. It signifies that each line of
a Python script contains a statement. These all help the user to get the required
output.

Types of statements in Python?

The different types of Python statements are listed below:


 Multi-Line Statements
 Python Conditional and Loop Statements
 Python If-else
 Python for loop
 Python while loop
 Python try-except
 Python with statement
 Python Expression statements
 Python pass statement
 Python del statement
 Python return statement
 Python import statement
 Python continue and
 Python break statement
 Statement in Python can be extended to one or more lines using
parentheses (), braces {}, square brackets [], semi-colon (;), and
continuation character slash (\). When the programmer needs to do
long calculations and cannot fit his statements into one line, one can
make use of these characters.
Declared using Continuation Character (\):
s = 1 + 2 + 3 + \
4 + 5 + 6 + \
7 + 8 + 9
Declared using parentheses () :
n = (1 * 2 * 3 + 7 + 8 + 9)
Declared using square brackets [] :
footballer = ['MESSI',
'NEYMAR',
'SUAREZ']
Declared using braces {} :
x = {1 + 2 + 3 + 4 + 5 + 6 +
7 + 8 + 9}
Declared using semicolons(;) :
flag = 2; ropes = 3; pole = 4

Constants:
In Python, constants are usually declared and assigned in a module. Here, the
module is a new file containing variables, func ons etc. which is imported to the
main file.
Inside the module constants are wri en in all CAPITAL_LETTERS and underscores
separa ng the words.
Example:
1. Create a file name as constantmechc.py
2. PI=3.14, GRAVITY=9.81
3. Create a main.py (Program File)
Import constantmechc
print(constantmechc.PI)
print(constantmechc.GRAVITY)
Literals:
Literals means a constant
Generally, literal are a nota on for represen ng a fixed value in source
code. They can also be defined as raw value or data given in variables or
constants.
#Numeric Literals
Here, 20,24.5, 2+3j are considered as literals.
Python has different types of literals
1. String literals
2. Numeric Literals
3. Boolean Literals
4. Literal Collec ons
5. Special literals
6. Complex Literals

DATA Types:

Built-In Types or Data Types implicitly available in python


Complex Data Type:
It is used to represent the complex numbers.
Ex: a+bj
Cn1=1+2j
Cn2=2+3j
Cn=Cn1+Cn2
print(Cn)
o/p= 3+5j
Complex data types will be used in data science applica on.
Type Conversion/Cas ng

1. What is type cas ng?


Ans. Type cas ng a process of conver ng one data type to another
data type.
In Python we have following type cas ng func ons.
int()
float()
str()
bool()
int() : This method will convert given value into integer type.
float() : This method will convert given value into float type.
str() : This method will convert given value into str type.
bool() : This method will convert given value into bool type.
Python Interning: (-5 to 256)
Import Module in Python:
Import in python is similar to #include header_file in C/C++. Python modules can
get access to code from another module by impor ng the file/func on using
import. The import statement is the most common way of invoking the import
machinery, but it is not the only way.
import module_name
When the import is used, it searches for the module ini ally in the local scope
by calling __import__() func on. The value returned by the func on is then
reflected in the output of the ini al code.

For user defined modules refer constants topic, which is already discussed
above.
>>>help(math) to get more details about the math module in python
>>>import sys
>>>sys.path
>>>import from math as mt
>>>mt.pi
Operators: Operator is used to perform opera ons on data
Types of operators:
Arithme c operators,
Comparison operators,
Logical operators,
Bitwise operators,
Assignment operators,
Iden ty operators,
Membership operators

Assignment Operator:

Arithme c operators:
It is used to perform the mathema cal opera ons.

+ is for addi on
- is for subtrac on
* is for mul plica on
/ is for division
// floor division
% modula on
Arithme c – Assignment Operators:

+= addi on and assignment #ex: a+=b means a=a+b


-= subtrac on and assignment #ex: a-=b means a=a-b
*= mul plica on and assignment
/= division and assignment
//= floor division and assignment
%= modula on and assignment

Rela onal Operators: Rela onal operator checks a condi on and return
Boolean value. (True/False) < (Less than), > (Greater Than)
10<5
False
5<10
True
Logical Operators: A logical operator checks mul ple condi ons at a me and
return bool value. (True or False)
 ‘and’ logical operator: It will return True, when all the given condi on are
True otherwise it returns False.

 ‘or’ logical operator: It will return True, when at least one condi on is True
within given condi ons. Otherwise, it will return False.

Membership Operator: It is used to check whether given member is exists or


not. If exists it returned true, otherwise it will return false.
In Python we have two membership operators.
 in
 not in
Iden ty Operators: It returns True if mul ple object have same id
(iden ty) otherwise it will return false
 is
 is not

Bitwise operators:
In Python, bitwise operators are used to perform bitwise calculations on
integers. The integers are first converted into binary and then operations are
performed on each bit or corresponding pair of bits, hence the name bitwise
operators. The result is then returned in decimal format.

OPERATOR NAME DESCRIPTION SYNTAX

Bitwise Result bit 1, if both operand bits are 1; otherwise,


& AND results bit 0.
x&y
OPERATOR NAME DESCRIPTION SYNTAX

Bitwise Result bit 1, if any of the operand bit is 1;


| OR otherwise, results bit 0. x|y

Bitwise
~ NOT
inverts individual bits ~x

Bitwise Results bit 1, if any of the operand bit is 1 but not


^ XOR both, otherwise results bit 0. x^y

Example:
a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary)

a & b = 1010
&
0100
= 0000
= 0 (Decimal)
Bitwise or operator Returns 1 if either of the bit is 1 else 0.
Example:
a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary)

a | b = 1010
|
0100
= 1110
= 14 (Decimal)
Name Space and Scope:

What is current role number?


 Used to uniquely iden fy the person
 Two persons cannot have same roll number.
Name Space:
 Unique name for each and every object
 Python also doesn’t have same name for objects (variables, method)
with in a single scope.

What is Scope?
1. Local Scope:
Contains names defined inside the current func on.
2. Global Scope:
Contains names defined at the top level of the script or module
3. Enclosing Scope:
Contains names defined inside any and all enclosed func on.
4. Built-In Scope:
Contains names built in to the python language.
Modifying the global variable in local scope:
We can’t modify global variable inside the local scope:
PYTHON PROGRAMMING

UNIT-II:
Flow control & Collections: If, If...else, if...elif...else,
Nested if, for loop, while loop, Break, Continue and Pass.
Numbers, Decimal, Fractions, Mathematics, List, Tuple,
String, Set and Dictionary. Data types manipulations
(create, Index, Negative indexing, Slicing, change or add
elements, delete or remove elements, Methods,
Comprehension, Membership Test, Iteration, Operations
and Built in Functions)

Learning Outcome: At the end of this Unit the student will be able to
• Implement Flow control statements required real world problems.
• Manipulate python programs by using the python data structures like lists,
dictionaries, tuples, strings and sets.

In the above program when user entered second number as


zero it is throwing run time error… How to handle runtime
errors?
Ans: Two ways
1st way is: By using logic for this, we should go for control
statements
2nd way is: By using exception handling mechanism, with help of by
try, except, finally blocks…
Control Statements:
1. When we use control statements?
Ans: Control statements are used to control the program as per our requirement.
In python we have 3 types of control statements..
1. Conditional Statements
2. Loops
3. Transfer Statements

1. Conditional Statement:
What we can do by using conditional statement?
Ans: Using conditional statements, we can execute single statement or
multiple statements based on the condition.

Types of Conditional Statements:


In Python we have following conditional statements
1. Simple if
2. if else
3. if else if
4. multiple if
5. nested if..
1. Simple if:
<syntax>
if <condition>:
statement-1
statement-2
Example to handle divide by zero error program by using simple if:

2. if else:
<syntax>
if <condition>: #condition True – execute statement-1, skip else
statement-1 #condition False – skip stm-1, exe else stm-2
else:
statement-2
3. if elif
<syntax>
if <condition-1>:
Statement-1 is executed
elif <condition-2>:
Statement-2 is executed
elif <condition-3>:
Statement-3 is executed
else:
Statement-2 is executed

Task1: Write a python program to accept a digit (0-5) display in letters….


Enter your Number: 5
You have entered number is: Five
1. Accept age from the user and display user status
age>=58 - senior citizen
age between 25-57 - working citizen
age between 16-24 - college student
age between 4-15 - school kid
age between 1-3 - playing kid
age other than range - invalid
2. Write a python program to accept alphabets and check it is vowel or not.
3. Write a python program to accept 3 subject marks i.e., calculate totmarks and avgmarks display
result:
Conditions: Fial – if he/she got < 35 in anyone subject
First class - if average >=60
Second class - if avgmarks between 50-59
Third class - if avgmarks between 35-49
What is the role of range() function?
range() function will do 3 responsibilities
1) It will initialize the starting range into given variable
2) It will compare ‘i’ value with ending range like i<6
If it is true it will go for iteration, otherwise it will skip
iteration.
3) After iteration is completed, it will increment the i value
one.
Write a python program to print 1 to 5 numbers like below.
o/p: 1 2 3 4 5
for i in range (1,6)
print (i,end= ‘ ‘)
Conditional statement within for loop:

Implementing if else or simple if or if elif or multiple if or nested if within for loop


is called as conditional statements within for loop.
Write a python program to print 1 to 10 numbers like below.
Out put:

Write a python program to print 1 to 10 numbers like below.


Out put:
Nested loop:
Implementing loop with in loop is called nested loop. That means implementing for loop within
for loop or while loop within while loop or while loop with in for loop or for loop within while
loop is called as nested loop.
Tutorial:

1. Write a python program to display list of even numbers and number of even numbers and sum
of even numbers within given range.
2. Write a python program to check given number is prime number or not.
What is prime number: A number which is divisible by 1 and itself is called as prime number.
3. Write a python program to print list of prime numbers upto given range.
4. Write a python program to print list of prime numbers upto given range in reverse order.
5. Write a python program to print odd numbers upto given range. In reverse order
Write a python program to display prime numbers in the range of 2-100

While loop:
Using while loop we can execute a set of statements as long as a condition.
While loop will execute as per given no of iterations after last iteration else part will execute.
If while loop is terminated by break then else part will not execute.
➢ Using break statement, we can stop the loop even if the while condition is true.
➢ Using continue statement, we can stop the current iteration and continue with the
next.
➢ Using else statement, we can run a block of code once when the condition is no longer
as true.
➢ Pass: Using pass we can pass from one block to another block.
Which we will use in functions.
while <condition>:
#logic
else:
#logic
Sum of even no and odd no program

Write a python program to accept two numbers implement swapping.

Write a python program to accept a string and print in reverse order.


Write a python program to display Fibonacci series … upto given range.
Output: Enter ur no: 10
0112358
Python Lists: are one of the most versatile data types that allow us to
work with multiple elements at once. For example,
Python list is Mutable
In python, a list is created by placing elements inside square brackets [ ]
Access list elements:
There are various ways in which we can access the elements of list.
We can use the index operator [ ] to access an item in a list. In python, indices start at 0. So, a list
having 10 elements will have an index from 0 to 9.
Trying to access indexes other than these will raise an IndexError. The index must be an integer.
We can’t use float or other types, this will result TypeError.
Nested lists are accessed using nested indexing.
Note: When we slice lists, the start index is inclusive but the end index is exclusive. For example,
my_list [2:5] returns a list with element at index 2, 3 and 4, but not 5.
Add/change list elements
Lists are mutable, meaning their elements can be changed unlike string or tuple.
We can use the assignment operator = to change an item or a range of items.
Methods Descriptions
append() Adds an element to the end of the list
extend() Add all elements of a list to another list
insert() Inserts an item at the defined index
remove() Removes an item from the list
pop() Returns and removes an element at the given index
clear() Removes all items from the list.
index() Returns the index of the first matched item
count() Returns the count of the number of items passed as an argument
sort() Sort items in a list in ascending order
reverse() Reverse the order of items in the list
copy() Returns a shallow copy of the list.

The pop() method removes and returns the last item if the index is not provided. This helps us
implement lists as stacks (First in, Last out, FILO data structures). And if we have to empty the
whole list, we can use the clear() method.
Tuple:
A tuple in python is similar to a list. The difference between the two is that we
cannot change the elements of a tuple once it is assigned whereas we can change
the elements of a list.
Creating a tuple: A tuple is created by placing all the items (elements) inside
parentheses ( ), separated by commas. The parentheses are optional; however, it is
a good practice to use them.
A tuple can have any number of items and they may be of different types (integers,
float, list, string, etc.,).

Having one element within parentheses is not enough. We will need a trailing
comma to indicate that it is, in fact, a tuple.
We can also use + operator to combine two tuples. This is called concatenation.
We can also repeat the elements in a tuple for a given number of times using *
operator.
Both + and * operations result in a new tuple.
Advantages of Tuple over list:
Since tuples are quite similar to lists, both of them are used in similar situations.
However, there are certain advantages of implementing a tuple over a list. Below
listed are some of the main advantages.
➢ We generally use tuples for different data types and lists for similar data
types.
➢ Since tuples are immutable, iterating through a tuple is faster than with list.
So there is a slight performance boost.
➢ Tuples that contain immutable elements can be used as a key for a dictionary.
With lists, this is not possible.
➢ If you have data that doesn’t change, implementing it as tuple will guarantee
that it remains write-protected.
Python Dictionary:
Python Dictionary is ordered collection of items. Each item of a dictionary has a
key/value pair.
Dictionaries are optimized to retrieve values when the key is known.
Creating Python Dictionary:
Creating a dictionary is as simple as placing items inside curly braces { } separated
by commas.
An item has a key and a corresponding value that is expressed as a pair (key:value).
While the values can be of any data type and can repeat, keys must be of immutable
type (string, number or tuple with immutable elements) and must be unique.

Changing and adding dictionary elements:


Dictionaries are mutable. We can add new items or change the value of existing
items using an assignment operator.
If the key is already present, then the existing value gets updated. In case the key is
not present, a new (key:value) pair is added to the dictionary.

Removing elements from dictionary:


We can remove a particular item in a dictionary by using the pop() method. This
method removes an item with the provided key and returns the value.
The popitem() method can bus used to remove and return an arbitrary (key,value)
item pair from the dictionary. All the items can be removed at once, using the clear()
method.
We can also use the del key word to remove individual items or the entire dictionary
itself.
Dictionary Built-in Functions
Built-in functions like all(), any(), len(), cmp(), sorted(), etc. are commonly used with dictionaries to
perform different tasks.

Function Description

all() Return True if all keys of the dictionary are True (or if the dictionary is empty).

any() Return True if any key of the dictionary is true. If the dictionary is empty, return False.

len() Return the length (the number of items) in the dictionary.

cmp() Compares items of two dictionaries. (Not available in Python 3)

sorted() Return a new sorted list of keys in the dictionary.

Python Dictionary Methods


Methods that are available with a dictionary are tabulated below. Some of them have already been used
in the above examples.

Method Description

clear() Removes all items from the dictionary.

copy() Returns a shallow copy of the dictionary.


fromkeys(seq[, v]) Returns a new dictionary with keys from seq and value equal to v (defaults to
None).

get(key[,d]) Returns the value of the key. If the key does not exist, returns d (defaults to None).

items() Return a new object of the dictionary's items in (key, value) format.

keys() Returns a new object of the dictionary's keys.

pop(key[,d]) Removes the item with the key and returns its value or d if key is not found. If d is
not provided and the key is not found, it raises KeyError.

popitem() Removes and returns an arbitrary item (key, value). Raises KeyError if the
dictionary is empty.

setdefault(key[,d]) Returns the corresponding value if the key is in the dictionary. If not, inserts the
key with a value of d and returns d (defaults to None).

update([other]) Updates the dictionary with the key/value pairs from other, overwriting existing
keys.

values() Returns a new object of the dictionary's values

Sets:
A set is an unordered collection of items. Every set element is unique (no duplicates) and must
be immutable (cannot be changed).
However, a set itself is mutable. We can add or remove items from it.
Sets can also be used to perform mathematical set operations like union, intersection, symmetric
difference, etc.
Creating Python Sets
A set is created by placing all the items (elements) inside curly braces { }, separated by comma,
or by using the built-in-set ( ) function.
It can have any number of items and they may of different types (integer, float, tuple, string etc.).
But a set cannot have mutable elements like lists, sets, or dictionaries as its elements.
Python Set operations:
Method Description
add() Adds an element to the set
clear() Removes all elements from the set
copy() Returns a copy of the set
difference() Returns the difference of two or more sets as a new set
difference_update() Removes all elements of another set from this set
discard() Removes an element from the set if it is a member. (Do nothing if the element is
not in set)
intersection() Returns the intersection of two sets as a new set
intersection_update() Updates the set with the intersection of itself and another
isdisjoint() Returns True if two sets have a null intersection
issubset() Returns True if another set contains this set
issuperset() Returns True if this set contains another set
pop() Removes and returns an arbitrary set element. Raises KeyError if the set is empty
remove() Removes an element from the set. If the element is not a member, raises a KeyError
symmetric_difference() : Returns the symmetric difference of two sets as a new set
symmetric_difference_update() : Updates a set with the symmetric difference of itself and another
union() Returns the union of sets in a new set,
Updates the set with the union of itself and others
Built-in Functions with Set
Built-in functions like all(), any(), enumerate(), len(), max(), min(), sorted(), sum() etc. are commonly used
with sets to perform different tasks.
Function Description
all() Returns True if all elements of the set are true (or if the set is empty).
any() Returns True if any element of the set is true. If the set is empty, returns False.
enumerate() Returns an enumerate object. It contains the index and value for all the items of the set as
a pair.
len() Returns the length (the number of items) in the set.
max() Returns the largest item in the set.
min() Returns the smallest item in the set.
sorted() Returns a new sorted list from elements in the set(does not sort the set itself).
sum() Returns the sum of all elements in the set.

Python Frozenset
Frozenset is a new class that has the characteristics of a set, but its elements cannot be changed
once assigned. While tuples are immutable lists, frozensets are immutable sets.
Sets being mutable are unhashable, so they can't be used as dictionary keys. On the other hand,
frozensets are hashable and can be used as keys to a dictionary.
Frozensets can be created using the frozenset() function.
This data type supports methods like copy(), difference(), intersection(), isdisjoint(), issubset(),
issuperset(), symmetric_difference() and union(). Being immutable, it does not have methods that
add or remove elements.
Strings in Python:
A string is a sequence of characters. A character is simply a symbol. For example, the English
language has 26 characters.
Computers don’t not deal with characters; they deal with numbers(binary). Even though you may
see character on your screen, internally it is stored and manipulated as a combination of 0s and
1s.
This conversion of character to a number is called encoding, and the reverse process is decoding.
ASCII and Unicode are some of the popular encodings used.
In python, a string is a sequence of Unicode characters. Unicode was introduced to include every
character in all languages and bring uniformity in encoding. You can learn about Unicode from
python Unicode.
How to create a string in python:
Strings can be created by enclosing characters inside a single quote or double-quotes. Even triple
quotes can be used in Python but generally used to represent multiline strings and docstrings.

How to access characters in string?


We can access individual characters using indexing and a range of characters using slicing. Index
starts from 0. Trying to access a character out of index range will raise an IndexError. The index
must be an integer. We can’t use floats or other types; this will result into TypeError.
Python allows negative indexing for its sequences.
The index of -1 refers to the last item, -2 to the second last item and so on. We can access a range
of items in a string by using the slicing operator : (colon).
Python String Operations
Concatenation of Two or More Strings
✓ Joining of two or more strings into a single one is called concatenation.
✓ The + operator does this in Python. Simply writing two string literals together also concatenates
them.
✓ The * operator can be used to repeat the string for a given number of times.
Iterating Through a string
We can iterate through a string using a for loop. Here is an example to count the number of 'l's in a string.

String Membership Test


We can test if a substring exists within a string or not, using the keyword in.
>>> 'a' in 'program'
True
>>> 'at' not in 'battle'
False
Built-in functions to Work with Python
Various built-in functions that work with sequence work with strings as well.
Some of the commonly used ones are enumerate() and len(). The enumerate() function returns an
enumerate object. It contains the index and value of all the items in the string as pairs. This can be useful
for iteration.
Similarly, len() returns the length (number of characters) of the string.
Python String Formatting
Escape Sequence
If we want to print a text like He said, "What's there?", we can neither use single quotes nor double quotes.
This will result in a SyntaxError as the text itself contains both single and double quotes.
>>> print("He said, "What's there?"")
SyntaxError: invalid syntax
>>> print('He said, "What's there?"')
SyntaxError: invalid syntax
One way to get around this problem is to use triple quotes. Alternatively, we can use escape sequences.
An escape sequence starts with a backslash and is interpreted differently. If we use a single quote to
represent a string, all the single quotes inside the string must be escaped. Similar is the case with double
quotes. Here is how it can be done to represent the above text.
# using triple quotes
print('''He said, "What's there?"''')
Output: He said, "What's there?"
# escaping single quotes
print('He said, "What\'s there?"')
Output: He said, "What's there?"
# escaping double quotes
print("He said, \"What's there?\"")
Output: He said, "What's there?"
Here is a list of all the escape sequences supported by Python.
Escape Sequence Description
\newline Backslash and newline ignored
\\ Backslash
\' Single quote
\" Double quote
\a ASCII Bell
\b ASCII Backspace
\f ASCII Formfeed
\n ASCII Linefeed
\r ASCII Carriage Return
\t ASCII Horizontal Tab
\v ASCII Vertical Tab
\ooo Character with octal value ooo
\xHH Character with hexadecimal value HH
Here are some examples
>>> print("C:\\Python32\\Lib")
O/P: C:\Python32\Lib
>>> print("This is printed\nin two lines")
This is printed
in two lines
>>> print("This is \x48\x45\x58 representation")
O/P: This is HEX representation
Raw String to ignore escape sequence
Sometimes we may wish to ignore the escape sequences inside a string. To do this we can place r or R in
front of the string. This will imply that it is a raw string and any escape sequence inside it will be ignored.
>>> print("This is \x61 \ngood example")
This is a
good example
>>> print(r"This is \x61 \ngood example")
This is \x61 \ngood example

The format() Method for Formatting Strings


The format() method that is available with the string object is very versatile and powerful in formatting
strings. Format strings contain curly braces { } as placeholders or replacement fields which get replaced.
We can use positional arguments or keyword arguments to specify the order.
# Python string format() method
# default(implicit) order
default_order = "{}, {} and {}".format('John','Bill','Sean')
print('\n--- Default Order ---')
print(default_order)
--- Default Order ---
John, Bill and Sean
# order using positional argument
positional_order = "{1}, {0} and {2}".format('John','Bill','Sean')
print('\n--- Positional Order ---')
print(positional_order)
--- Positional Order ---
Bill, John and Sean
# order using keyword argument
keyword_order = "{s}, {b} and {j}".format(j='John',b='Bill',s='Sean')
print('\n--- Keyword Order ---')
print(keyword_order)
--- Keyword Order ---
Sean, Bill and John
The format() method can have optional format specifications. They are separated from the field name
using colon. For example, we can left-justify <, right-justify > or center ^ a string in the given space.
We can also format integers as binary, hexadecimal, etc. and floats can be rounded or displayed in the
exponent format. There are tons of formatting you can use. Visit here for all the string formatting available
with the format() method.
>>> # formatting integers
>>> "Binary representation of {0} is {0:b}".format(12)
'Binary representation of 12 is 1100'
>>> # formatting floats
>>> "Exponent representation: {0:e}".format(1566.345)
'Exponent representation: 1.566345e+03'
>>> # round off
>>> "One third is: {0:.3f}".format(1/3)
'One third is: 0.333'
>>> # string alignment
>>> "|{:<10}|{:^10}|{:>10}|".format('butter','bread','ham')
'|butter | bread | ham|'
Old style formatting
We can even format strings like the old sprintf() style used in C programming language. We use the %
operator to accomplish this.
>>> x = 12.3456789
>>> print('The value of x is %3.2f' %x)
The value of x is 12.35
>>> print('The value of x is %3.4f' %x)
The value of x is 12.3457
Common Python String Methods
There are numerous methods available with the string object. The format() method that we mentioned
above is one of them. Some of the commonly used methods are lower(), upper(), join(), split(), find(),
replace() etc. Here is a complete list of all the built-in methods to work with strings in Python.
>>> "MecHaNIcaL".lower()
'mechanical'
>>> "MecHaNIcaL".upper()
'MECHANICAL'
>>> "This will split all words into a list".split()
['This', 'will', 'split', 'all', 'words', 'into', 'a', 'list']
>>> ' '.join(['This', 'will', 'join', 'all', 'words', 'into', 'a', 'string'])
'This will join all words into a string'
>>> 'Happy New Year'.find('ew')
7
>>> 'Happy New Year'.replace('Happy','Brilliant')
'Brilliant New Year'
Mathematics & Fractions in Python:

Python Decimal
In Python, numbers that contain decimal points are always treated as double-precision floating-
point numbers. Decimal points have a smaller range than floats, but more precision.

Decimal modules have a precision that can be adjusted to any size necessary for a given problem,
unlike hardware-based binary floating points. By default, precision is set to 28 places. There are
some values that cannot be accurately represented by the float data type. If the 0.1 value is stored
in a float variable (binary floating-point value), we get only an approximation. In the same
way, 1/3 cannot be exactly represented in a decimal floating point.
Importing the Decimal class from the decimal module is the first statement. Next, we create two
variables called "i" and "j", each containing some values. A value is stored in the variable "k" when
i and j are divided by each other. Once the numbers have been converted to decimal types, the
process is repeated.

Rounding off Numbers Using Python Decimal Module:

A round( ) function returns a floating point number with the specified number of decimals as
a rounded version of the original number. In the default case, the function returns the nearest
integer, since the number of decimals is 0.

In the Decimal module, rounding types are available, as shown below:

Rounding Description
ROUND_CEILING This will round towards Infinity
ROUND_DOWN This rounds the value towards zero
ROUND_FLOOR This will round towards Infinity
ROUND_HALF_DOWN This will round to the nearest value going towards zero
ROUND_HALF_EVEN The value is rounded to the nearest even integer
ROUND_HALF_UP This will round to nearest value going away from zero
ROUND_UP This will round values away from zero
Whenever the last number is either zero or five, the number is
ROUND_05UP
rounded away from zero
Important Function in Python Decimal Module
a. exp() Function

It's pretty straightforward to follow the code sample. Numbers are rounded off with a precision
of two digits. Changing the rounding method is done via the "rounding" object (part of the
main context).

The exp() function – Exponent calculation

The exp() function is used to calculate the exponent value of a decimal point number, e.g. x^2
b. sqrt() Function

Sqrt() is a function that calculates and returns the square root value of the decimal number that
has been passed to it.

Syntax: decimal.Decimal(decimal-number).sqrt()

The "compare" method in the decimal module allows you to compare two
decimal-type objects. Its usage is illustrated in the following examples.
In order to compare two decimal-type objects, you must supply the other number as
an argument. Depending on the numbers being compared, a value of 0, 1, or -1 will be
returned. If the value is 0, both numbers are equal, if it is 1, the first number is greater
than the second, and if it is -1, the first number is less.
The logarithmic functions
There are some logarithmic functions in the Decimal module. Here we are
discussing about two of them. The first one is the ln() method. This method is
used to find the natural logarithm of the decimal number.

Another method is log10() method. This method is used to find the logarithmic
value where base is 10.

Example Code
#Perform ln() and log10() methods
import decimal
my_dec = decimal.Decimal(25.36)
print(my_dec)
#Find logarithmic value with base e
print('ln(x) is: ' + str(my_dec.ln()))
#Find logarithmic value with base 10
print('log(x) is: ' + str(my_dec.log10()))

Output
25.3599999999999994315658113919198513031005859375
ln(x) is: 3.233173129569025152000878282
log(x) is: 1.404149249209695070459909761

The as_tuple() and the fma() method


The as_tuple method is used to represent the decimal as a tuple
with three elements. The elements are sign, digits and the exponent value. In the
sign field when the number is 0, it means the decimal is positive, when it is 1, it
represents the negative number.

The fma() method is known as the fused multiplication and add. If we use fma(x,
y) It will compute the (number * x) + y. In this case the (number*x) part is not
rounded off.

Example Code
#Perform as_tuple() and fma() methods
import decimal
my_dec1 = decimal.Decimal(5.3)
print(my_dec1)
my_dec2 = decimal.Decimal(-9.23)
print(my_dec2)
#Show decimal as tuple
print('\nmy_dec1 as tuple: ' + str(my_dec1.as_tuple()))
print('\nmy_dec2 as tuple: ' + str(my_dec2.as_tuple()))
#Perform Fused Multiply and Add
print('\n(x*5)+8 is: ' + str(my_dec1.fma(5, 8)))

Output
5.29999999999999982236431605997495353221893310546875
-9.230000000000000426325641456060111522674560546875

my_dec1 as tuple: DecimalTuple(sign=0, digits=(5, 2, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 2, 2, 3,


6, 4,
3, 1, 6, 0, 5, 9, 9, 7, 4, 9, 5, 3, 5, 3, 2, 2, 1, 8, 9, 3, 3, 1, 0, 5, 4, 6, 8, 7, 5), exponent=-50)

my_dec2 as tuple: DecimalTuple(sign=1, digits=(9, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 2, 6, 3,


2, 5,
6, 4, 1, 4, 5, 6, 0, 6, 0, 1, 1, 1, 5, 2, 2, 6, 7, 4, 5, 6, 0, 5, 4, 6, 8, 7, 5), exponent=-48)

(x*5)+8 is: 34.49999999999999911182158030

Some copying functions


There are some different methods for copying decimal numbers into another
decimal object. The first method is copy_abs(). It is used to get the absolute
value from the decimal number. The second method is copy_negate(), It is used
to copy the decimal number after negating the actual number. The third function
is copy_sign(). this method prints the first argument, by taking the sign from the
second argument.

Example Code
#Perform copy_abs(), copy_negate() and copy_sign()
import decimal
my_dec = decimal.Decimal(-25.36)
print(my_dec)
#copy the absolute value
temp_dec = my_dec.copy_abs()
print('Absolute is: ' + str(temp_dec))
#copy the negative value
my_dec = decimal.Decimal(7.26)
temp_dec = my_dec.copy_negate()
print('Negate of 7.26 is: ' + str(temp_dec))
#copy the sign value from second argument to first one
my_dec = decimal.Decimal(-25.36)
temp_dec = my_dec.copy_sign(decimal.Decimal(12.5))
print('Copy sign from second argument: ' + str(temp_dec))
Output
-25.3599999999999994315658113919198513031005859375
Absolute is: 25.3599999999999994315658113919198513031005859375
Negate of 7.26 is: -7.2599999999999997868371792719699442386627197265625
Copy sign from second argument:
25.3599999999999994315658113919198513031005859375

The max and min methods


The max and min are two simple methods. These are used to find the maximum
or minimum between two numbers respectively.

Example Code
#Perform max() and min() methods
import decimal
my_dec1 = decimal.Decimal(5.3)
print(my_dec1)
my_dec2 = decimal.Decimal(-9.23)
print(my_dec2)
#Show Minimum and Maximum
print('Minumum: ' + str(my_dec1.min(my_dec2)))
print('Maximum: ' + str(my_dec2.max(my_dec1)))

Output
5.29999999999999982236431605997495353221893310546875
-9.230000000000000426325641456060111522674560546875
Minumum: -9.230000000000000426325641456
Maximum: 5.299999999999999822364316060

Sources:
https://www.tutorialspoint.com/
https://www.geeksforgeeks.org/python-programming-language/
https://www.w3schools.com/python/
PYTHON PROGRAMMING

UNIT-III:
Functions: Function, Function argument, Recursion,
Anonymous / Lambda functions, Global, Local and
Nonlocal variables, Global keyword, Modules and
Packages.
Learning Outcome: At the end of this Unit the student will be able to
• Resolve real world problems using python functions.
• Familiarize the usage of Modules and packages to enhance the problem
solving.

Func on is a block of organized and reusable program code that performs a


single, specific, and well-defined task.
What is func on?
 Func on is a group of statements that together perform a task.
 The main advantage of func on is code reusability
 The func ons can also be called as methods, procedure or subrou nes.
 Python supports two types of func ons:
1. Built-In func on
2. User Defined func on
1. Built-In func on: The func ons which are coming along with python
so ware automa cally are called as built in func ons or predefined
func ons. Ex: print(), type(), input()…etc.
2. User Defined Func ons: The func ons which are developed by
programmer explicitly according to business requirements are called
as user defined func ons.
Ex: for banking sectors used the func ons like deposit(), withdraw(),
statement(),
Every func on encapsulates a set of opera ons and when called it returns the
informa on to calling program.
Func ons provide be er modularity for your applica on and a high degree of code
reuse.
Func on Defini on:
 A func on ‘f’ that uses another func on ‘g’ is known as the calling func on and
‘f’ is known as the called func on.
 The inputs that the func on takes are known as arguments/parameters.
 When a called func on returns some result back to the calling func on, it is said
to return that result.
 The calling func on may or may not pass parameters to the called func on. If the
called func on accepts arguments, the calling func on will pass parameters, else
not.
 Func on declara on is a declara on statement that iden fies a func on with its
name, a list of arguments that it accepts, and the type of data it returns.
 Func on defini on consists of a func on header that iden fies the func on,
followed by the body of the func on containing the executable code for that
func on.
However, to define a func on, you must keep the following points in mind.

1. Func on blocks starts with the keyword def.


2. The keyword is followed by the func on name and parentheses ( ). The func on
name is used to uniquely iden fy the func on.
3. A er the parentheses a colon (:) is placed.
4. Parameters or arguments that the func on accepts are placed with parentheses.
Through these parameters values are passed to the func on. They are op onal.
In-case no values are to passes, nothing is placed within the parenthesis.
5. The first statement of a func on can be an op onal statement- the
documenta on string of the func on or docstring describe what the func on
does.
6. The code block within the func on is properly indented to from the block code.
7. A func on may have a return[expression] statement. That is, the return
statement is op onal. If it exits, it passes back an expression to the caller. A return
statement with no arguments is the same as return None.
8. You can assign the func on name to a variable. Doing this will allow you to call
the same func on using the name of that variable.
9. The words before parentheses specifies the func on name, and the comma-
separated values inside the parentheses are func on arguments.

Types of func ons:


1. Func ons with parameters and with return values
2. Func ons with parameters and without return values
3. Func ons without parameters with return values.
Example to define a func on without parameters and returning any value.

Example to define a func on without parameters and not returning any value.
Returning mul ple values from a func ons:

In any programming language using a single func on we can return a single value but
in python we have a special feature called with the help of single func on we can
return mul ple values.

Example to defining a func on which returns mul ple values.

Types of Arguments/Types of Parameters


In python we have various types parameters like below:
1. Formal Arguments
2. Actual arguments
3. Posi onal arguments
4. Keyword arguments
5. Default arguments
6. Variable length arguments

1. What are formal arguments?


Called func on arguments are formal arguments.
2. What are actual arguments?
Calling func on arguments are actual arguments.
Example: To understand actual arguments and formal arguments:
3. Posi onal Arguments:
At the me of func on calling, actual parameters should be passed according to the posi on of the
formal parameters.

Ex:

Note: The number of arguments and the posi on of the argument must be matched. If we change the order
then result may be changed and if we change the number of arguments then we will get error.

Keyword Arguments:

We can pass arguments values by keyword i.e., parameter name

Default Arguments:

We can provide default values to arguments.


In this case if we didn’t pass the value it will take default value.

Variable lengths Arguments or Arbitrary arguments:

We can pass any number of arguments to a func on such type of arguments are called as variable length
arguments.

We can declare a variable length argument with * symbol as follows:

def func on1(*n):

Recursion: (Backward Tracking) [Loops are forward tracking]


A recursive func on is defined as a func on that calls itself to solve a smaller version
o fits task un l a final call is made which does not require a call to itself.
Every Recursive solu on has two major cases,
Every recursive func on must have at least one base case. Otherwise, the recursive
func on will generate an infinite sequence of calls thereby resul ng, in an error
condi on known as an infinite stack.
Base Case: Termina ng from recursive case
Recursive Case: Calling itself
Example for recursion: Factorial Program
5! = 5x4!
= 5x4x3!
= 5x4x3x2!
= 5x4x3x2x1!
Lambda or Anonymous func ons:
Lambda or anonymous func ons are so called because they are declared as other
func ons using the def key word. Rather, they are created using the lambda keyword.
It contains only a single line
Syntax:
Lambda arguments: Expression
This is equivalent to the below general func on declara on like the following code.
def Sum(x,y):
return x+y
The arguments contain a comma separated list of arguments and the expression is an
arithme c expression that uses these arguments. The func on can be assigned to a
variable to give it a name.

Here x and y are the arguments and x+y is the expression that gets evaluated and
returned.
Key points:
1. Lambda func ons have no name.
2. Lambda func ons can take any number of arguments.
3. Lambda func on can return just one value in the form of an expression.
4. It always contains an expression which is returned but not return keyword.
5. They are one line version of a func on and hence cannot contain mul ple
expressions.
6. They cannot access variables other than those in their parameters.
7. Lambda func on cannot even access global variables.
Program: To find smaller of two numbers using lambda func on

Program: To use a lambda func on with an ordinary func on.

In the aforemen oned code, the regular func on increment accepts a value in y. It
then passes y to a lambda func on. The lambda func on increments its value and
finally the regular func on returns the incremented value to the earlier.

You can use a lambda func on without assigning it to a variable. This is shown below.

Program: That uses a lambda func on to find the sum of first 10 natural numbers
In the above code, we have assigned a variable x to a lambda expression and then invoked the
lambda func on with empty parentheses (without arguments)
 You can call a lambda func on from another lambda func on. In such a case, the lamba
funciton is said to be a nested func on. However, use of nested lambda func on must be
avoided.

With con nua on of Unit-1: Local space and global space

Global keyword:
Built in Scope: print(“Hi”) #already defined func on in python
type()

LEGB Rule:
L means Local
E means Enclosed
G means Global
B means Built-In
Name Space in Python:
A name space is a collec on of currently defined symbolic names along with
informa on about the object that each name references.

Python Modules:
Modules are pre-wri en pieces of code that are used to perform common tasks like
genera ng random numbers, performing mathema cal opera ons, etc.
 Module is a file that contains code to perform a task.
 It allows you to reuse or more func ons in your programs.
 A module may contain variables, func ons, classes, etc.,
 Module is a file with a .py extension that has defini ons of all func ons and
variables that you would like to use even in other programs. (xxxx.py file)
The standard library modules

In the above code, we import the sys module (short of system) using the import
statement to use its func onality related to the Python interpreter and its environment.
A module imported in a program must be located and loaded into memory before it
can be used. Python first searches for the modules in the current working directory.
The from and import statements:
A module may contain defini on for many variables and func ons. When you import
a module, you can use any variable or func on defined in that module. But if you
want to use only selected variable or func ons, then you can use the from… import
statement.

Name of moule:
Every module has a name. You can find the name of a module by using the __name__
a ribute of the module.
First create a file named as main.py in python local library.
Write a set of instruc ons of a code in terms of func ons.
Import a module that named as main by using the syntax from main import *

Packages in Python:
A package is a hierarchical file directory structure that has modules and other packages
within it. Like modules, you can very easily create packages in Python.
Key points to remember:
Packages are searched for in the path specified by sys.path.
__init__.py file can be an empty file and may also be used to execute ini aliza on code
for the package or set the __all__ variable.
The import statement first checks if the item is defined in the package. If it is unable to
find it, an ImportError excep on is raised.
UNIT-IV

Object Oriented Programming: Introduction to OOPs,


Class, Object, Constructors, Methods, Inheritance, Method
Overriding, Multiple Inheritance, Operator overloading,
Encapsulation and Polymorphism.

Learning Outcome:
At the end of this Unit the student will be able to
• Design object‐oriented programs with Python classes.
• Usage of inheritance, encapsulation, inheritance and
polymorphism for reusability.
1. What is OOPS?
Ans: OOPs stands for Object Oriented programming in system. It is a latest program
approach.
2. How many programming approaches we have?
Ans: Programming approaches are 2 types
1. Procedural Oriented approach
2. Object oriented approach
3. What is meant by procedural oriented approach?
Ans: In procedural oriented approach program is a collec on of procedures or
methods or func ons.
Example:
M1()
{
Logic
}
M2()
{
Logic
}
Main() #ini ally func on execu on is star ng from main() step-1
{
M1() #step2 will execute
M2() #step3 will execute
}
A programming language which will follow above approach that is called as
procedural oriented programming language.

Ex: C-Language.

Due to limita on of above procedural oriented programming approach.


Industry experts are introduced a new programming approach. i.e.,

Object Oriented Programming approach.


What is Object Oriented Programming approach?
Ans: In object oriented programming approach.. program is a collec on of classes.
Ex.
class C1:
{
M1()
{
}
M2()
{
}
}
class C2:
{
Main() # step-1 calling
{
C1.M1() #Step-2 go to M1() func on in class-1
C1.M2() #Step-3 go to M2() func on in class-1
}
}
A programming language which will follow above approach which is called as
object-oriented programming language.
Ex: C++, Java, C#, .Net, VB.net, PYTHON

Every object-oriented programming language should follow below 4 principles.


1) Encapsula on
2) Abstrac on
3) Inheritance
4) Polymorphism

To achieve the above 4 principles every object-oriented programming language will


depend on below 2 concepts.
1. Class
2. Object
Both are inter-related with each other.
What is Class?
Ans: Class is a collec on of states and behaviours. To define a class, we should use
class key word.
<syntax to define class.
class <class name>:
states
behaviours

class MyClass:
#states
#behaviours
What is state?
Ans: A field which is represen ng a value is called as state.
Sates are two types: 1. Variable 2. Constant
What is variable?
Ans: A field which represent some value but value can be changes is called as
variable.
What is Constant?
Ans: A field which represent some value but value can’t be changed is called as
constant.
In python we have 3 types of variables.
1. Local variable
2. Instance Variable
3. Sta c Variable.
What is local variable?
Ans: A variable which is declare with in the method is called as local variable.

What is the scope of local variable?


Ans: Within the par cular method (as part of method execu on)

When the memory will allocate for local variable?


Ans: At the me of method execu on. Once method execu on is completed, all local
variables will destroy.
What is Instance variable?
Ans: Instance means object.
A variable which is declared inside the constructor or inside the instance method by
prefixing self-keyword is called as instance variable.
Where instance variable will create?
Ans: Within the object.
What is self?
Ans: Self is a keyword. Which represen ng current class object.
Why self?
Unlike other programming languages like C++, where self is considered to be a
keyword, in Python it is a conven on that programmers tend to follow. It is basically
a parameter in a method defini on. However, you can use any other name in place
of self like another or me or Phanisir or anything else for the first parameter of a
method.

When the memory will allocate for instance variable?


Ans: At the me of object is crea ng.

When the memory will de-allocate for instance variable?


Ans: At the me of object is destroying.

What is the scope of instance variable?


Ans: We can access with in the constructors and within the instance methods of that
class.

Ex: for instance, variable. self.a=10

What is Sta c Variable?


Ans: A variable which is declared inside the class or inside the sta c method by
prefixing class name is called as sta c variable.
Note: While declaring sta c variable within the class, prefixing class name is not
required.
Ex: for sta c variable MyClass.b=20

What is the scope of sta c variable?


Ans: Within the class anywhere..

When the memory will allocate for sta c variable?


Ans: At the me of class is loading.

What is behaviour?
Ans: A block which represent some func onality (logic) is called as behaviour.

In python we can define following types of behaviours.


1. Method or func on
2. Constructor
What is method?
Ans: A block which represent some func onality will execute whenever we call, is
called as method.

Types of methods:
1. Instance method
2. Sta c method
3. Class method
Instance method Class method Sta c Method
Bound to the object of a
Bound to the class Bound to the class
class
It can modify an object It can’t modify a class or
It can modify a class state
state object state
Can access and modify Can’t access or modify
Can access only class
both class and instance the class and instance
variable
variables. variables

What is Instance method?


Ans: A method which is taking self-keyword as first parameter is called an instance
method.
Instance method address will be available within the object.
Due to that reason instance method we have to access by using object.
<Syntax to define instance method>

def <method name(self)>:


logic
Ex:
def MyFun(self):
print(“my fun is calling”)

What is object? (it’s a real me en ty)


Ans: Object is an instance of class.
What is class?
Ans: Class is a logical representa on that means when we define a class no memory
will allocate for class members.
When we create an object; memory will allocate; with this we can say class is a
logical representa on; object is a physical representa on.

For Example:
Human being is a class -> Anil and Rani are objects of human being class
Employee is a class -> Gupta and Phani are objects of employee class
Car is a class -> Your car and my car are objects.

What is Instance?
Ans: Instance is nothing but physical representa on, finally we can say that object is
a physical representa on of a class.

<syntax to create object>


Example:1 Obj=MyClass()
Example:2 a=MyClass()
Example:2 b=Exmployee()

Programming by using Instance Method:


Programming by using Local variables within Instance Method:
Write a python program to define calculate class with one instance method for
addi on of two numbers and prin ng addi on result.
Define Employee Class with 2 instance methods..
SetEmpInfo() -> This method is to ini alize empno, empname, empsal
DisplayEmpInfo() -> This method is to display Employee informa on i.e., empno,
empname, empsal

Reason for Errors:


In the above program empno, empname, empsal are declared as local
variables within SetEmpInfo() instance method.
These variables cannot access in second method because the scope of local
variables with in that method. What is the solu on for the above program.
declare the variables with prefix self.
Observa on: In the above program. empno, empname, empsal are ini alizing
within the instance method, but object is crea ng first line and empno,
empname, empsal are ini alizing second line, but we need one ini alizing
mechanism for empno, empname, empsal which will execute at the me of
object is crea ng it is nothing but constructor.
Create two objects for Employee Class..
Observa on: Default Constructor is ini alizing the same values to both
objects..
How to overcome this problem?
Ans: By ini alizing instance variables..
With the help of parameterized constructor.
What is parametrized constructor?
Ans: While defining a constructor if we declare parameters, which is called as
parameterized constructor.
Write python program for a student class with the following states and behaviours:
States are: s d, stname, s otmarks of 3 subjects m1, m2, m3, stavgmarks of 3 subjects, result of
3 subjects. Result can be (i) Fail <35 in any one subject.
(ii) 1st class if avgmarks >=60
(iii) 2nd class if avgmarks >=50
(iv) 3rd class if avgmarks >=40
Behaviours are: 1) parameterized constructor
2) CalResult of 3 subjects
3) Display studentInfo() i.e., s d, stname,s omarks, stavgmarks, stresult.
4) Display college details () i.e., college name, branch, year, sec on.
Inheritance:
Inheri ng the members from one class to another class is called as inheritance.
Establishing the parent and child rela on between the classes is called as inheritance.
A class, which is giving parent class, super class or based class.
A class, which is receiving is known as child class or sub class or derived class.

Because of inheritance super class member can accessed by sub class but not vice-versa.

Syntax For Inheritance:


Class BC: #Based class or Parent Class
#members
Class DC(BC): #Derived Class or Child Class
#members
In Python we have various types of inheritance like below:
1. Single Inheritance
2. Mul ple Inheritance
3. Mul Inheritance
4. Mul -Path Inheritance
5. Hierarchical Inheritance
6. Hybrid Inheritance

1. Single Inheritance:
Inheri ng from one class to another class is called as single inheritance.
Before going for inheritance, the following example we have to understand.
1. How to access instance method within the class?

We don’t require to create object; we can access by using self-keyword. Here self is
nothing but current class object.
2. How to call instance method outside the class
With the help of object.
3. How to access sta c method within the class.

In Python when you are accessing sta c method within the class are outside the class, we
should access with the help of class name.

Example for single Inheritance:


Write parent within the child parenthesis

Mul -level Inheritance:


Hierarchical Inheritance:
Mul ple Inheritance: Inheri ng from mul ple base classes into single derived class is called as
mul ple mul ple inheritance.
Polymorphism:
What is polymorphism?
Ans: Polymorphism means one name many forms.
Implemen ng mul ple func onali es with the same name is
called as . That means implemen ng mul ple
methods with the same name but every method behaviour will
be different is called as polymorphism.

In Python polymorphism are of two types


1. Overloading
2. Overriding
Overloading:
In python we can implement three types of overloading
1. Method Overloading
2. Operator Overloading
3. Constructor Overloading
Method Overloading:

If two methods are having same name with different arguments list then those
methods are called as overloaded methods.

In the above example is working for addi on opera on only 2 no’s and 3 no’s but it
is not working for other combina on. This type of method overloading is not allowed
in python.

To implement single addi on method for mul ple arguments:


Single asterisk (*) is also used in *args. It is used to pass a number of arguments to
a func on, it is mostly used to pass a non-key argument and variable length
argument list.
Constructor Overloading:
Implemen ng mul ple constructors with the different number of arguments is
called as constructor overloading.

Operator Overloading:
We can use the same operator for mul ple purpose which is nothing but operator
overloading.
Example: ‘ + ‘ operator can be used for arithme c addi on and string concatena on.
Overriding:
We have two types of method overriding
1. Method overriding
2. Constructor overriding
Method Overriding:
Reimplemen ng super class method within the sub class with the
same and same signature is called as method overriding.

Constructor Overriding:
Implemen ng the super class constructor and sub class constructor with
the same signature is called as constructor overriding.
Observa on:
When we execute the below statement. “DC ()” it will go to DC class and
it will try to invoke the DC class constructor. But within the DC class we
have ‘’’-‘’’ comment DC class constructor. But due to inheritance BC class
constructor will inherit to DC class which will execute.
UNIT-V:
Advanced topics: Iterators, Building Your Own Iterator, Infinite
Iterators, Generators, Generator Expression, Closure Function,
Decorators, @property decorator, Getters and Setters, RegEx,
Match object, datetime, Files (Open, Read, Write, Close) and File
Methods,

Learning Outcome:
At the end of this Unit the student will be able to
• Interpret the advantages of advanced concepts like iterators,
generator, decorators and regular expressions.
• Identify the commonly used operation involved in files for I/O
processing.
Iterators:
What are the iterators?
An iterator in python refers to an object that we can iterate upon.
The iterator consists of countable values, and it is possible to traverse
through these values, one by one.

The iterator simply implements the python’s iterator/protocol.


The iterator protocol is a python class which comes with two special
methods.

__iter__ ( ) and __next__ ( )

With these 2 methods, the iterator is able to compute the next value in
the itera on.

The __iter__ ( ) method returns the iterator object.


While the __next__ ( ) method helps us traverse the elements in the
iterable object.

Iterator is used for itera ons nothing but repe on of process.

There is one more way to iterate the values. Which is Iterator.

How to create an iterator?


My_list is the name of the list. From list we have to create an iterator.
We have iter func on which converts out list to iterator.
Iterator will not give you, all the values at a me. It will give you one value
at a me.
What is happening behind the program?
When we say iterator: It will have mul ple values. When we call the
func on again it will preserve the old values and give the next value. i++.

If your want to create your own objects?


Here list is inbuilt func on.

To create out own iterator we need 2 func ons


1. iter( ) -> gives object or iterator
2. next ( )

Advantage of iterator: once we got the value of ‘i ‘it will not repeat
again.
Generators:

Generator is the alternator for the iterator. When we don’t


want to use the iterator, then generator will come into the
picture.
How to create generator.
We create generators by using yield keword.
Generator give you iterator.
A func on cannot give you an iterator. We have to convert the
func on into generator. Normally in func on we write return
def FirstTen ()
return 5
values= FirstTen()
Generator give iterator here FirstTen () func on is generator
yield will return format of iterator to fetch values, we have to
use __next__( ) func on

**Conclusion:
 Generator func on allows you to declare a func on that
behaves like an iterator.
 They make an iterator in a fast, easy and clean way.
 Python generator is simple way of crea ng iterators.
 The work done by iterators are automa cally handled by
generators.
 Generator is a func on that return an object (iterator)
which we can iterate over (one value at a me)
Closures:
Func on within the func on called nested func on
Inner() func on outside of the func on body thrown an error.
Func on name with parenthesis is execu ng that func on defini on,
If it removes, we will return the func on reference to ‘a’ variable
So that, it means we executed this inner func on body outside its
Scope, this is the local func on (inner) we executed it outside that
func on. But, we know that we can’t call a func on outside its scope then
how we are ge ng this output.
This technique is called as Closure.
Here, func on ‘ a ‘ and inner are the same func on and we are
execu ng this func on outside its scope, this technique is called
as closure.
“The technique by which some data get a ached to the code is
called as closure” in python.
Closure:
Func on object that remembers values in the enclosing scope
even if they are not present in memory.
A er calling outer() func on ; we are calling a(), it is poin ng
towards the func on inner, we called that and we go the result
even though we finished the execu on of this outer func on then
also the message “Hi Welcome” is remembered and it is printed,
this technique is called as closure.
When do we have a closure?
What are the criteria needed to create a closure in python.
1. Nested func on
2. Nested func on must refer values in enclosing scope.
3. Enclosing func on must return nested func on.
What are the advantages of closures in python.
1. Can avoid global values
2. Data hiding
3. Implement decorators
Date and Time Module:
It will give 7 fields like Year, Month, Day, Hours, Minutes, Seconds and Micro
Seconds.
For example: 2023 11 15 10 30 40 000500
datetime ----- Module
datetime ----- class
now( ) ----- method
import datetime
datetime.datetime.now( )
Creating date: using constructor (datetime( ))
datetime( ) in the parenthesis we will pass 7 fields.
datetime.datetime(2023,11,15,10,30,40,000500)
x = datetime.datetime(2023,11,15,10,30,40,000500)
print(x) -> will get the output
strftime (parameter) --- formatting Date and Time fields
Here the parameter is a single parameter is nothing but formatting parameter.
Parameters in strftime(“Formating parameter”)
Type of parameter representation Symbol of argument Example
2 digit %y 23
Year
4 digit %Y 2023
short %b Jun
Month
full %B June
short %a Mon
Day
full %A Monday
%H 24 hrs format
Hours %I 12 hrs format
%p (AM/PM)
Minutes %M 0-59
Seconds %S 0-59
000000 to
Micro-Seconds %f
999999
Files (Open, Read, Write, Close) and File Methods:

Files are used to save the output data.


File is nothing but collection of data. Files are divided into 2 types.
 Text file
 Binary file
First create a File object, whereas in C-Lang we will be called as File
pointer.
open( )
file_object = open(“filename.txt”, “Access mode”)
Here file object is nothing but file pointer which points to the content
of the file.
Access modes:

r - read mode
*only for reading the content
*File pointer point at the beginning of the file.
* File should exist before opening in read mode

fp=open(“mechd.txt”, “r”)

mechd.txt
Welcome to the Python
Class.

w- write mode
*only for writing the content
*File pointer point at the beginning of the file.
1) If the file exists the file is opened and pointer points at
Beginning and data will be overwritten.
2) If the file doesn’t exist then new file will be created with
given file name.
fp=open(“mechd.txt”, “w”)

mechd.txt
Welcome to the Python
Class.

a - append mode
1) To append and write the data
2) File exist --- file pointer points at the end and the
content in file
3) File does’t exist --- New file will be created and file
pointer points at beginning.

fp=open(“mechd.txt”, “a”)

mechd.txt
Welcome to the Python
Class.

Access Modes:
r - Reading
w - Writing
a - Appending/writing
All these for TEXT files
r+ - Reading and writing
w+ - Reading and Writing
a+ - Reading Appending
Access Modes:
rb - Reading
wb - Writing
ab - Appending/writing
All these for BINARY files
rb+ - Reading and writing
wb+ - Reading and Writing
ab+ - Reading Appending

Read mode - File pointer at beginning


Write mode - File pointer at beginning Create a
Append mode - File pointer at the end of content. New File

Note: Every opened file should be closed. Its user responsibility.


Ex: file_object.close( )

WRITING: f1 = open(“ mechd.txt ”, “w”)


write( )
* write( ) * writelines( )

f1.write(string)

Ex: f1 = open(“mechd.txt”, “w”)


f1.write(“Welcome to Python”)

f1.writelines(list)

Ex: f1 = open(“mechd.txt”, “w”)


lines=[“Hello”, “Welcome”, “Python”]
f1.writelines(“lines”)
READING: f1 = open(“mechd.txt ”, “r”)
read( )
* read( ) * readline( )

f1.read(bit positions)
mechd.txt
Welcome to the Python
Class.

Ex: f1 = open(“mechd.txt”, “r”)


f1.read(5) ----output is Welco
f1.read(5) ----output is me to
f1.read(3) ----output is the
f1.read( ) ----output is Welcome to the Python class

readline( ) means reading content of single line


f1.readline( )
mechd.txt
Hello
Welcome
Python class

Ex: f1 = open(“mechd.txt”, “r”)


f1.readline( ) ----output is Hello
f1.readline( ) ----output is Welcome
f1.readline( ) ----output is Python class

readline( ) means reading content of all lines.

f1.readlines( ) ----output is Hello Welcome Python class


f1=open(“mechd.txt”, “w”)
f1.write(“Welcome to the Python Class”)
mechd.txt
Welcome to the Python
Class.
f1.close( )
f1=open(“mechd.txt”, “r”)
print(f1.read( )) Output is Welcome to the Python
Regular Expressions: RegEx
It is a sequence of characters (strings) used for pattern matching.
Here, pattern means a character or a group of characters.

.
Example: E-Mail: sphani.me@anits edu.in

@ and . Pattern matching


To implement Regular Expression, we need to import re package.
Functions Available:

findall( ) --- Return list of all matches


search( ) --- Return match object if there are any matches
split( ) --- Split the string from the given pattern
sub( ) --- Substitute new string to old string.
The match object will be having different methods in order to display the results

1. start( ) ----- give the position of occurrence


2. span( ) ----- tuple of start and end positions of match.
3. string( ) ---- return the actual string used for pattern matching.
Decorators:
What is Decoration?
It is nothing but adding something to make a thing more attractive or
presentable.

Standard Definition: “Any callable python object that is used to modify a


function or a class.
Function Decorator
Class Decorator
1. Function Decorator:
1. Nested function
2. One function can return another function
3. Reference about the function (memory location of that function)
4. Function as parameter of another function.
@Decorator_function_name
Setter and Getter:

These are the special type of methods

Using setter we can initialize an individual instance variable.


Using getter we can retrieve value from an individual instance
variable.
Finally, we can say that getter and setter are individual instance
variable initialization and retrieval mechanism.
Setter should prefix with set or Set
Getter should prefix with get or Get

Syntax for setter:


def <settername(self,<parametername>):
<instance variable name>= <parametername>

Syntax for getter:


def <settername(self):
return <instance variable name>

def setX(self,a):
self.x=a
Note: setter name should be same as instance variable name
but instance variable name should be small case like: x
Setter name should be upper case like: X

Example for getter definition


def getX(self)
return self.x

You might also like