0% found this document useful (0 votes)
10 views347 pages

Python Notes Software2026.1

Uploaded by

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

Python Notes Software2026.1

Uploaded by

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

Day – 1

Python programming

INTRODUCTION
..............................,

Tiobe index – check which programming language trending

python trending no -1

---------------------------.

=> core Python


=> Advanced Python
=> Data science related moduled – Numpy ,pandas ,matplotlib,scipy,Scikit,seaborn,NLP...etc
----------------------------.
Pre – Requists for learning python
– no need to know about any languages
----------------------------.

What is required to become a software engineer


– excellent Coding Standards
– Coding – Hacker Ranking Examples

Day – 2

Real Time Applications devloped by using PYTHON Programming

-------------------------.

=> By using Python Programming , top world class Software develops the following
Applications/Products.

1. Web Applications
a) JAVA Lang(SUN Ms --oracle) -----> Servelts ,JSP,Spring<Hibernate ,....etc
b) c#.net Language (MS) ------> asp.net
c) PYTHON Language

requirement
---------------.

Calendar ----develop – by using java lang – 25 lines code write


Calendar same --- C#

...........................'

Python only 2 lines code write – calendar App


Less coading and More meaningful – Libraries(Modules)
Ex-

>>> import calendar


>>> print(calendar.calendar(2024))
2024

January February March


Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 2 3 4 5 6 7 1 2 3 4 1 2 3
8 9 10 11 12 13 14 5 6 7 8 9 10 11 4 5 6 7 8 9 10
15 16 17 18 19 20 21 12 13 14 15 16 17 18 11 12 13 14 15 16 17
22 23 24 25 26 27 28 19 20 21 22 23 24 25 18 19 20 21 22 23 24
29 30 31 26 27 28 29 25 26 27 28 29 30 31

April May June


Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 2 3 4 5 6 7 1 2 3 4 5 1 2
8 9 10 11 12 13 14 6 7 8 9 10 11 12 3 4 5 6 7 8 9
15 16 17 18 19 20 21 13 14 15 16 17 18 19 10 11 12 13 14 15 16
22 23 24 25 26 27 28 20 21 22 23 24 25 26 17 18 19 20 21 22 23
29 30 27 28 29 30 31 24 25 26 27 28 29 30

July August September


Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 2 3 4 5 6 7 1 2 3 4 1
8 9 10 11 12 13 14 5 6 7 8 9 10 11 2 3 4 5 6 7 8
15 16 17 18 19 20 21 12 13 14 15 16 17 18 9 10 11 12 13 14 15
22 23 24 25 26 27 28 19 20 21 22 23 24 25 16 17 18 19 20 21 22
29 30 31 26 27 28 29 30 31 23 24 25 26 27 28 29
30

October November December


Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su
1 2 3 4 5 6 1 2 3 1
7 8 9 10 11 12 13 4 5 6 7 8 9 10 2 3 4 5 6 7 8
14 15 16 17 18 19 20 11 12 13 14 15 16 17 9 10 11 12 13 14 15
21 22 23 24 25 26 27 18 19 20 21 22 23 24 16 17 18 19 20 21 22
28 29 30 31 25 26 27 28 29 30 23 24 25 26 27 28 29
30 31

--------------------------------------------------------------------------------------------.

otp programing Python programming


ex-----.
>>> import random
>>> print(random.randint(1000,35555))
5895

------------------------------------------------.

2. Game applications
3. Arrtifical intelligence applivations (ML,DL)
4. Desktop Applications ( GUI Applications)
5. Image Processing Applications
6. Text Processing application
7. Business applications
8. Audio and video applications
9. Web Scrapping / Harvesting Applications
10. Data visulization
11. Scientific applications ex nasa
12. software devlopment
13. operating system installers ...etc

Day -3

Getting Started with Python Programming


----------------------------------------------------------.

Index
-------.
– History of Python
1. 1980 concived
2. implementation 1989
3. 1991 officially released
4. Guido van Rossum devloped
5. CWI institue in nether land by devloped
6. managed by -non comerical orginization “Python software foundation”
7. website – www.python.org
---------------------------------------------------------------------------------------------------.

versions

1. python – 1.x --- outdated


2. python 2.x---- outdated-- not support backword compatability
3. pytnon 3.x ------ new

examples\

>> print("hello world")


hello world
>>> import calendar
>>> print(calendar.month\(2023,4))
April 2023
Mo Tu We Th Fr Sa Su
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
>>> import math
>>> print(math.pow(2,3))
8.0
>>> print(math.sin(90))
0.8939966636005579
>>>

Day – 4

Feature of Python
----------------------,

python programing provide 11 feature


1. simple
2. Freeware and open source
3. platform independent language
4. Dynamically typed programming language
5. Interpreted programming language
6. High level Programming Language
7. Robust (Strong)
8. Both Functional (procedure) and object Oriented Programming Lang(OOps)
9. Extensible
10. Embedded
11. Supports Third APIs such as numpy,pandas ,matploatlib,..etc

SIMPLE

----------------;

– Python is one of the simple programming language bcoz of 3 important technical factors.
They are

Factor -1
----------. provide rich set of modules (libraries ) . so that python programmers are re-using the
predefined code wothout writing our own code.

Definition module
------------------------.
Amodule ia collection functions , Attributes and class Names .

Examples : calender , math,qr code , random, os module ,multithreading etc.

Factor – 2
------------.
day – 5

--------------------------------------------------------------------------------------------------------------------------
-------------
Factor-2
--------------------------------------------------------------------------------------------------------------------------
-------------
=>Python Programming Provides In-built Garbage Collection Facility by executing Garbage
Collector Program. So That Garbage Collector collects un-used memory space and improves the
performance of Python Based Applications.
----------------------------------------
Def. of Garbage Collector:
----------------------------------------
=>Garbage Collector is one of the In-Built Python Program in Python Software and It is running
Behind of Regular Python Program and whose Role is Collects Un-Used Memory space and
Improves the
Performance of Python Based Applications.
=>Hence Garbage Collector takes take about Automatic Memory Management.
--------------------------------------------------------------------------------------------------------------------------
-------------
Factor-3
--------------------------------------------------------------------------------------------------------------------------
-------------
=>Python Programming Lang Provides User-Friendly Syntaxes and Makes the programmer to
develop Error-Free Programs within Limited Span of Time.
=====================================X================================

>>> pi=22/7
>>> print(pi)
3.142857142857143
>>> =3.4
File "<python-input-4>", line 1
=3.4
^
SyntaxError: invalid syntax
>>> a=3.4
>>> print("%0.25f" %a)
3.3999999999999999111821580
>>> print("%0.75f" %a)
3.399999999999999911182158029987476766109466552734375000000000000000000000000
>>>

============.
Simple

– python programming is eady and hence python is simple .

2. Free ware and open source


Freeware
----------;
i any software download freely

example – python,java-----
Open Source:
---------------.
– the standard name of python – cpython
– many software compney came forwaord and customized CPYTHON and developed their own
inhouse tools.
– CPYTHON – python distributions

some of thepython distributions


1. jpython or jython--- javabased applications running
2. Iron Python OR Ipython – used C# applications
3. ruby python- ruby applications
4. Micro python – used to run / develop micro controller applications
5. Anaconda python – used to run Big Data/ Hadoop Based Applications
6. stackless python – used to concurrency applications ..etc

Day – 6

Platform Independent Language

=>A Platform is nothing but Type of OS being Used to run Application / Program.
=>In this context, we have two types of Programming languages. They are

1. Platform Dependent Lang


2. Platform Independent Lang
--------------------------------------------------------------------------
1. Platform Dependent Lang
--------------------------------------------------------------------------
=>In Platform Dependent Lang, Data Types differes from One OS to Another OS.
Example: C,C++....etc

--------------------------------------------------------------------------
2. Platform Independent Lang
--------------------------------------------------------------------------
=>In Platform Independent Lang, Data Types memory remains Same on All Types OSes.
=>In Effective Platform Independent Lang, all types of Values will store in the form of OBJECTs and
they can store Un-Limited amount of data
=>Hence java Object contains Size Restricted where Python Objects contains Un-limited Size and
unlimited values can store.

NOTE: IN PYTHON ALL VALUES ARE STOREd IN THE OF OBJECTS.


Examples: Java, Python.

Day – 7
==============================================
4. Dynamically Typed
==============================================
=>In IT, we have Two Types of Programming languages. They are
1. Static Typed Programming Languages
2. Dynamically Typed Programming Languages
-----------------------------------------------------------------------------------------------------------------------
1. Static Typed Programming Languages
-----------------------------------------------------------------------------------------------------------------------
=>In Static Typed Programming Languages, It is mandatory to Specify Variable Declaration for
storing
Inputs in main memory of Computer.

Examples Statements:
---------------------------------
int x,y,z; // Variable Declaration--mandatory
x=10
y=30
z=x+y

Examples Lang: C, C++, Java, C#.net....etc


-----------------------------------------------------------------------------------------------------------------------
2. Dynamically Typed Programming Languages
-----------------------------------------------------------------------------------------------------------------------
=>In Dynamically Typed Programming Languages, depends on type of value we are assiging, whose
data type automatoically / Implicitly assigned by Python Execution Environment
=> There is No Need to write Variable declaration in Dynamically Typed Programming Languages

Example Stmts:
---------------------
>>> a=100
>>> b=200
>>> c=a+b
>>> print(a,type(a))-----------100 <class 'int'>
>>> print(b,type(b))----------200 <class 'int'>
>>> print(c,type(c))----------300 <class 'int'>
Examples: Python
===============================================
5. Interpreted Programming
===============================================
=>When we develop any python program, we must give some file name with an extension .py (File
Name.py).
=>When we execute python program, two process taken place internally
a) Compilation Process
b) Execution Process.
=>In COMPILATION PROCESS, The python Source Code submitted to Python Compiler and It
reads the source Code, Check for errors by verifying syntaxes and if no errors found then Python
Compiler Converts into Intermediate Code called BYTE CODE with an extension .pyc
(FileName.pyc). If erros found in source code then we get error displyed on the console.
=>In EXECUTION PROCESS, The PVM reads the Python Intermediate Code(Byte Code) and Line
by Line and Converted into Machine Understable Code (Executable or binary Code) and It is read by
OS and Processer and finally Gives Result.
=>Hence In Python Program execution, Compilation Process and Execution Process is taking place
Line by Line conversion and It is one of the Interpretation Based Programming Language.
--------------------------------------------------------------------
Definition of PVM ( Python Virtual Machine )
--------------------------------------------------------------------
=>PVM is one program in Python Software and whose role is to read LINE by LINE of Byte Code
and Converted into Machine Understable Code (Executable or binary Code)

DAY – 8

High level

– 1. low level programming language


– 2. High level programming language
=======================================
– 6. High Level Programming
– =======================================
– =>In this context, we have two types of languages. They are

– 1. Low Level Programming Languages
– 2. High Level Programming Languages
– -----------------------------------------------------------------
– 1. Low Level Programming Languages:
– -----------------------------------------------------------------
– =>In Low Programming Languages, data is always stored in the form of low level values such
as Binary data, Octal Data and Hexa Decimal data. These Number System are not directly
understandable end-users

– Example : a=0b1010101010
– b=0xBEE
– c=0o23
– -----------------------------------------------------------------
– 2. High Level Programming Languages
– -----------------------------------------------------------------
– =>In these languages, Internally, Even the programmer specifies the data in the form of Low
Level Format such Binary data, Octal Data and Hexa Decimal data, automatically Python
Programming Language Execution Environment Converts into High Level data, which is
understandable by end-users . Hence Python is one of the High Level Programming
Languages.

– Examples:
– ----------------
– >>> a=0b101010111110000
– >>> b=0b10101111000
– >>> print(a)-----------------------22000
– >>> print(b)----------------------1400
– >>> a=0xBEE
– >>> print(a)-----------------------3054
– >>> bin(22000)-----------------'0b101010111110000'
– >>> hex(3054)----------------'0xbee'
– ======================================x============================
====

Day – 9
Data Reprsentating in Python
-----------------------------------.

--Importants of Data in Applications development


--- Types of Literals
----Important of Identifiers /Variables
-----Rules of Using Identifiers / Variables in Python

-----------.
Data – Banking Sector
Insurance domain
Amazon ,Flipkart ----etc.

----------------------------------------.
Information:

FN latime
xy 00:00
----------------.

What is Literal ---Types of Literals


-----------------------------------------------.
= Literals are nothing but input values passing as input to the program
= in Other words , the values passing to the program as an input are called literals .
= in python programming , Primarillay ,we have 5 types of literals , they are

1. integer literals / values


2. floating point literaks
3. string literals
4. boolean literals
5. collection literals
------------------------------------------.
Identifiers and Variables in Python Programming
In Python, identifiers and variables are fundamental concepts that play a crucial role in writing
clean, efficient, and readable code. Here's a concise explanation of their importance:

1. Identifiers
• Definition: Identifiers are the names used to identify variables, functions, classes, or other
objects in Python.
• Rules for Identifiers:
• Must begin with a letter (A-Z or a-z) or an underscore _.
• Can contain letters, digits (0-9), and underscores but cannot have special characters
like @, $, %, etc.
• Cannot be a Python keyword (e.g., if, else, while, etc.).
• Case-sensitive (myVar and myvar are different).
• Should be meaningful and descriptive for better readability.
• Importance:
• Helps in organizing and structuring code.
• Makes the code self-explanatory and easier to debug.
• Adhering to naming conventions improves collaboration in team projects.

2. Variables
• Definition: Variables are containers for storing data values. They are essentially identifiers
that hold data.
• Key Features:
• Python is dynamically typed, so you don’t need to declare the type of a variable
explicitly.
• Variables can store different types of data (e.g., integers, strings, lists, etc.).
• Importance:
• Enables data manipulation and storage during program execution.
• Simplifies code by allowing reuse of values without hardcoding.
• Enhances flexibility, as variables can change their values dynamically.

Best Practices for Identifiers and Variables


1. Use descriptive names (e.g., student_name instead of sn).
2. Follow PEP 8 guidelines:
• Use snake_case for variables and functions (e.g., total_sum).
• Use PascalCase for class names (e.g., StudentRecord).
3. Avoid single-character names unless in loops (e.g., i, j).
4. Use constants (all uppercase) for fixed values (e.g., PI = 3.14).
By following these principles, you can write Python code that is clean, efficient, and easy to
understand!

Data type in Python

int
float
complex
bool

str
bytes
bytearry
Day – 10

=================================================
Data Types in Python
=================================================
=>The purpose of DataTypes in Python is that " To allocate Sufficient Amount of Memory Space in
main
memory of computer and Inputs can stored".
=>Python Programming Provides 14 data types and Classified into 6 Categories. They are
I. Fundamental Cattegory Data Types.
1. int (immutable)
2. float (immutable)
3. bool (immutable)
4. complex (immutable)
II. Sequence Category Data Types
1. str (immutable)
2. bytes (immutable)
3. bytearray(mutable)
4. range (immutable)
III. List Category Data Types (Collection or Data Structures)
1. list (mutable)
2. tuple (immutable)
IV. Set Category Data Types (Collection or Data Structures)
1. set (mutable and immutable)
2. frozenset (immutable)
V. Dict Category Data Types (Collection or Data Structures)
1. dict (mutable)
VI. NoneType Category Data Type
1. NoneType

====================================================
I. Fundamental Category Data Types.
====================================================
=>The purpose of Fundamental Category Data Types is that " To Store Single Value".
=>In Python Programming, we have 4 data types in Fundamental Category. They are
1. int
2. float
3. bool
4. complex
===========================================
1. int
===========================================
Properties:
---------------------
=>'int' is one of the pre-defined class name and treated as Fundamental data Type.
=>The purpose of int data type is that " To store Integer data OR Whole Numbers OR Integral data
(Numbers without Decimal places)".
----------------
Examples:
------------------------------- -------------
Python Instructions Output
-------------------------------- -------------
>>> a=123
>>> print(a)----------------------------------123
>>> type(a)----------------------------------<class 'int'>
>>> id(a)-------------------------------------140716113134184
---------------------------------------
>>> sno=4567
>>> print(sno,type(sno))----------------4567 <class 'int'>
>>> print(id(sno))-------------------------1785231794992
-------------------------------------------------------------------------------
>>> print(sno,type(sno),id(sno))----4567 <class 'int'> 1785231794992
NOTE: One Can Use Class Names as Variable Names
Examples:
-----------------
>>> int=34 # here int is an object / variables
>>> print(int,type(int))---------------------34 <class 'int'>
------------------------------------------------------------------------------------------------------------------------
=>With int data type, In Python Programming, along with Integer data, we can also store Different
Number System Values. In Any Programming Lang, we have 4 Types of Number Systems. They
are

1. Decimal Number System


2. Binary Number System
3. Octal Number System
4. Hexa Decimal Number System
-------------------------------------------------------------------------------------------------------------------------
1. Decimal Number System
-------------------------------------------------------------------------------------------------------------------------
=>Decimal Number System is one the Default Number System in Programming lang
=>This Number System Contains
Digits: 0 1 2 3 4 5 6 7 8 9 ---Total digits=10
base: 10
=>base 10 Literals are callled Decimal Number System Values
-------------------------------------------------------------------------------------------------------------------------
2. Binary Number System
-------------------------------------------------------------------------------------------------------------------------
=>Binary Number System is Understandable by OS and Processor.
=>This Number System Contains
Digits: 0 1 ---Total digits=2
base: 2
=>base 2 Literals are callled Binary Number System Values
=>In python programming, To Store Binary Data, Binary data must be preceded by letter either 0b
OR 0B.
=>Syntax: varname=0b Binary data
(OR)
varname=0B Binary data

=>Even we store Binary data in Python Programming, Python Programming Execution environment
automatically / Implcitly Converted into Decimal Number System Types.

-----------------
Examples:
-----------------
>>> a=0b1101
>>> print(a,type(a))-------------------------13 <class 'int'>
-------------------------------
>>> a=0B1111
>>> print(a,type(a))-------------------------15 <class 'int'>
---------------------------------
>>> a=0B101110
>>> print(a,type(a))-------------------------46 <class 'int'>
--------------------------------
>>> bin(13)------------------------------------'0b1101'
>>> bin(15)------------------------------------'0b1111'
>>> bin(46)------------------------------------'0b101110'
NOTE: bin() is used converting any number system data into Binary Number System Type.
------------------------------------------------------------------------------------------------------------------------
3. Octal Number System
-------------------------------------------------------------------------------------------------------------------------
=>Octal Number System is Understandable by Micro processor Kits --8086
=>This Number System Contains
Digits: 0 1 2 3 4 5 6 7 -----Total digits=8
base:8
=>base 8 Literals are callled Octal Number System Values
=>In python programming, To Store Octal Data, Octal data must be preceded by letter either 0o OR
0O.
=>Syntax: varname=0o Octal data
(OR)
varname=0O Octal data

=>Even we store Octal data in Python Programming, Python Programming Execution environment
automatically / Implcitly Converted into Decimal Number System Types.
Examples:
-------------------
>>> a=0o33
>>> print(a,type(a))----------------------27 <class 'int'>
>>> a=0O123
>>> print(a,type(a))---------------------83 <class 'int'>
>>> a=0o128--------------------------------SyntaxError: invalid digit '8' in octal literal
NOTE:
---------------
NOTE: oct() is used converting any number system data into Octal Number System Type.
Examples:
-------------------
>>> oct(27)-----------------'0o33'
>>> oct(83)----------------'0o123'
-------------------------------------------------------------------------------------------------------------------------
4. Hexa Decimal Number System
-------------------------------------------------------------------------------------------------------------------------
=>Hexa Decimal Number System used in development OSes
=>This Number System Contains
Digits: 0 1 2 3 4 5 6 7 8 9
A(10) B(11) C(12) D(13) E(14) F(15)-----Total ---16

=>Base 16 Literals are callled Hexa Decimal Number System Values


=>In python programming, To Store Hexa Decimal Data, Hexa Decimal data must be preceded by
letter either 0x OR 0X.
=>Syntax: varname=0x Hexa Decimal Data
(OR)
varname=0X Hexa Decimal data
=>Even we store Hexa Decimal data in Python Programming, Python Programming Execution
environment automatically / Implcitly Converted into Decimal Number System Types.
----------------------------------
Examples:
----------------------------------
>>> a=0xAC
>>> print(a,type(a))-------------------------------172 <class 'int'>
>>> a=0xBEE
>>> print(a,type(a))-------------------------------3054 <class 'int'>
>>> a=0XFaCe
>>> print(a,type(a))-------------------------------64206 <class 'int'>
>>> a=0xACCER-----------------------SyntaxError: invalid hexadecimal literal
>>> a=0xBEEK---------SyntaxError: invalid hexadecimal literal
NOTE: hex() is used converting any number system data into Hexa Decimal Number System Type.
>>> hex(172)----------------------------------------'0xac'
>>> hex(3054)--------------------------------------'0xbee'
>>> hex(64206)------------------------------------'0xface'
-------------------------------------------------------------------------------------------------------------------------
Special Points:
--------------------------------
>>> a=0b1010
>>> b=oct(a)
>>> print(b,type(b))------------0o12 <class 'str'>
-------------------------
>>> a=0xF
>>> c=oct(a)
>>> print(c,type(c))--------------0o17 <class 'str'>
-----------------------------------------
>>> a=23
>>> d=oct(a)
>>> print(d,type(d))------------0o27 <class 'str'>
=================================================
>>> a=0o12
>>> b=bin(a)
>>> print(b)------------------0b1010
--------------------
>>> a=0xE
>>> b=bin(a)
>>> print(b)--------------------0b1110
------------------
>>> a=7
>>> b=bin(a)
>>> print(b)-------------------0b111
====================================================
>>> a=0b1111
>>> b=hex(a)
>>> print(b)--------------------0xf
---------------------
>>> a=0o17
>>> b=hex(a)
>>> print(b)------------------0xf
-------------------------------------------------------------------------
>>> a=14
>>> b=hex(a)
>>> print(b)------------------0xe
========================================================
Q) What are the Various Base Conversion Functions in Python?
ANS: the Various Base Conversion Functions in Python are

1) bin()
2) oct()
3) hex()
4)
==========================================================
2. float
==========================================================
Properties
--------------------------
=>'float' is one of the pre-defined class name and treated as Fundamental data Type.
=>The purpose of float data type is that "To store Real Constant values OR Float OR Double
Pointing
(Number with Decimal Places)".
=>float data type never allows us to represent / Store Binary,Octal and Hexa Decimal Values
=>float data type allows us to store Scientific Notation data. The Advantage of Scientific is that To
take Less Memory space for bigger floating point Values.
--------------------
Examples:
--------------------
>>> a=12.34
>>> print(a,type(a))-----------------------------------12.34 <class 'float'>
>>> b=0.9
>>> print(b,type(b))----------------------------------0.9 <class 'float'>
------------------------------
>>> a=10
>>> b=1.2
>>> c=a+b
>>> print(a,type(a))---------------------------------10 <class 'int'>
>>> print(b,type(b))--------------------------------1.2 <class 'float'>
>>> print(c,type(c))--------------------------------11.2 <class 'float'>
--------------------------------------------------------------------------------------------------------
>>> a=0b1010.0b1111------------SyntaxError: invalid decimal literal
>>> a=0o13.0o23----------------SyntaxError: invalid decimal literal
>>> a=0xAC.0XBEE------------SyntaxError: invalid decimal literal
>>> a=0b1010.0xAC------------SyntaxError: invalid decimal literal
>>> a=0o12.0b1010------------SyntaxError: invalid decimal literal
--------------------------------------------------------------------------------------------------------
>>> a=3e2
>>> print(a,type(a))--------------------300.0 <class 'float'>
----------------------------------
>>> a=4e-2
>>> print(a,type(a))---------------0.04 <class 'float'>
-----------------------------------------------------------
>>> a=0.00000000000000000000000000000000000000000000006
>>> print(a,type(a))---------6e-47 <class 'float'>
======================================
3. bool
========================================
=>'bool' is one of the pre-defined class name and treated as Fundamental data Type.
=>The purpose of bool data type is that "To Store True False Values".
=>In Python Programming True, False are Called Keywords and It is treated as values of bool data
type.
=>In Python Programming, Internally, The value of True is treated as 1 and False is treated as 0.

Examples:
---------------------------------------
>>> a=True
>>> print(a,type(a))--------------------------------True <class 'bool'>
>>> b=False
>>> print(b,type(b))------------------------------False <class 'bool'>
------------------------------
>>> a=true--------------NameError: name 'true' is not defined
>>> a=false----------------------NameError: name 'false' is not defined
----------------------------------------------------------------------------------------------------------
>>> a=True
>>> b=False
>>> print(a+b)------------------------1
>>> print(a-b)------------------------1
>>> print(2*True+True+False)------------3
>>> print(2+True*3+False)-------------5
>>> print(0b1010-True+2*True)----------11
>>> print(True/True)----------------------1.0
>>> print(True//True)------------------------1
>>> print(False//True)----------------------0
#Most Imp
>>> print(True//False)---------------------------ZeroDivisionError: integer division or modulo by zero
======================================x=================================
======== .
````````````````````````
Day -1 2

================================================
4. complex
================================================
Properties
-----------------
=>'complex' is one of the pre-defined class and treated as Fundamental data type.
=>The purpose of complex data type is that "To store Complex Values / Imaginary values".
=>The Gegeral Notation of compelx data type is given bellow
x+yj or x-yj
Here 'x' is called Real Part
Here 'y' is caqlled Imaginary part
and j Represents sqrt(-1) or sqr(j)=-1
=>Internally, Real and Imgainary parts of Complex Object are treated as float data type
=>To Extract the real and Imginary parts of Complex object, we have 2 pre-defined attributes. They
are
1) real
2) imag

Syntax: complexobj.real------>Gives Real Part of Complex object


complexobj.imag----->Gives Imaginary Part of Complex Object
=>On the object of complex data type, we can perform various Arithmetic Operation such as
Addition, Substraction, Multiplication..etc
-------------------
Examples:
-------------------
>>> a=2+3j
>>> print(a,type(a))----------------------------------(2+3j) <class 'complex'>
>>> b=-2-4j
>>> print(b,type(b))--------------------------------(-2-4j) <class 'complex'>
>>> a=1.2+3.4j
>>> print(a,type(a))--------------------------------(1.2+3.4j) <class 'complex'>
>>> b=-2.3-4.5j
>>> print(b,type(b))-------------------------------(-2.3-4.5j) <class 'complex'>
>>> a=12+4.5j
>>> print(a,type(a))-------------------------------(12+4.5j) <class 'complex'>
>>> b=-12.5-4j
>>> print(b,type(b))------------------------------(-12.5-4j) <class 'complex'>
---------------------------------------------
>>> a=2j
>>> print(a,type(a))------------------2j <class 'complex'>
>>> b=-5j
>>> print(b,type(b))-----------------(-0-5j) <class 'complex'>
>>> a=2.3j
>>> print(a,type(a))-----------------2.3j <class 'complex'>
>>> b=-2.6j
>>> print(b,type(b))------------- (-0-2.6j) <class 'complex'>
----------------------------------------------------------------------------------------
>>> a=10+3j
>>> print(a,type(a))------------------(10+3j) <class 'complex'>
>>> print(a.real)---------------------- 10.0
>>> print(a.imag)-------------------- 3.0
>>> b=2.5+4.6j
>>> print(b,type(b))--------------- (2.5+4.6j) <class 'complex'>
>>> print(b.real)------------------- 2.5
>>> print(b.imag)------------------ 4.6
----------------------------------------------------------------------------------------
>>> a=-3.5j
>>> print(a,type(a))------------------- (-0-3.5j) <class 'complex'>
>>> print(a.real)----------------------- -0.0
>>> a=2.5j
>>> print(a,type(a))------------------- 2.5j <class 'complex'>
>>> print(a.real)------------------------ 0.0
>>> print(a.imag)---------------------- 2.5
>>> a=-1+4.5j
>>> print(a,type(a))----------------- (-1+4.5j) <class 'complex'>
>>> print(a.real)--------------------- -1.0
>>> print(a.imag)--------------------- 4.5
---------------------------------------------------------------------------------------------------------
>>> a=2+3j
>>> b=3+8j
>>> c=a+b
>>> print(c,type(c))-----------------(5+11j) <class 'complex'>
----------------------
>>> d=a-b
>>> print(d,type(d))------------(-1-5j) <class 'complex'>
-----------------
>>> e=a*b
>>> print(e,type(e))-----------(-18+25j) <class 'complex'>
==================================x=====================================
==.
==================================================
II. Sequence Category Data Types
==================================================
=>The purpose of Sequence Category Data Types is that "To store Sequence of values".
=>In Python programming, we have 4 data types in Sequence Category . They are

1. str
2. bytes
3. bytearray
4. range
========================================================================
.=================================================
1. str ( Part-1 )
=================================================
iNDEX
-----------
=>Purpose of str
=>Definition of str
=>Types of strs
=>Notation used for storing str data
=>Memory Management of str data
=>Operations on str Data
a) Indexing
b) Slicing
=>Programmin Examples
--------------------------------------------------------------------------------------------------------------------------
--------------
Properties
----------------------------
=>'str' is one of the pre-defined class and treated as Sequence Data Type.
=>The purpose of str data type is that "To store String data or text data or Alphanumeric data or
numeric data or special symbols within double Quotes or single quotes or tripple double quotes and
tripple single quotes. "
------------------------
=>Def. of str:
-----------------------
=>str is a collection of Characters or Alphanumeric data or numeric data or any type of data enclosed
within double Quotes or single quotes or tripple double quotes and tripple single quotes. "
----------------------------
Types of Str data
-----------------------------
=>In Python Programming, we have two types of Str Data. They are
1. Single Line String Data
2. Multi Line String Data
-----------------------------------------
1. Single Line String Data:
-----------------------------------------
=>Syntax1:- varname=" Single Line String Data "
(OR)
=>Syntax2:- varname=' Single Line String Data '
=>With the help double Quotes (" ") and single Quotes (' ') we can store single line str data only but
not possible to store multi line string data.
---------------------------------------------------------------------------------------------------------------------
2. Multi Line String Data:
-----------------------------------------
=>Syntax1:- varname=" " " String Data1
String Data2
------------------
String data-n " " "

(OR)

=>Syntax2:- varname=' ' ' String Data1


String Data2
------------------
String data-n ' ' '

=>With the help OF tripple double Quotes (" " " " " ") and Tripple single Quotes (' ' ' ' ' ') we can
store single line str data and multi line string data.
--------------------------------------------------------------------------------------------------------------------------
----------------
Examples:
--------------------------------------------------------------------------------------------------------------------------
------------
>>> s1="Python"
>>> print(s1,type(s1))--------------Python <class 'str'>
>>> s2='Python'
>>> print(s2,type(s2))-------------Python <class 'str'>
>>> s3='A'
>>> print(s3,type(s3))-----------A <class 'str'>
>>> s4="A"
>>> print(s4,type(s4))--------------A <class 'str'>
------------------------------
>>> s5="Python3.10"
>>> print(s5,type(s5))--------------Python3.10 <class 'str'>
>>> s6="123456"
>>> print(s6,type(s6))----------123456 <class 'str'>
>>> s7="Python Programming 1234$Rossum_Guido"
>>> print(s7,type(s7))----------Python Programming 1234$Rossum_Guido <class 'str'>
---------------------------
>>> addr1= "Guido van Rossum
------------------------------
SyntaxError: unterminated string literal (detected at line 1)
>>> addr1= ' Guido van Rossum
-----------------------------
SyntaxError: unterminated string literal (detected at line 1)
-------------------------------------
>>> addr1=" " "Guido van Rossum
... HNO:3-4,Hill Side
... Python Software Foundation
... Nether Lands-56"""
>>> print(addr1,type(addr1))
Guido van Rossum
HNO:3-4,Hill Side
Python Software Foundation
Nether Lands-56 <class 'str'>
-------------------
>>> addr2=' ' 'Travis Oliphant
... HNO:23-45, Sea Side
... Numpy Organization
... nethr lands-67 '''
>>> print(addr2,type(addr2))
Travis Oliphant
HNO:23-45, Sea Side
Numpy Organization
nethr lands-67 <class 'str'>
------------------------------------------
>>> s7=" " " Python " " "
>>> print(s7,type(s7))--------------Python <class 'str'>
>>> s8=' ' ' Python ' ' '
>>> print(s8,type(s8))-----------------Python <class 'str'>
>>> s9=" " " Z " " "
>>> print(s9,type(s9))-------------Z <class 'str'>
>>> s10=' ' ' K ' ' '
>>> print(s10,type(s10))------------K <class 'str'>
------------------------
>>> s1="Python Programmin"
>>> print(s1,type(s1))--------------------Python Programmin <class 'str'>
>>> s1--------------------------------------- ' Python Programmin '
>>> s7=" " " Python " " "
>>> print(s7,type(s7))------------------Python <class 'str'>
>>> s7-------------------------------------- ' Python '
-------------------------------
>>> s1=" " "Python is an oop lang
... python is also fun Prog lang
... Python is also Modular Prog lang " " "
>>> print(s1,type(s1))
Python is an oop lang
python is also fun Prog lang
Python is also Modular Prog lang <class 'str'>
>>> s1
' Python is an oop lang \n python is also fun Prog lang \n Python is also Modular Prog
lang '
=================================x======================================.

Day – 1 3

==============================================
Operations on str Data
==============================================
=>On str data, we can perform Two Types of Operations. They are
1. Indexing
2. Slicing
--------------------------------------------------------------------------------------------------------------------------
--------------
1. Indexing
--------------------------------------------------------------------------------------------------------------------------
--------------
=>The Process of Obtaining Single Value from given Main Str object is called Indexing
=>Syntax: strobj[Index]
=>here strobj is an object of <class,'str'>
=>index represents Either +Ve Index or -Ve Index
=>If we enter Valid Index value then we get Corresponding Inxdexed Value.
=>If we enter InValid Index value then we get IndexError.
---------------------------
Examples
---------------------------
>>> s="PYTHON"
>>> print(s,type(s))-------------------PYTHON <class 'str'>
>>> print(s[0])----------------------P
>>> print(s[-6])---------------------P
>>> print(s[-1])--------------------N
>>> print(s[5])---------------------N
>>> print(s[3])--------------------H
>>> print(s[-3])-------------------H
>>> print(s[-2])-------------------O
>>> print(s[-4])-------------------T
>>> print(s[-5])------------------Y
>>> print(s[2])-------------------T
>>> s[2]----------------------------'T'
>>> s[-2]--------------------------'O'
>>> print(s[8])-------------------IndexError: string index out of range
>>> print(s[-12])----------------IndexError: string index out of range
---------------------
>>> s="123453456"
>>> print(s,type(s))---------------123453456 <class 'str'>
>>> s[2]----------------------'3'
>>> s[-1]-------------------'6'
>>> s[0]--------------------'1'
>>> s[len(s)-1]-------------'6'
>>> s[-len(s)]---------------'1'
--------------------------------------------
>>> s="JAVA"
>>> print(s,type(s))-------------JAVA <class 'str'>
>>> len(s)-------------------------4
>>> s[len(s)-1]-----------------'A'
>>> s[-len(s)]------------------'J'
>>> s[len(s)-len(s)]-------------'J'
>>> s[-2]---------------------------'V'
>>> s[2]----------------------------'V'
>>> s[len(s)]---------------------------------IndexError: string index out of range
---------------------------------------------------
>>> s="MISSISSIPPI"
>>> s[len(s)-1]----------------'I'
>>> s[-len(s)]-----------------'M'
>>> s[len(s)]-----------------------IndexError: string index out of range
--------------------------------------------------------------------------------------------------------------------------
--------------
2.Slicing
--------------------------------------------------------------------------------------------------------------------------
--------------
=>The Process obtaining Range of Values OR Sub String from Given main Str Object is called
Slicing.
=>To Perform Slicing Operations, we have 5 Syntaxes. They are
--------------------------------------------------------------------------------------------------------------------------
--------------
Syntax1: strobj[BEGIN:END]
--------------------------------------------------------------------------------------------------------------------------
-------------
=>This Syntax generates Range of Values OR Sub String from BEGIN Index to END-1 Index
provided
BEGIN<END Otherwise we never get any result OR Space OR ' ' as a Result
Examples:
-----------------------------
>>> s="PYTHON"
>>> print(s,type(s))-------------------PYTHON <class 'str'>
>>> s[0:3]--------------------------------'PYT'
>>> s[2:6]--------------------------------'THON'
>>> s[1:6]---------------------------------'YTHON'
>>> s[2:1]---------------------------------' '
>>> s[0:6]----------------------------------'PYTHON'
----------------------------
>>> s="PYTHON"
>>> print(s,type(s))-----------------PYTHON <class 'str'>
>>> s[-6:-2]---------------------------'PYTH'
>>> s[-3:-1]---------------------------'HO'
>>> s[-6:-3]---------------------------'PYT'
>>> s[-3:-6]---------------------------' '
>>> s[-6:-1]---------------------------'PYTHO'
--------------------------------------------------------------------------------------------------
Sub Rule: strobj[BEGINPOSINDEX:ENDNEGATIVEINDEX]
--------------------------------------------------------------------------------------------------
=>This Syntax Gives Range of Characters from BEGINPOSINDEX to ENDNEGATIVEINDEX-1
provided
BEGINPOSINDEX > ENDNEGATIVEINDEX. Otherwise we get Space or NO Result OR ' ' as a
result.
-----------------
Examples
-----------------
>>> s="PYTHON"
>>> print(s,type(s))----------PYTHON <class 'str'>
>>> s[1:-2]-------------'YTH'
>>> s[2:-1]--------------'THO'
>>> s[-3:1]--------------' '
--------------------------------------------------------------------------------------------------------------------------
--------------
Syntax:2 : strobj[BEGIN : ]
--------------------------------------------------------------------------------------------------------------------------
--------------
=>In This Syntax, we are Specifying BEGIN Index and we did't Specify END Index.
=>If we don't specify END Index then PVM Takes END Index as len(strobj)
(OR)
=>If we don't specify END Index then PVM Takes BEGIN INDEX Character to Last Character.
----------------
Examples:
----------------
>>> s="PYTHON"
>>> print(s,type(s))--------------PYTHON <class 'str'>
>>> s[2:]----------------------------'THON'
>>> s[0:]----------------------------'PYTHON'
>>> s[3:]----------------------------'HON'
>>> s[4:]----------------------------'ON'
>>> s[1:]---------------------------'YTHON'
-------------------------------
>>> s="PYTHON"
>>> print(s,type(s))----------------PYTHON <class 'str'>
>>> s[-3:]-----------------------------'HON'
>>> s[-2:]-----------------------------'ON'
>>> s[-6:]-----------------------------'PYTHON'
>>> s[-5:]----------------------------'YTHON'
>>> s[-4:]----------------------------'THON'
>>> s[-1:]----------------------------'N'
-----------------------------------------------------
Special Points
-----------------------------------------------------
>>> s="PYTHON"
>>> print(s,type(s))-----------------------PYTHON <class 'str'>
>>> s[-12:]-----------------------------------'PYTHON'
>>> s[-23:]----------------------------------'PYTHON'
>>> s[23:]----------------------------------' '
>>> s[2:4]---------------------------------- 'TH'
>>> s[12:44]------------------------------- ' '
>>> s[-66:-1]------------------------------ 'PYTHO'
>>> s[2:122]------------------------------ 'THON'
>>> s[2:-122]-------------------------------' '
>>> s[2:-1]----------------------------------'THO'
>>> s[2:-22]--------------------------------' '
--------------------------------------------------------------------------------------------------------------------------
---------------
Syntax3: strobj[ : End]
--------------------------------------------------------------------------------------------------------------------------
---------------
=>In This Syntax, we are Specifying END Index and we did't Specify BEGIN Index.
=>If we don't specify BEGIN Index then PVM Takes BEGIN Index as 0 OR -len(strobj)
(OR)
=>If we don't specify BEGIN Index then PVM Takes First Character to END-1 Index.
--------------------------------
Examples:
--------------------------------
>>> s="PYTHON"
>>> print(s,type(s))--------------PYTHON <class 'str'>
>>> s[:3]----------------------------'PYT'
>>> s[:6]----------------------------'PYTHON'
>>> s[:5]---------------------------'PYTHO'
>>> s[:4]---------------------------'PYTH'
------------------------------
>>> s="PYTHON"
>>> print(s,type(s))-------------PYTHON <class 'str'>
>>> s[:-3]---------------------------'PYT'
>>> s[:-2]--------------------------'PYTH'
>>> s[:-1]--------------------------'PYTHO'
>>> s[:-4]--------------------------'PY'
>>> s[:-5]---------------------------'P'
--------------------------------------------------------------------------------------------------------------------------
---------------
Syntax4: strobj[ : ]
--------------------------------------------------------------------------------------------------------------------------
---------------
=>In This Syntax, we are not Specifying BEGIN Index and END Index
=>If we don't specify BEGIN Index and END Index then PVM Takes BEGIN Index as 0 OR -
len(strobj) and
END Index as len(strobj) or -1
(OR)
=>If we don't specify BEGIN Index and END Index then PVM Takes from First Character(0th Index
or
-len(strobj) index ) to last Character ( len(strobj) or -1).
=>Hence This Syntax always gives Total String Data.
---------------------------------------------
Examples
---------------------------------------------
>>> s="PYTHON"
>>> print(s,type(s))-------------------PYTHON <class 'str'>
>>> s[:]-----------------------------------'PYTHON'
>>> s="JAVA PROG"
>>> print(s,type(s))-------------------JAVA PROG <class 'str'>
>>> s[:]----------------------------------'JAVA PROG'
>>> s[0:]--------------------------------'JAVA PROG'
>>> s[:len(s)]--------------------------'JAVA PROG'
>>> s[-len(s):]-------------------------'JAVA PROG'
NOTE: All the above Syntaxes are Extracting the data from strobj in Forward Direction with Default
Step value 1.
--------------------------------------------------------------------------------------------------------------------------
-----------------
Syntax 5: strobj[BEGIN: END : STEP]
--------------------------------------------------------------------------------------------------------------------------
-----
RULE-1: Here BEGIN, END and STEP Values can be either +VE or -VE
-------------

RULE-2: If STEP Value is +VE then PVM Takes the Range of Characters from BEGIN Index to
END-1
------------- Index in FORWARD Direction With Step Value provided BEGIN INDEX < END INDEX
Otherwise
we get Space or ' ' as a result
-------------
RULE-3: If STEP Value is -VE then PVM Takes the Range of Characters from BEGIN Index to
END+1
------------- Index in BACKWARD Direction With Step Value provided BEGIN INDEX > END
INDEX Otherwise we get Space or ' ' as a result
-------------
RULE-4 : In FORWARD Direction, If END Value is 0 Then we get Space or ' ' as a result
-------------

-------------
RULE-5: In BACKWARD Direction, If END Value is -1 Then we get Space or ' ' as a result
-------------
--------------------------------------------------------------------------------------------------------------------------
---
Examples: RULE-2
--------------------------------------------------------------------------------------------------------------------------
-
>>> s="PYTHON"
>>> print(s)-------------------------------PYTHON
>>> s[0:4]---------------------------------'PYTH'
>>> s[0:4:1]------------------------------'PYTH'
>>> s[2:6:1]------------------------------'THON'
>>> s[2:6:2]------------------------------'TO'
>>> s[0:6:2]-----------------------------'PTO'
>>> s[0:6:3]-----------------------------'PH'
>>> s[ : : ]--------------------------------'PYTHON'
>>> s[ : :2]--------------------------------'PTO'
>>> s[ : :3]--------------------------------'PH'
>>> s[-6:-1:2]----------------------------'PTO'
>>> s[-6: :]-------------------------------'PYTHON'
>>> s[:6:]---------------------------------'PYTHON'
>>> s[0:6:]-------------------------------'PYTHON'
>>> s[:-1:]-------------------------------'PYTHO'
----------------------------------------------------------------------------------------------------------
Examples: RULE-3
---------------------------------------------------------------------------------------------------------
>>> s="PYTHON"
>>> print(s)-----------------------------PYTHON
>>> s[::]---------------------------------'PYTHON'
>>> s[::1]-------------------------------'PYTHON'
>>> s[::-1]-------------------------------'NOHTYP'
>>> s[::-2]--------------------------------'NHY'
>>> s[0:6:-2]-----------------------------''
>>> s[5:0:-1]----------------------------'NOHTY'
>>> s[::-3]-------------------------------'NT'
>>> s[4: :-2]----------------------------'OTP'
>>> s[: :2]------------------------------'PTO'
>>> s[: :2][::-1]------------------------'OTP'
>>> s[-1:-7:-1]-------------------------'NOHTYP'
>>> s[-1::-1]---------------------------'NOHTYP'
>>> s[-1::-2]---------------------------'NHY'
>>> s[-2::-2]---------------------------'OTP'
>>> s[2:6:][::-1]----------------------'NOHT'
>>> s[2:6:]----------------------------'THON'
-------------------------------------------------------------------------------------------------------
Examples-------------RULE-4
-------------------------------------------------------------------------------------------------------
>>> s="PYTHON"
>>> print(s)-----------------------------PYTHON
>>> s[2:0:1]-----------------------------' '
>>> s[:0:1]------------------------------' '
>>> s="JAVA PROG"
>>> print(s)----------------------------JAVA PROG
>>> s[:0:1]-----------------------------''
>>> s[:0]------------------------------' '
>>> s[:0:3]--------------------------' '
-------------------------------------------------------------------------------------------------------
Examples-------------RULE-5
-------------------------------------------------------------------------------------------------------
>>> s="PYTHON"
>>> print(s)--------------------PYTHON
>>> s[::-1]---------------------'NOHTYP'
>>> s[ :-1:-1]------------------' '
>>> s[ :-1:-3]-----------------' '
>>> s[ :-1:-4]------------------' '
-------------------------------------------------------------------------------------------------------
Special Points
------------------------------------------------------------------------------------------------------
>>> "PYTHON"[::-1]----------------------'NOHTYP'
>>> "PYTHON"[::-1]=="PYTHON"-------------False
>>> "PYTHON"[::2]=="PYTHON"[::-1][::2]--------False
>>> "MOM"[::-1]=="MOM"----------------------True
>>> "MOM"[::-1]=="MOM"[::]-----------------True
>>> "LIRIL"[::-1]=="LIRIl"[::-1]--------------False
------------------------------------------------------------------------------------------------------
day – 14

===================================================
Mutability and Immutability objects
====================================================
--------------------------------
Mutable Object
--------------------------------
=>A Mutbale object is one, Which allows us to Perform the Changes / Modify / Update the values at
Same Memory Address
-----------------
Examples:
-----------------
=>bytearray,list,set,dict
--------------------------------
Immutable Object
--------------------------------
=>An Immutbale object is one, which will satisfy the following properties.
a) The value of Immutable object never allows us to Modify at same address
( OR Value of Immutable object can be modified and Modified value can be placed
at New Memory Address)
b) Immutable objects does not support Item Assigment

Examples: int, float, complex, bool, str, bytes, range,tuple,set,frozenset

DAY --- 15
----------------.
TYPE CASTING TECHNIQUES IN PYTHON PROGRAMMING
----------------------------------------------------------------------------------.

int

--------.

Typecasting in Python
Typecasting in Python refers to converting one data type into another. It is useful when you need to
perform operations that require specific data types. Python supports two types of typecasting:

1. Implicit Typecasting
• Python automatically converts one data type to another without user intervention.
• It typically happens when there is no risk of data loss.
Example:
Python

a = 5 # Integer
b = 2.5 # Float
result = a + b # Implicitly converts 'a' to float
print(result) # Output: 7.5
print(type(result)) # Output: <class 'float'>

2. Explicit Typecasting
• The user manually converts one data type to another using Python's built-in functions like
int(), float(), str(), etc.
• This is done when automatic conversion is not possible or desired.
Example:
Python

# Converting float to integer


x = 10.8
y = int(x) # Explicitly casting float to int
print(y) # Output: 10

# Converting integer to string


num = 123
text = str(num)
print(text) # Output: '123'
print(type(text)) # Output: <class 'str'>

Common Typecasting Functions


1. int() - Converts to integer.
2. float() - Converts to float.
3. str() - Converts to string.
4. list() - Converts to list.
5. tuple() - Converts to tuple.
6. set() - Converts to set.
Example:
Python

# Converting list to tuple


my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple) # Output: (1, 2, 3)

Typecasting is a powerful feature in Python that ensures flexibility and compatibility between
different data types.

===============================================
1. int()
===============================================
=>int() is used for Converting One Possible Type of Value into int type value.
-----------------
=>Syntax: varname=int(float / bool / complex / str)
--------------------------------------------------------------------------------------------------------------------------
-------------------
Example-1: float type value to int type---->Possible
--------------------------------------------------------------------------------------------------------------------------
-------------------
>>> a=12.34
>>> print(a,type(a))------------------12.34 <class 'float'>
>>> b=int(a)
>>> print(b,type(b))------------------12 <class 'int'>
-------------
>>> a=0.5
>>> print(a,type(a))---------------0.5 <class 'float'>
>>> b=int(a)
>>> print(b,type(b))--------------0 <class 'int'>
--------------------------------------------------------------------------------------------------------------------------
-------------------
Example-2: bool type value to int type---->Possible
--------------------------------------------------------------------------------------------------------------------------
-------------------
>>> a=True
>>> print(a,type(a))-----------------True <class 'bool'>
>>> b=int(a)
>>> print(b,type(b))----------------1 <class 'int'>
>>> a=False
>>> print(a,type(a))----------------False <class 'bool'>
>>> b=int(a)
>>> print(b,type(b))--------------0 <class 'int'>
--------------------------------------------------------------------------------------------------------------------------
-------------------
Example-3: complex type value to int type---->Not Possible
--------------------------------------------------------------------------------------------------------------------------
-------------------
>>> a=2+3j
>>> print(a,type(a))--------------(2+3j) <class 'complex'>
>>> b=int(a)------------------------TypeError: int() argument must be a string,
--------------------------------------------------------------------------------------------------------------------------
-------------------
Example-4: str type to int
--------------------------------------------------------------------------------------------------------------------------
-------------------
Case-1: Str int--------->int--->Possible
------------
>>> a="12"
>>> print(a,type(a))-----------12 <class 'str'>
>>> b=int(a)
>>> print(b,type(b))---------12 <class 'int'>
-----------------------------------------------------------
Case-2: str float------->int---->Not Possible
-----------
>>> a="12.34"
>>> print(a,type(a))---------------12.34 <class 'str'>
>>> b=int(a)-------------ValueError: invalid literal for int() with base 10: '12.34'
-----------------------------------------------------------
Case-3: str bool------>int------>Not Possible
-----------
>>> a="True"
>>> print(a,type(a))---------------True <class 'str'>
>>> b=int(a)---------------------------ValueError: invalid literal for int() with base 10: 'True'
-------------------
Case-4: str complex----->int------>Not Possible
-----------
>>> a="2+3j"
>>> print(a,type(a))---------------True <class 'str'>
>>> b=int(a)---------------------------ValueError: invalid literal for int() with base 10: 'True'
-----------------------------------------------------------
Case-4: Pure Str------>int--->Not Possible
------------------
>>> a="PYTHON"
>>> print(a,type(a))-------------PYTHON <class 'str'>
>>> b=int(a)-------------------------ValueError: invalid literal for int() with base 10: 'PYTHON'
==================================x=====================================
==.
==============================================
2. float()
===============================================
=>float() is used for Converting One Possible Type of Value into float type value.
-----------------
=>Syntax: varname=float(int / bool / complex / str)
--------------------------------------------------------------------------------------------------------------------------
----------------------
Example-1: int type--->float type----->Possible
--------------------------------------------------------------------------------------------------------------------------
----------------------
>>> a=100
>>> print(a,type(a))-----------------100 <class 'int'>
>>> b=float(a)
>>> print(b,type(b))----------------100.0 <class 'float'>
>>> a=0
>>> print(a,type(a))---------------0 <class 'int'>
>>> b=float(a)
>>> print(b,type(b))--------------0.0 <class 'float'>
--------------------------------------------------------------------------------------------------------------------------
----------------------
Example-2: bool type--->float type----->Possible
--------------------------------------------------------------------------------------------------------------------------
----------------------
>>> a=True
>>> print(a,type(a))------------True <class 'bool'>
>>> b=float(a)
>>> print(b,type(b))------------1.0 <class 'float'>
>>> a=False
>>> print(a,type(a))------------False <class 'bool'>
>>> b=float(a)
>>> print(b,type(b))-----------0.0 <class 'float'>
--------------------------------------------------------------------------------------------------------------------------
----------------------
Example-3: complex type--->float type----->Not Possible
--------------------------------------------------------------------------------------------------------------------------
----------------------
>>> a=2+3.5j
>>> print(a,type(a))--------(2+3.5j) <class 'complex'>
>>> b=float(a)---------TypeError: float() argument must be a string or a real number
--------------------------------------------------------------------------------------------------------------------------
----------------------
Example-4: str type--->float type
--------------------------------------------------------------------------------------------------------------------------
----------------------
Case-1: str int--->float--->Possible
-----------
>>> a="12"
>>> print(a,type(a))---------12 <class 'str'>
>>> b=float(a)
>>> print(b,type(b))---------12.0 <class 'float'>
---------------------------------------------------------------------
Case-2: str float--->float--->Possible
------------
>>> a="12.34"
>>> print(a,type(a))-----------12.34 <class 'str'>
>>> b=float(a)
>>> print(b,type(b))---------12.34 <class 'float'>
-------
>>> a="12.34.45"
>>> print(a,type(a))---------12.34.45 <class 'str'>
>>> b=float(a)---------------------ValueError: could not convert string to float: '12.34.45'
---------------------------------------------------------------------
Case-3: str bool--->float--->Not Possible
-----------
>>> a="True"
>>> print(a,type(a))----------------True <class 'str'>
>>> b=float(a)----------------------ValueError: could not convert string to float: 'True'
---------------------------------------------------------------------
Case-4: str complex--->float--->Not Possible
--------------
>>> a="2+3j"
>>> print(a,type(a))-----------2+3j <class 'str'>
>>> b=float(a)----------------ValueError: could not convert string to float: '2+3j'
---------------------------------------------------------------------
Case-5: Pure str--->float--->Not Possible
------------
>>> a="Python3.11"
>>> print(a,type(a))------------Python3.11 <class 'str'>
>>> b=float(a)------------------ValueError: could not convert string to float: 'Python3.11'
=============================x==========================================
===.

============================================
3. bool()
============================================
=>bool() is used for Converting One Possible Type of Value into bool type value.
-----------------
=>Syntax: varname=bool(int / float / complex / str)
-----------------
=>ALL NON-ZERO VALUES ARE TREATED AS TRUE
=>ALL ZERO VALUES ARE TREATED AS FALSE
--------------------------------------------------------------------------------------------------------------------------
--------------
Example1: int type--->bool type---->Possible
--------------------------------------------------------------------------------------------------------------------------
--------------
>>> a=123
>>> print(a,type(a))------------------123 <class 'int'>
>>> b=bool(a)
>>> print(b,type(b))-------------------True <class 'bool'>
>>> a=-234
>>> print(a,type(a))--------------- -234 <class 'int'>
>>> b=bool(a)
>>> print(b,type(b))---------------True <class 'bool'>
>>> a=0
>>> print(a,type(a))----------------0 <class 'int'>
>>> b=bool(a)
>>> print(b,type(b))--------------False <class 'bool'>
--------------------------------------------------------------------------------------------------------------------------
--------------
Example2: float type--->bool type---->Possible
--------------------------------------------------------------------------------------------------------------------------
--------------
>>> a=12.34
>>> print(a,type(a))-----------------12.34 <class 'float'>
>>> b=bool(a)
>>> print(b,type(b))---------------True <class 'bool'>
>>> a=0.00000000000000000000000000000000000000000000000001
>>> print(a,type(a))------------1e-50 <class 'float'>
>>> b=bool(a)
>>> print(b,type(b))------------True <class 'bool'>
>>> a=0.000000
>>> print(a,type(a))------------0.0 <class 'float'>
>>> b=bool(a)
>>> print(b,type(b))----------False <class 'bool'>
--------------------------------------------------------------------------------------------------------------------------
--------------
Example3: complex type--->bool type---->Possible
--------------------------------------------------------------------------------------------------------------------------
--------------
>>> a=2+3j
>>> print(a,type(a))-----------(2+3j) <class 'complex'>
>>> b=bool(a)
>>> print(b,type(b))-----------True <class 'bool'>
>>> a=0+0j
>>> print(a,type(a))-----------0j <class 'complex'>
>>> b=bool(a)
>>> print(b,type(b))----------False <class 'bool'>
--------------------------------------------------------------------------------------------------------------------------
--------------
Example4: str type--->bool type
--------------------------------------------------------------------------------------------------------------------------
--------------
Case-1: str int---->bool--->Possible
------------
>>> a="123"
>>> print(a,type(a))------------------123 <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))------------------True <class 'bool'>
>>> a="0"
>>> print(a,type(a))----------------0 <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))---------------True <class 'bool'>
---------------------------------------------------------------------
Case-2: str float ---->bool--->Possible
----------------------
>>> a="12.45"
>>> print(a,type(a))-------------12.45 <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))-------------True <class 'bool'>
>>> a="0.0"
>>> print(a,type(a))------------0.0 <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))----------True <class 'bool'>
---------------------------------------------------------------------
Case-3: str bool ---->bool--->Possible
------------
>>> a="True"
>>> print(a,type(a))--------------True <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))--------------True <class 'bool'>
>>> a="False"
>>> print(a,type(a))------------------False <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))-----------------True <class 'bool'>
---------------------------------------------------------------------
Case-4: str complex ---->bool--->Possible
-----------
>>> a="4+5.6j"
>>> print(a,type(a))---------------4+5.6j <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))--------------True <class 'bool'>
----------------------------------------------------------------------
Case-5: pure str ---->bool--->Possible
--------------
>>> a="Python"
>>> print(a,type(a))---------------------Python <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))-------------------True <class 'bool'>
>>> a=" "
>>> print(a,type(a))------- space <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))------------- True <class 'bool'>
------------
>>> a=""
>>> print(a,type(a)) "" <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))-----------False <class 'bool'> (bcoz len(a) is zero)
-----------------------------------------------------------------------------------------------------------.

============================================
4. complex()
============================================
=>complex() is used for Converting One Possible Type of Value into compelx type value.
-----------------
=>Syntax: varname=complex(int / float / bool / str)
--------------------------------------------------------------------------------------------------------------------------
-------------------
Example-1: int type---->complex type---->Possible
--------------------------------------------------------------------------------------------------------------------------
-------------------
>>> a=12
>>> print(a,type(a))-------------12 <class 'int'>
>>> b=complex(a)
>>> print(b,type(b))-------------(12+0j) <class 'complex'>
--------------------------------------------------------------------------------------------------------------------------
-------------------
Example-2: float type---->complex type---->Possible
--------------------------------------------------------------------------------------------------------------------------
-------------------
>>> a=3.4
>>> print(a,type(a))-------------3.4 <class 'float'>
>>> b=complex(a)
>>> print(b,type(b))------------(3.4+0j) <class 'complex'>
--------------------------------------------------------------------------------------------------------------------------
-------------------
Example-3: bool type---->complex type---->Possible
--------------------------------------------------------------------------------------------------------------------------
-------------------
>>> a=True
>>> print(a,type(a))----------------True <class 'bool'>
>>> b=complex(a)
>>> print(b,type(b))---------------(1+0j) <class 'complex'>
>>> a=False
>>> print(a,type(a))---------------False <class 'bool'>
>>> b=complex(a)
>>> print(b,type(b))-------------0j <class 'complex'>
--------------------------------------------------------------------------------------------------------------------------
-------------------
Example-4: str type---->complex type
--------------------------------------------------------------------------------------------------------------------------
-------------------
Case-1: str int---->complex--->Possible
------------
>>> a="4"
>>> print(a,type(a))-------------4 <class 'str'>
>>> b=complex(a)
>>> print(b,type(b))----------(4+0j) <class 'complex'>
--------------------------------------------------------------------------
Case-2: str float---->complex--->Possible
------------
>>> a="3.4"
>>> print(a,type(a))-----------3.4 <class 'float'>
>>> b=complex(a)
>>> print(b,type(b))-----------(3.4+0j) <class 'complex'>
--------------------------------------------------------------------------
Case-3: str bool---->complex--->
-------------
>>> a="True"
>>> print(a,type(a))--------------True <class 'str'>
>>> b=complex(a)---------------ValueError: complex() arg is a malformed string
--------------------------------------------------------------------------
Case-4: str complex---->complex--->Possible
----------
>>> a="2.3+4.5j"
>>> print(a,type(a))----------2.3+4.5j <class 'str'>
>>> b=complex(a)
>>> print(b,type(b))------------(2.3+4.5j) <class 'complex'>
>>> a="2.3+4.5i"
>>> print(a,type(a))-----------2.3+4.5i <class 'str'>
>>> b=complex(a)-------------ValueError: complex() arg is a malformed string
--------------------------------------------------------------------------
Case-5: pure str---->complex--->Not Possible
-----------
>>> a="python+3j"
>>> print(a,type(a))-------------python+3j <class 'str'>
>>> b=complex(a)-------------------ValueError: complex() arg is a malformed string
===================================================
5. str()
===================================================
=>str() is used converting all types of values into str type.
-------------------
Syntax: varname=str(int/float/bool/complex)
-------------------
--------------------------------------------------------------------------------------------------------------------------
-------------
Examples:
--------------------------------------------------------------------------------------------------------------------------
-------------
>>> a=123
>>> print(a,type(a))------------------123 <class 'int'>
>>> b=str(a)
>>> print(b,type(b))----------------123 <class 'str'>
>>> b---------------------------------- '123'
-----------------------
>>> a=23.45
>>> print(a,type(a))-------------23.45 <class 'float'>
>>> b=str(a)
>>> print(b,type(b))-----------23.45 <class 'str'>
>>> b------------------------------ '23.45'
-------------------------
>>> a=True
>>> print(a,type(a))----------True <class 'bool'>
>>> b=str(a)
>>> print(b,type(b))---------True <class 'str'>
>>> b-----------------------------'True'
------------------------------
>>> a=2.5+6.7j
>>> print(a,type(a))--------------(2.5+6.7j) <class 'complex'>
>>> b=str(a)
>>> print(b,type(b))-------------(2.5+6.7j) <class 'str'>
>>> b--------------------------------- '(2.5+6.7j)'
========================================================================
========

day --- 16

===================================================
2. bytes
====================================================
Properties
------------------
=>'bytes' is one of the pre-defined class name and treated as Sequence Data Type.
=>The purpose of bytes data type is that "To organize the Numerical Integer values ranges from
(0,256) for the implementation of End-to-End Encryption".
=>bytes data type does not contains any symbolic notations for oraganizing (0,256) data. But we can
convert any type of Value(s) into bytes type by using bytes()
=>Syntax: varname=bytes(object)
=>An object of bytes belongs to immutable bcoz bytes object does not support Item Assigment.
=>On the object of bytes, we can perform both Indexing and Slicing Operations.
=>An object of bytes maintains Insertion Order (Which is nothing but, whatever the order we insert
the data, In the same order data will be displayed).
--------------------------------------------------------------------------------------------------------------------------
-----------------
Examples
--------------------------------------------------------------------------------------------------------------------------
-----------------
>>> lst=[10,34,56,100,256,0,102]
>>> print(lst,type(lst))----------------------[10, 34, 56, 100, 256, 0, 102] <class 'list'>
>>> b=bytes(lst)----------------------------ValueError: bytes must be in range(0, 256)
>>> lst=[10,-34,56,100,255,0,102]
>>> print(lst,type(lst))-------------------[10, -34, 56, 100, 255, 0, 102] <class 'list'>
>>> b=bytes(lst)--------------------------ValueError: bytes must be in range(0, 256)
>>> lst=[10,34,56,100,255,0,102]
>>> print(lst,type(lst))-------------------[10, 34, 56, 100, 255, 0, 102] <class 'list'>
>>> b=bytes(lst)
>>> print(b,type(b))---------------------b'\n"8d\xff\x00f' <class 'bytes'>
>>> for val in b:
... print(val)
...
10
34
56
100
255
0
102

>>> print(b,type(b))----------------b'\n"8d\xff\x00f' <class 'bytes'>


>>> print(b[0])--------------------10
>>> print(b[-1])-------------------102
>>> print(b[0:4])--------------- b'\n"8d'
>>> for val in b[0:4]:
... print(val)
...
10
34
56
100
>>> b[0]----------------------------10
>>> b[0]=123---------------TypeError: 'bytes' object does not support item assignment
==============================x=========================================
======

====================================================
3. bytearray
====================================================
Properties
------------------
=>'bytearray' is one of the pre-defined class name and treated as Sequence Data Type.
=>The purpose of bytearray data type is that "To organize the Numerical Integer values ranges from
(0,256) for the implementation of End-to-End Encryption".
=>bytearray data type does not contains any symbolic notations for oraganizing (0,256) data. But we
can convert any type of Value(s) into bytearray type by using bytearray()
=>Syntax: varname=bytearray(object)
=>An object of bytearray belongs to mutable bcoz bytearray object supports Item Assigment.
=>On the object of bytearray, we can perform both Indexing and Slicing Operations.
=>An object of bytearray maintains Insertion Order (Which is nothing but, whatever the order we
insert the data, In the same order data will be displayed).
--------------------------------------------------------------------------------------------------------------------------
------------------
NOTE: The Functionality of bytes and bytearray are exactly same but bytes object belongs to
Immutable bcoz bytes object does not support Item assigment where bytearray object blongs to
Mutable bcoz bytearray object supports Item Assigment.
--------------------------------------------------------------------------------------------------------------------------
------------------
Examples:
--------------------------------------------------------------------------------------------------------------------------
------------------
>>> tpl=(10,34,56,100,256,0,102)
>>> print(tpl,type(tpl))-----------------(10, 34, 56, 100, 256, 0, 102) <class 'tuple'>
>>> ba=bytearray(tpl)--------------------ValueError: byte must be in range(0, 256)
>>> tpl=(-10,34,56,100,255,0,102)
>>> print(tpl,type(tpl))-------(-10, 34, 56, 100, 255, 0, 102) <class 'tuple'>
>>> ba=bytearray(tpl)-------------ValueError: byte must be in range(0, 256)
-------------------------
>>> tpl=(10,34,56,100,255,0,102)
>>> print(tpl,type(tpl))------------(10, 34, 56, 100, 255, 0, 102) <class 'tuple'>
>>> ba=bytearray(tpl)
>>> print(ba,type(ba))------------bytearray(b'\n"8d\xff\x00f') <class 'bytearray'>
-------------------------------
>>> tpl=(10,34,56,100,255,0,102)
>>> print(tpl,type(tpl))-----------------(10, 34, 56, 100, 255, 0, 102) <class 'tuple'>
>>> ba=bytearray(tpl)
>>> print(ba,type(ba))---------------------bytearray(b'\n"8d\xff\x00f') <class 'bytearray'>
>>> for val in ba:
... print(val)
...
10
34
56
100
255
0
102
>>> for val in ba[::-1]:
... print(val)
...
102
0
255
100
56
34
10
>>> for val in ba:
... print(val)
...
10
34
56
100
255
0
102
>>> print(ba,type(ba),id(ba))---------bytearray(b'\n"8d\xff\x00f') <class 'bytearray'> 2149788291504
>>> ba[0]--------------10
>>> ba[-1]------------102
>>> ba[0]=123 # Updating / item assoigment on bytearray object--allowed
>>> for val in ba:
... print(val)
...
123
34
56
100
255
0
102
>>> print(ba,type(ba),id(ba))-----bytearray(b'{"8d\xff\x00f') <class 'bytearray'> 2149788291504
------------------------------------------
>>> b=bytes(ba) # Converting bytearray into bytes
>>> print(b,type(b))---------------b'{"8d\xff\x00f' <class 'bytes'>
>>> for val in b:
... print(val)
...
123
34
56
100
255
0
102
>>> b[0]---------------------123
>>> b[0]=12------TypeError: 'bytes' object does not support item assignment
>>> x=bytearray(b) # Converting bytes into bytearray
>>> print(x,type(x),id(x))----bytearray(b'{"8d\xff\x00f') <class 'bytearray'> 2149788291888
>>> for v in x:
... print(v)
...
123
34
56
100
255
0
102
>>> x[1]----------------------34
>>> x[1]=234
>>> for v in x:
... print(v)
...
123
234
56
100
255
0
102
>>> print(x,type(x),id(x))-----bytearray(b'{\xea8d\xff\x00f') <class 'bytearray'> 2149788291888
--------------------------------------------------------------------------------------------------------------------------
------------------

==============================================
4. range
==============================================
Properties
-------------------
=>'range' is one of the pre-defined class and treated as Sequence data type
=>The purpose of range data type is that "To Store Sequence of Numerical Integer Values with Equal
Interval of Value."
=>An object of range belongs to Immutable bcoz range object does not support Item Assignment.
=>On the object of range, we can perform Both Indexing Slicing Operations
=>The range of Values can be stored either in forward or Backward Directions.
=>range data type contains 3 syntaxes. They are
--------------------------------------------------------------------------------------------------------------------------
------------------
Syntax-1: varname=range(Value)
--------------------------------------------------------------------------------------------------------------------------
------------------
=>This Syntax generates range of values from 0 to Value-1
Examples:
-----------------
>>> r=range(6)
>>> print(r,type(r))
range(0, 6) <class 'range'>
>>> for v in r:
... print(v)
...
0
1
2
3
4
5
>>> for val in range(6):
... print(val)
...
0
1
2
3
4
5
>>> for val in range(10):
... print(val)
...
0
1
2
3
4
5
6
7
8
9
--------------------------------------------------------------------------------------------------------------------------
------------------
Syntax-2 : varname=range(Begin,End)
--------------------------------------------------------------------------------------------------------------------------
------------------
=>This Syntax generates range of values from Begin to End-1
Examples:
------------------
>>> r=range(10,16)
>>> print(r,type(r))
range(10, 16) <class 'range'>
>>> for val in r:
... print(val)
...
10
11
12
13
14
15
>>> for val in range(10,16):
... print(val)
...
10
11
12
13
14
15
>>> for val in range(10,16):
... print(val,end=" ") # 10 11 12 13 14 15

NOTE: The Syntax-1 and Syntax-2 generates range of values in FORWARD DIRECTION with
Default
Interval 1.
--------------------------------------------------------------------------------------------------------------------------
------------------
Syntax-3: varname=range(Begin,End,Step)
--------------------------------------------------------------------------------------------------------------------------
------------------
=>This Syntax generates range of values from Begin to End-1 by maintaining Equal Interval value in
the form Step either in Forward Direction or Backdirection.
-----------------------------------
Examples:
------------------------------------
>>> r=range(10,21,2)
>>> for val in r:
... print(val)
...
10
12
14
16
18
20
>>> for val in range(10,21,2):
... print(val)
...
10
12
14
16
18
20
--------------------------------------------------------------------------------------------------------------------------
----------
Implementation of range data type
--------------------------------------------------------------------------------------------------------------------------
----------
Q1) 0 1 2 3 4 5 6 7 8 9 10--------range(11)
>>> for val in range(11):
... print(val)
...
0
1
2
3
4
5
6
7
8
9
10
--------------------------------------------------------------------------------------------------------------------------
----------
Q2) 10 11 12 13 14 15 16 17 18 19 20--range(10,21)
>>> for val in range(10,21):
... print(val)
...
10
11
12
13
14
15
16
17
18
19
20
--------------------------------------------------------------------------------------------------------------------------
----------
Q3) 1000 1001 1002 1003 1004 1005----range(1000,1006)
>>> for val in range(1000,1006):
... print(val)
...
1000
1001
1002
1003
1004
1005
--------------------------------------------------------------------------------------------------------------------------
----------
Q4) 10 12 14 16 18 20-------range(10,21,2)
>>> for val in range(10,21,2):
... print(val)
...
10
12
14
16
18
20
--------------------------------------------------------------------------------------------------------------------------
----------
Q5) 100 110 120 130 140 150 160 170 180 190 200----range(100,201,10)
>>> for v in range(100,201,10):
... print(v)
...
100
110
120
130
140
150
160
170
180
190
200
--------------------------------------------------------------------------------------------------------------------------
----------
Q6) 10 9 8 7 6 5 4 3 2 1-----range(10,0,-1)
>>> for v in range(10,0,-1):
... print(v)
...
10
9
8
7
6
5
4
3
2
1

--------------------------------------------------------------------------------------------------------------------------
----------
Q7) 100 90 80 70 60 50 40 30 20 10 0------range(100,-1,-10)
>>> for hyd in range(100,-1,-10):
... print(hyd)
...
100
90
80
70
60
50
40
30
20
10
0
--------------------------------------------------------------------------------------------------------------------------
----------
Q8) -10 -11 -12 -13 -14 -15-------- range(-10,-16,-1)
>>> for val in range(-10,-16,-1):
... print(val)
...
-10
-11
-12
-13
-14
-15
--------------------------------------------------------------------------------------------------------------------------
----------
Q9) -100 -90 -80 -70 -60 -50 -40 -30 -20 -10 ----range(-100,-9,10)
>>> for val in range(-100,-9,10):
... print(val)
...
-100
-90
-80
-70
-60
-50
-40
-30
-20
-10
--------------------------------------------------------------------------------------------------------------------------
----------
10) -5 -4 -3 -2 -1 0 1 2 3 4 5 -----range(-5,6,1) OR range(-5,6)
>>> for val in range(-5,6,1):
... print(val)
...
-5
-4
-3
-2
-1
0
1
2
3
4
5
>>> for val in range(-5,6):
... print(val)
...
-5
-4
-3
-2
-1
0
1
2
3
4
5
--------------------------------------------------------------------------------------------------------------------------
----------
>>> for val in range(-1000,-1201,-50):
... print(val)
...
-1000
-1050
-1100
-1150
-1200
>>> r=range(-1000,-1201,-50)
>>> r[0]-------------------------1000
>>> r[-1]-------------------------1200
>>> for val in r[0:2]:
... print(val)
...
-1000
-1050
>>> r[0]=2000----TypeError: 'range' object does not support item assignment
-----------------
>>> for val in range(10,21,2)[::-1]:
... print(val)
...
20
18
16
14
12
10
==============================================================
Exmaple Sheet of range data type
-------------------------------------------------------------------------
Q1) 0 1 2 3 4 5 6 7 8 9 10

Q2) 10 11 12 13 14 15 16 17 18 19 20

Q3) 1000 1001 1002 1003 1004 1005


------------------------------------------------------------------------
Q4) 10 12 14 16 18 20
Q5) 100 110 120 130 140 150 160 170 180 190 200
--------------------------------------------------------------------------------
Q6) 10 9 8 7 6 5 4 3 2 1
Q7) 100 90 80 70 60 50 40 30 20 10 0
-------------------------------------------------------------------------------
Q8) -10 -11 -12 -13 -14 -15
Q9) -100 -90 -80 -70 -60 -50 -40 -30 -20 -10
-------------------------------------------------------------------------------
10) -5 -4 -3 -2 -1 0 1 2 3 4 5
11)

====================================================================
III. List Category Data Types (Collection or Data Structures)

====================================================================
=>The purpose of List Category Data Types is that "To store Multiple Values either of same Type
OR Different Type OR Both the Types in Single Object with Unique and Duplicate Values".
=>In Python Programming, we have 2 data types in List Category. They are
1. list (mutable)
2. tuple (immutable)
==============================x=========================================
======
1. list
==============================================
Index:
------------------------------------------------------------------------
=>Properties of list
=>Types of list
a) emty list
b) non-empty list
=>Operations on list
=>Pre-defined functions in list
=>Nested List / Inner List
=>Programming Examples
========================================================================
========
Properties of list
--------------------------------------------------------------------------------------------------------------------------
-----------------
=>'list' is one of the pre-defined class and treated as list data type
=>The purpose of list data type is that " To store Multiple Values either of same Type OR Different
Type
OR Both the Types in Single Object with Unique and Duplicate Values".
=>The Values / Elements of list must be stored / Organized with Square Brackets [ ] and Values must
be
separted by comma.
=>An object of list maintains Insertion order.
=>On object of list, we can perform Both Indexing and Slicing Operations.
=>An object of list belongs to Mutable
=>W.r.t list class, we can create 2 types of list objects. They are
a) Empty List
b) Non-Empty List
--------------------------
a) Empty List:
--------------------------
=>An empty list is one, which does not contain any Elements and whose length is 0.
=>Syntax: varname=[]
(OR)
varname=list()
--------------------------
b) Non-Empty List:
--------------------------
=>An Non-Empty list is one, which contains Elements and whose length is >0.
=>Syntax: varname=[Val1,Val2.....Val-n]
(OR)
varname=list(object)
--------------------------------------------------------------------------------------------------------------------------
--------
Examples:
--------------------------------------------------------------------------------------------------------------------------
--------
>>> l1=[10,20,30,10,40,50,20,10]
>>> print(l1,type(l1))----------------[10, 20, 30, 10, 40, 50, 20, 10] <class 'list'>
>>> l2=[20,"Rossum",34.56,True,2+3j]
>>> print(l2,type(l2))---------------------[20, 'Rossum', 34.56, True, (2+3j)] <class 'list'>
>>> l2[0]----------------20
>>> l2[-1]-------------(2+3j)
>>> l2[1:4]-----------['Rossum', 34.56, True]
>>> l2[::2]--------------[20, 34.56, (2+3j)]
>>> l2[::-1]-----------[(2+3j), True, 34.56, 'Rossum', 20]
---------------------------
>>> l2=[20,"Rossum",34.56,True,2+3j]
>>> print(l2,type(l2),id(l2))--------[20, 'Rossum', 34.56, True, (2+3j)] <class 'list'> 2705927635008
>>> l2[0]=30
>>> print(l2,type(l2),id(l2))----[30, 'Rossum', 34.56, True, (2+3j)] <class 'list'> 2705927635008
>>> l2[2:4]=[44.55,False]
>>> print(l2,type(l2),id(l2))----[30, 'Rossum', 44.55, False, (2+3j)] <class 'list'> 2705927635008
---------------------------------------
>>> l1=[10,"Rossum",34.56]
>>> print(l1,type(l1),len(l1))----------------[10, 'Rossum', 34.56] <class 'list'> 3
>>> l2=[]
>>> print(l2,type(l2),len(l2))--------------- [] <class 'list' > 0
OR
>>> l3=list()
>>> print(l3,type(l3),len(l3))-------------- [] <class 'list'> 0
-------------------------------------
>>> l1=[10,20,30,40,50,60]
>>> print(l1,type(l1))-------------------------[10, 20, 30, 40, 50, 60] <class 'list'>
>>> b=bytes(l1)
>>> print(b,type(b))-------------------------b'\n\x14\x1e(2<' <class 'bytes'>
>>> l2=list(b)
>>> print(l2,type(l2))---------------------[10, 20, 30, 40, 50, 60] <class 'list'>
>>> s="MISSISSIPPI"
>>> l3=list(s)
>>> print(l3,type(l3))-----['M', 'I', 'S', 'S', 'I', 'S', 'S', 'I', 'P', 'P', 'I'] <class 'list'>
------------------------
>>> a=[10]
>>> print(a,type(a))------------------[10] <class 'list'>
>>> x=100
>>> b=list(x)------------------TypeError: 'int' object is not iterable
To solve the above Error, Use the following
>>> b=list([x])
>>> print(b,type(b))--------------------[100] <class 'list'>
>>> b=list(x,)------------TypeError: 'int' object is not iterable
-----------------------------------------------------------------

day – 18
----------.
=================================================
Pre-defined functions in list
==================================================
=>We know that, on the object of list, we can perform Both Indexing and Slicing Operations.
=>Along with Indexing and Slicing Operations, we can Perform Various Operations by using Pre-
Defined
Functions present in list object. They are
--------------------------------------------------------------------------------------------------------------------------
--------------------
1. append()
--------------------------------------------------------------------------------------------------------------------------
--------------------
Syntax: listobj.append(Value)
=>This Function is used for adding the values to list object at end.
--------------------------
Example
-------------------------
>>> lst=[10,"Rossum",34.56]
>>> print(lst,id(lst))----[10, 'Rossum', 34.56] 2705927639808
>>> lst.append("PYTHON")
>>> print(lst,id(lst))----[10, 'Rossum', 34.56, 'PYTHON'] 2705927639808
>>> lst.append(True)
>>> lst.append(1+2.5j)
>>> print(lst,id(lst))----[10, 'Rossum', 34.56, 'PYTHON', True, (1+2.5j)] 2705927639808
--------------------------------------------------------------------------------------------------------------------------
--------------------
2. insert()
--------------------------------------------------------------------------------------------------------------------------
--------------------
Syntax: listobj.insert(Index,Value)
=>This Function is used for adding the value to list object at Specified Index
=>When we enter Invalid Possitive Index then the value inserted at Last/End of List object
=>When we enter Invalid Negative Index then the value inserted at First of List object
-------------------
Examples
-------------------
>>> lst=[10,"Rossum",34.56]
>>> print(lst,id(lst))---------[10, 'Rossum', 34.56] 2705923376704
>>> lst.insert(2,"PYTHON")
>>> print(lst,id(lst))-----------[10, 'Rossum', 'PYTHON', 34.56] 2705923376704
>>> lst[-1]=44.56
>>> print(lst,id(lst))--------[10, 'Rossum', 'PYTHON', 44.56] 2705923376704
>>> lst.insert(2,True)
>>> print(lst,id(lst))-----[10, 'Rossum', True, 'PYTHON', 44.56] 2705923376704
>>> lst.insert(-1,2+3j)
>>> print(lst,id(lst))-----[10, 'Rossum', True, 'PYTHON', (2+3j), 44.56] 2705923376704
-------------------------------------
>>> lst=[10,"Rossum",34.56]
>>> print(lst,id(lst))-----------[10, 'Rossum', 34.56] 2705927639296
>>> lst.insert(10,"PYTHON")
>>> print(lst,id(lst))-----------[10, 'Rossum', 34.56, 'PYTHON'] 2705927639296
>>> lst.insert(-10,"HYD")
>>> print(lst,id(lst))----------['HYD', 10, 'Rossum', 34.56, 'PYTHON'] 2705927639296
--------------------------------------------------------------------------------------------------------------------------
--------------------
3. clear()
--------------------------------------------------------------------------------------------------------------------------
--------------------
Syntax: listobj.clear()
=>This Function is used for Removing all the elements of Non-Empty List object
=>When we call clear() on empty list object then we get No Output / None
Examples:
------------------
>>> lst=[10,"Rossum",34.56]
>>> print(lst,id(lst),len(lst))---------------[10, 'Rossum', 34.56] 2705927639808 3
>>> lst.clear()
>>> print(lst,id(lst),len(lst))------------ [] 2705927639808 0
----------------------------------
>>> lst.clear() -------------- No Ouput
(OR)
>>> print(lst.clear())----------None
>>> [].clear()-------------------No Output
(OR)
>>> print([].clear())
None
>>> print(list().clear())----------None
-------------------------------------------------------------------------------------------------------------------------
4. remove()----Based on Value
--------------------------------------------------------------------------------------------------------------------------
--------------------
=>Syntax: listobj.remove(Value)
=>This Function is used for Removing the First Occurence of Specified Element of list object.
=>If the Specified Element does not exist in list object then we get ValueError.
----------------------
=>Examples:
----------------------
>>> lst=[10,"Rossum",34.56,"Python"]
>>> print(lst,len(lst))--------------------[10, 'Rossum', 34.56, 'Python'] 4
>>> lst.remove("Rossum")
>>> print(lst,len(lst))------------------[10, 34.56, 'Python'] 3
>>> lst.remove(34.56)
>>> print(lst,len(lst))--------------------[10, 'Python'] 2
>>> lst.remove("Python")
>>> print(lst,len(lst))------------------[10] 1
>>> lst.remove(10)
>>> print(lst,len(lst))------------------[] 0
>>> lst.remove("Python")--------------ValueError: list.remove(x): x not in list
>>> list().remove(100)-------------------ValueError: list.remove(x): x not in list
---------------------------------------
>>> lst1=[10,20,30,10,30,"Python",True]
>>> print(lst1,len(lst1))---------------[10, 20, 30, 10, 30, 'Python', True] 7
>>> lst1.remove(10)
>>> print(lst1,len(lst1))--------------[20, 30, 10, 30, 'Python', True] 6
>>> lst1.remove(10)
>>> print(lst1,len(lst1))--------------[20, 30, 30, 'Python', True] 5
>>> lst1.remove(30)
>>> print(lst1,len(lst1))--------------[20, 30, 'Python', True] 4
>>> lst1.remove(30)
>>> print(lst1,len(lst1))--------------[20, 'Python', True] 3
-------------------------------------------------------------------------------------------------------------------------
5. pop(index)----Index Based
--------------------------------------------------------------------------------------------------------------------------
--------------------
=>Syntax: listobj.pop(index)
=>This Function is used for Removing the Element of listobj based on Index.
=>If the Index is invalid then we get IndexError
-------------------
Examples:
-------------------
>>> lst1=[10,20,30,10,30,"Python",True]
>>> print(lst1)--------------------------[10, 20, 30, 10, 30, 'Python', True]
>>> lst1.pop(3)-------------------------10
>>> print(lst1)--------------------------[10, 20, 30, 30, 'Python', True]
>>> lst1.pop(-4)-----------------------30
>>> print(lst1)--------------------------[10, 20, 30, 'Python', True]
>>> lst1.pop(0)------------------------10
>>> print(lst1)--------------------------[20, 30, 'Python', True]
>>> lst1.pop(0)------------------------20
>>> print(lst1)------------------------[30, 'Python', True]
>>> lst1.pop(0)----------------------30
>>> print(lst1)-------------------------['Python', True]
>>> lst1.pop(0)-----------------------'Python'
>>> print(lst1)------------------------[True]
>>> lst1.pop(0)-----------------------True
>>> print(lst1)-------------------------[]
>>> lst1.pop(0)--------------------------IndexError: pop from empty list
>>> list().pop(-4)------------------------IndexError: pop from empty list
>>> list().pop(4)-------------------------IndexError: pop from empty list
--------------------------------------------------------------------------------------------------------------------------
-----------------
6. pop()
--------------------------------------------------------------------------------------------------------------------------
--------------------
Syntax: listobj.pop()
=>This Function is used for Removing always Last Element of Listobject.
=>If we call pop() on empty list object then we get IndexError
------------------
Examples:
------------------
>>> lst=[10,"Rossum",34.56,"Python"]
>>> print(lst)----------------------------[10, 'Rossum', 34.56, 'Python']
>>> lst.pop()--------------------------'Python'
>>> print(lst)---------------------------[10, 'Rossum', 34.56]
>>> lst.pop()-------------------------34.56
>>> print(lst)-------------------------[10, 'Rossum']
>>> lst.pop()--------------------------'Rossum'
>>> print(lst)-------------------------[10]
>>> lst.pop()--------------------------10
>>> print(lst)-------------------------[]
>>> lst.pop()--------------------------IndexError: pop from empty list
---------------------------------------------------------------------------
>>> list().pop()----------------IndexError: pop from empty list
>>> [].pop()---------------------IndexError: pop from empty list
--------------------------------------------------------------------------------------------------------------------------
--
NOTE: del operator--Most Imp
---------
Syntax1: del objname[Index]---->Removing the element based on Index
Syntax2: del objname[Begin:End:Step]--->Removing the Elements Based in Slicing Operations
Syntax3: del objname--------->Removing the entire object
------------------
Examples
------------------
>>> lst=[10,"Sagatika",66.66,"OUCET","HYD"]
>>> print(lst,type(lst),id(lst))-----------[10, 'Sagatika', 66.66, 'OUCET', 'HYD'] <class 'list'>
2302481486656
>>> del lst[-2]
>>> print(lst,type(lst),id(lst))----------[10, 'Sagatika', 66.66, 'HYD'] <class 'list'> 2302481486656
>>> del lst[0:2]
>>> print(lst,type(lst),id(lst))---------[66.66, 'HYD'] <class 'list'> 2302481486656
>>> lst=[10,"Sagatika",66.66,"OUCET","HYD"]
>>> del lst[::2]
>>> print(lst,type(lst),id(lst))--------['Sagatika', 'OUCET'] <class 'list'> 2302485776384
>>> del lst
>>> print(lst,type(lst),id(lst))-----NameError: name 'lst' is not defined.

DAY – 19
------------,

7) index()
--------------------------------------------------------------------------------------------------------------------------
-----------------
Syntax: listobj.index(Value)
------------
=>This Function is used for Finding Index of First Occurence of Specified Element in List object.
=>if the Specified Element not present in List object then we get ValueError.
----------------
Examples:
----------------
>>> lst=[10,20,30,40,10,60,70,10,30]
>>> print(lst)-------------[10, 20, 30, 40, 10, 60, 70, 10, 30]
>>> lst.index(10)---------0
>>> lst.index(20)---------1
>>> lst.index(30)----------2
>>> lst.index(300)----------ValueError: 300 is not in list
>>> list().index(10)---------ValueError: 10 is not in list
>>> [].index(-12)-------------ValueError: -12 is not in list
--------------------------------------------------------------------------------------------------------------------------
-----------------
8) copy()----Shallow Copy
--------------------------------------------------------------------------------------------------------------------------
-----------------
=>This Function is Used for Copying the content of One Object into another Object ( Implements
Shallow Copy).
=>Syntax: Listobject2=listobj1.copy()
----------------
Examples:
----------------
>>> lst1=[10,"Rossum",34.56]
>>> print(lst1,type(lst1),id(lst1))------[10, 'Rossum', 34.56] <class 'list'> 2302481827584
>>> lst2=lst1.copy() # Shallow Copy
>>> print(lst2,type(lst2),id(lst2))----[10, 'Rossum', 34.56] <class 'list'> 2302481486656
>>> lst1.append("PYTHON")
>>> print(lst1,type(lst1),id(lst1))---[10, 'Rossum', 34.56, 'PYTHON'] <class 'list'> 2302481827584
>>> print(lst2,type(lst2),id(lst2))---[10, 'Rossum', 34.56] <class 'list'> 2302481486656
>>> lst2.append("NL")
>>> print(lst2,type(lst2),id(lst2))--[10, 'Rossum', 34.56, 'NL'] <class 'list'> 2302481486656
>>> print(lst1,type(lst1),id(lst1))--[10, 'Rossum', 34.56, 'PYTHON'] <class 'list'> 2302481827584
-------------------------------
Deep Copy--Examples
---------------------------------
>>> lst1=[10,"Rossum",34.56]
>>> print(lst1,type(lst1),id(lst1))---------[10, 'Rossum', 34.56] <class 'list'> 2302481517760
>>> lst2=lst1 # Deep Copy
>>> print(lst2,type(lst2),id(lst2))---[10, 'Rossum', 34.56] <class 'list'> 2302481517760
>>> lst1.append("HYD")
>>> print(lst1,type(lst1),id(lst1))---[10, 'Rossum', 34.56, 'HYD'] <class 'list'> 2302481517760
>>> print(lst2,type(lst2),id(lst2))---[10, 'Rossum', 34.56, 'HYD'] <class 'list'> 2302481517760
>>> lst2.remove("Rossum")
>>> print(lst1,type(lst1),id(lst1))---[10, 34.56, 'HYD'] <class 'list'> 2302481517760
>>> print(lst2,type(lst2),id(lst2))---[10, 34.56, 'HYD'] <class 'list'> 2302481517760
--------------------------------------------------------------------------------------------------------------------------
-----------------
9. count()
--------------------------------------------------------------------------------------------------------------------------
-----------------
=>Syntax: listobj1.count(Value)
=>This Function is used for finding / Counting Number of occurences of Specified Value of List
object.
=>If the Specified Value does not exist in list object then we get 0 as a Result.
-----------------------
Examples
-----------------------
>>> lst=[10,20,30,10,20,50,60,70,10]
>>> print(lst)-----------[10, 20, 30, 10, 20, 50, 60, 70, 10]
>>> lst.count(10)-------3
>>> lst.count(20)-------2
>>> lst.count(30)-------1
>>> lst.count(40)-------0
>>> lst.count("PYTHON" )-----0
>>> list().count(10)----------0
>>> [].count(10)-------------0
--------------------------------------------------------------------------------------------------------------------------
-----------------
10. reverse()
--------------------------------------------------------------------------------------------------------------------------
-----------------
Syntax: listobj.reverse()
=>This Function is used for reversing(Front elements to back and back elements to Front) the
elements
of list object in same list itself.
----------------------
Examples:
---------------------
>>> lst1=[10,"Rossum",34.56,"PYTHON"]
>>> print(lst1,id(lst1))-----------[10, 'Rossum', 34.56, 'PYTHON'] 2302485781376
>>> lst1.reverse()
>>> print(lst1,id(lst1))-----------['PYTHON', 34.56, 'Rossum', 10] 2302485781376
-----------------------
>>> lst2=[10,20,30,100,200,300]
>>> print(lst2,id(lst2))--------[10, 20, 30, 100, 200, 300] 2302485776384
>>> lst2.reverse()
>>> print(lst2,id(lst2))-------[300, 200, 100, 30, 20, 10] 2302485776384
---------------------------------------
>>> lst2=[10,20,30,100,200,300]
>>> lst3=lst2.reverse()
>>> print(lst2,id(lst2))---------[300, 200, 100, 30, 20, 10] 2302481517760
>>> print(lst3)--------------None
>>> list().reverse() # No Output
(OR)
>>> print(list().reverse())--------None

--------------------------------------------------------------------------------------------------------------------------
--------------------
11) extend()
--------------------------------------------------------------------------------------------------------------------------
--------------------
Syntax: listobj1.extend(listobj2)
=>This Function is used for Merging / Combining The values of listobj2 with ListObj1. Hence
Listobj1
contains Its Own Elements and Elements of listobj2.
Syntax: listobj1=listobj1+ listobj2+ ........+listobj-n
=>By using + Operator also we can Merge OR Combine Multiple elements of list objects
---------------
Examples:
---------------
>>> lst1=[10,20,30,40]
>>> lst2=["Python","Java"]
>>> lst3=["Rossum","Gosling"]
>>> lst1.extend(lst2,lst3)------------TypeError: list.extend() takes exactly one argument (2 given)
#### TO Solve the above Error
>>> lst1.extend(lst2)
>>> lst1.extend(lst3)
>>> print(lst1)-------[10, 20, 30, 40, 'Python', 'Java', 'Rossum', 'Gosling']
------------------------------
OR
------------------------------
>>> lst1=[10,20,30,40]
>>> lst2=["Python","Java"]
>>> lst3=["Rossum","Gosling"]
>>> lst1=lst1+lst2+lst3 # Used + Operartor for Merging
>>> print(lst1)-----[10, 20, 30, 40, 'Python', 'Java', 'Rossum', 'Gosling']
--------------------------------------------------------------------------------------------------------------------------
--------------------
12) sort()
--------------------------------------------------------------------------------------------------------------------------
--------------------
Syntax1: listobj.sort()----->Sorts the given List data in ASCending Order
Syntax2: listobj.sort(revserse=False)----->Sorts the given List data in ASCending Order
Syntax3: listobj.sort(reverse=True)--->Sort the given List data in DESCending Order
-----------------
Examples:
-----------------
>>> lst=[10,-2,12,56,13,-7,45,6]
>>> print(lst,id(lst))--------[10, -2, 12, 56, 13, -7, 45, 6] 2302485781696
>>> lst.sort()
>>> print(lst,id(lst))------[-7, -2, 6, 10, 12, 13, 45, 56] 2302485781696
>>> #------------------------------------
>>> lst=[10,-2,12,56,13,-7,45,6]
>>> print(lst,id(lst))------------[10, -2, 12, 56, 13, -7, 45, 6] 2302481486656
>>> lst.sort()
>>> print(lst,id(lst))---------[-7, -2, 6, 10, 12, 13, 45, 56] 2302481486656
>>> lst.reverse()
>>> print(lst,id(lst))----------[56, 45, 13, 12, 10, 6, -2, -7] 2302481486656
>>> #-----------------------------------------
>>> lst=[10,-2,12,56,13,-7,45,6]
>>> print(lst,id(lst))----------[10, -2, 12, 56, 13, -7, 45, 6] 2302485781696
>>> lst.sort(reverse=True)
>>> print(lst,id(lst))--------[56, 45, 13, 12, 10, 6, -2, -7] 2302485781696
>>> #------------------------------------------
>>> lst=[10,-2,12,56,13,-7,45,6]
>>> print(lst,id(lst))----------[10, -2, 12, 56, 13, -7, 45, 6] 2302481486656
>>> lst.sort(reverse=False)
>>> print(lst,id(lst))-----------[-7, -2, 6, 10, 12, 13, 45, 56] 2302481486656
>>> #-----------------------------------------------
>>> lst=["Trump","Zaki","Biden","Putin","Rossum","Alen"]
>>> print(lst)----------['Trump', 'Zaki', 'Biden', 'Putin', 'Rossum', 'Alen']
>>> lst.sort(reverse=True)
>>> print(lst)------------['Zaki', 'Trump', 'Rossum', 'Putin', 'Biden', 'Alen']
>>> #-------------------------------------------------
>>> lst=["Trump","Zaki","Biden","Putin","Rossum","Alen"]
>>> print(lst)----------['Trump', 'Zaki', 'Biden', 'Putin', 'Rossum', 'Alen']
>>> lst.sort()
>>> print(lst)-------['Alen', 'Biden', 'Putin', 'Rossum', 'Trump', 'Zaki']
>>> #---------------------------------------------------
>>> lst=[10,"Trump",33.33,2+3j,True]
>>> print(lst)---------[10, 'Trump', 33.33, (2+3j), True]
>>> lst.sort()----------TypeError: '<' not supported between instances of 'str' and 'int'
==================================x=====================================
======

--------------------------------------------------------------------------------------------------------------------------
--------------------

dAY – 20

NESTED LIST / INNER LIST


--------------------------------------.

LST=[100,''ROSSUM'',18,17,19,76,79,''OUCET'']
or
LST=[12,[BOYS INFO],[GIRLS INFO],''PYTHON'']

===============================================
Inner or Nested List
===============================================
=>The Process of Defining one list inside of another list is called Inner or Nested List
=>Syntax:- listobj=[ Val1, Val2....[Val11,Val12...Val1n], [Val21,Val22..Val2n...], Val-n ]

=>Here Val1,Val2...Val-n are called Values of Outer List


=>Here Val11,Val12...Val-1n are called Values of one Inner List
=>Here Val21,Val22...Val-2n are called Values of another Inner List
=>In inner list we can perform Both Indexing and Slicing Operations
=>On Inner List, we can apply all pre-defined function of list.

Examples:
---------------------------
>>> lst=[100,"Karthik",[18,16,20],[76,75,66],"OUCET"]
>>> print(lst)-----------------[100, 'Karthik', [18, 16, 20], [76, 75, 66], 'OUCET']
>>> lst[-1]--------------------'OUCET'
>>> lst[-2]------------------------[76, 75, 66]
>>> lst[-3]--------------------------[18, 16, 20]
>>> lst[1]-----------------------------------'Karthik'
>>> lst[0]-----------------------------------100
>>> print(lst[2],type(lst[2]))----------------[18, 16, 20] <class 'list'>
>>> print(lst[-2],type(lst[-2]))-------------[76, 75, 66] <class 'list'>
>>> lst[2][0]------------------------------18
>>> lst[2][1]------------------------------16
>>> lst[2][1]=17
>>> print(lst)-----------------[100, 'Karthik', [18, 17, 20], [76, 75, 66], 'OUCET']
>>> lst[2].append(16)
>>> print(lst)---------------[100, 'Karthik', [18, 17, 20, 16], [76, 75, 66], 'OUCET']
>>> lst[-2].insert(-2,80)
>>> print(lst)--------------[100, 'Karthik', [18, 17, 20, 16], [76, 80, 75, 66], 'OUCET']
>>> del lst[-2]
>>> print(lst)--------------[100, 'Karthik', [18, 17, 20, 16], 'OUCET']
>>> lst[2].clear()
>>> print(lst)----------------[100, 'Karthik', [], 'OUCET']
>>> del lst[2]
>>> print(lst)---------------------[100, 'Karthik', 'OUCET']
>>> lst.insert(2,[16,15,18,17])
>>> print(lst)--------------------------[100, 'Karthik', [16, 15, 18, 17], 'OUCET']
>>> lst.insert(-1,[77,66,78,55])
>>> print(lst)-----------------[100, 'Karthik', [16, 15, 18, 17], [77, 66, 78, 55], 'OUCET']
>>> lst[2].sort()
>>> print(lst)-------------------[100, 'Karthik', [15, 16, 17, 18], [77, 66, 78, 55], 'OUCET']
>>> lst[-2].sort(reverse=True)
>>> print(lst)--------------------[100, 'Karthik', [15, 16, 17, 18], [78, 77, 66, 55], 'OUCET']
------------------
Examples:
------------------
>>> studlist=[100,"DLPrince",[18,16,19],[78,66,79],"OUCET"]

>>> print(studlist,type(studlist))--[100, 'DLPrince', [18, 16, 19], [78, 66, 79], 'OUCET']
<class 'list'>
>>> print(studlist[2],type(studlist[2]))---[18, 16, 19] <class 'list'>
>>> print(studlist[-2],type(studlist[-2]))---[78, 66, 79] <class 'list'>
>>> studlist[-3].append(17)
>>> print(studlist,type(studlist))--[100, 'DLPrince', [18, 16, 19, 17], [78, 66, 79],
'OUCET'] <class 'list'>
>>> studlist[3].append(68)
>>> print(studlist,type(studlist))---[100, 'DLPrince', [18, 16, 19, 17], [78, 66, 79, 68],
'OUCET'] <class 'list'>
>>> studlist[2].sort()
>>> print(studlist,type(studlist))---[100, 'DLPrince', [16, 17, 18, 19], [78, 66, 79, 68],
'OUCET'] <class 'list'>
>>> studlist[3].sort(reverse=True)
>>> print(studlist,type(studlist))----[100, 'DLPrince', [16, 17, 18, 19], [79, 78, 68, 66],
'OUCET'] <class 'list'>
>>> studlist[2].pop(-2)----18
>>> studlist[-2].remove(68)
>>> print(studlist,type(studlist))--[100, 'DLPrince', [16, 17, 19], [79, 78, 66], 'OUCET']
<class 'list'>
>>> studlist[2].clear()
>>> print(studlist,type(studlist))--[100, 'DLPrince', [], [79, 78, 66], 'OUCET'] <class
'list'>
>>> studlist[2].append(14)
>>> print(studlist,type(studlist))---[100, 'DLPrince', [14], [79, 78, 66], 'OUCET'] <class
'list'>
>>> del studlist[2]
>>> del studlist[-2]
>>> print(studlist,type(studlist))---[100, 'DLPrince', 'OUCET'] <class 'list'>
>>> studlist.insert(2,[17,15,14,19])
>>> print(studlist,type(studlist))--[100, 'DLPrince', [17, 15, 14, 19], 'OUCET'] <class
'list'>
>>> studlist.append([66,78,65,76])
>>> print(studlist,type(studlist))---[100, 'DLPrince', [17, 15, 14, 19], 'OUCET', [66, 78,
65, 76]] <class 'list'>
>>> studlist[-2]---'OUCET'
>>> len(studlist)----5
>>> len(studlist[2])---4
>>> len(studlist[-1])---4
===================x==================================.
=============================================
tuple
=============================================
Properties
-----------------
=>'tuple' is one of the pre-defined class and treated as list data type
=>The purpose of tuple data type is that " To store Multiple Values either of same Type OR Different
Type OR Both the Types in Single Object with Unique and Duplicate Values".
=>The Values / Elements of tuple must be stored / Organized with Braces ( ) and Values must be
separted by comma.
=>An object of tuple maintains Insertion order.
=>On object of tuple, we can perform Both Indexing and Slicing Operations.
=>An object of tuple belongs to IMMutable
=>W.r.t tuple class, we can create 2 types of tuple objects. They are
a) Empty tuple
b) Non-Empty tuple
--------------------------
a) Empty tuple:
--------------------------
=>An empty tuple is one, which does not contain any Elements and whose length is 0.
=>Syntax: varname=()
(OR)
varname=tuple()
--------------------------
b) Non-Empty tuple:
--------------------------
=>An Non-Empty tuple is one, which contains Elements and whose length is >0.
=>Syntax: varname=(Val1,Val2.....Val-n)
(OR)
=>Syntax: varname=Val1,Val2.....Val-n
(OR)
varname=tuple(object)
--------------------------------------------------------------------------------------------------------------------------
--------------------
NOTE: The Functionality of tuple is exactly similar to Functionality of list but list object belongs to
Mutable and tuple object belongs to Immutable.
--------------------------------------------------------------------------------------------------------------------------
--------------------
Examples:
--------------------------------------------------------------------------------------------------------------------------
--------------------
>>> t1=(10,20,30,10,50,60,70)
>>> print(t1,type(t1))----------------(10, 20, 30, 10, 50, 60, 70) <class 'tuple'>
>>> t2=(100,"Travis",33.33,"HYD")
>>> print(t2,type(t2))-----------(100, 'Travis', 33.33, 'HYD') <class 'tuple'>
>>> len(t1)-----------7
>>> len(t2)----------4
>>> t3=100,"Rossum",44.44,"PYTHON"
>>> print(t3,type(t3))-----(100, 'Rossum', 44.44, 'PYTHON') <class 'tuple'>
--------------------------------------------
>>> t1=()
>>> print(t1,type(t1))------------() <class 'tuple'>
>>> len(t1)-------------------------0
>>> t2=tuple()
>>> print(t2,type(t2))-----------() <class 'tuple'>
>>> len(t2)------------------------0
--------------------------------------------
>>> t=(100,"Rossum",44.44,"PYTHON")
>>> print(t,type(t),id(t))--------(100, 'Rossum', 44.44, 'PYTHON') <class 'tuple'> 2605398318096
>>> t[0]--------------100
>>> t[1]--------------'Rossum'
>>> t[-1]------------'PYTHON'
>>> t[0]=200-----------TypeError: 'tuple' object does not support item assignment
----------------------------------------------
>>> l1=[100,"Rossum",44.44,"PYTHON"]
>>> print(l1,type(l1))-----------[100, 'Rossum', 44.44, 'PYTHON'] <class 'list'>
>>> t1=tuple(l1)
>>> print(t1,type(t1))----------(100, 'Rossum', 44.44, 'PYTHON') <class 'tuple'>
>>> l2=list(t1)
>>> print(l2,type(l2))----------[100, 'Rossum', 44.44, 'PYTHON'] <class 'list'>
------------------------------------------------------------
>>> t=(100,"Rossum",44.44,"PYTHON")
>>> print(t,type(t))-----------(100, 'Rossum', 44.44, 'PYTHON') <class 'tuple'>
>>> t[0:3]-----------(100, 'Rossum', 44.44)
>>> t[::-1]-------------('PYTHON', 44.44, 'Rossum', 100)
-------------------------------------------------------------------------------------------------------------------------
Special Points
---------------------------
>>> a=10
>>> t=tuple(a)--------------TypeError: 'int' object is not iterable
>>> t=tuple(a,)-------------TypeError: 'int' object is not iterable
>>> t=tuple((a))-------------TypeError: 'int' object is not iterable
>>> t=tuple([a])
>>> print(t,type(t))--------------(10,) <class 'tuple'>
--------OR-------------
>>> b=100
>>> t=(b,)
>>> print(t,type(t))-----------(100,) <class 'tuple'>
-----------------------------------
>>> b=12.34
>>> t=(b)
>>> print(t,type(t))------------12.34 <class 'float'>
>>> t=(b,)
>>> print(t,type(t))------------(12.34,) <class 'tuple'>
-----------------------------------------------------------
=============================================
Pre-defined Function in tuple
=============================================
=>We know that on the object of tuple we can perform Both Indexing and Slicing Operations.
=>Along with these operations, we can also perform other operations by using the following
pre-defined Functions.

1)index()
2)count()
-------------------
Examples:
------------------
>>> t1=(10,"RS",45.67)
>>> print(t1,type(t1))------------(10, 'RS', 45.67) <class 'tuple'>
>>> t1.index(10)---------0
>>> t1.index("RS")------1
>>> t1=(10,"RS",45.67)
>>> print(t1,type(t1))-------(10, 'RS', 45.67) <class 'tuple'>
>>> t1.count(10)-------1
>>> t1.count(100)------0
>>> t1=(10,0,10,10,20,0,10)
>>> print(t1,type(t1))---------(10, 0, 10, 10, 20, 0, 10) <class 'tuple'>
>>> t1.count(10)---------------4
>>> t1.count(0)-----------------2
>>> t1.count(100)--------------0
---------------------------
The Functions not present in tuple
---------------------------
append()
insert()
remove()
clear()
pop(index)
pop()
reverse()
sort()
copy()
extend()
---------------------------------------
NOTE:- By Using del Operator we can't delete values of tuple object By using Indexing and
slicing but we can delete entire object
Examples:
---------------
>>> t1=(10,-34,0,10,23,56,76,21)
>>> print(t1,type(t1))--------------(10, -34, 0, 10, 23, 56, 76, 21) <class 'tuple'>
>>> del t1[0]------TypeError: 'tuple' object doesn't support item deletion
>>> del t1[0:4]----TypeError: 'tuple' object does not support item deletion
>>> del t1 # Here we are removing complete object.
>>> print(t1,type(t1))-----NameError: name 't1' is not defined.
========================================================
MOST IMP:
---------------
sorted(): This Function is used for Sorting the data of immutable object tuple and gives
the sorted data in the form of list.
=>Syntax: listobj=sorted(tuple object)

Examples:
--------------------------------------------------------
>>> t1=(10,23,-56,-1,13,15,6,-2)
>>> print(t1,type(t1))------------(10, 23, -56, -1, 13, 15, 6, -2) <class 'tuple'>
>>> t1.sort()----------------------AttributeError: 'tuple' object has no attribute 'sort'
>>> x=sorted(t1)
>>> print(x,type(x))-----------[-56, -2, -1, 6, 10, 13, 15, 23] <class 'list'>
>>> print(t1,type(t1))----------(10, 23, -56, -1, 13, 15, 6, -2) <class 'tuple'>
>>> t1=tuple(x) # Converted sorted list into tuple
>>> print(t1,type(t1))---------(-56, -2, -1, 6, 10, 13, 15, 23) <class 'tuple'>
>>> t2=t1[::-1]
>>> print(t2,type(t2))------(23, 15, 13, 10, 6, -1, -2, -56) <class 'tuple'>
OR
>>> t1=(10,-4,12,34,16,-6,0,15)
>>> print(t1,type(t1))---------------------(10, -4, 12, 34, 16, -6, 0, 15) <class 'tuple'>
>>> l1=list(t1)
>>> print(l1,type(l1))-----------------[10, -4, 12, 34, 16, -6, 0, 15] <class 'list'>
>>> l1.sort()
>>> print(l1,type(l1))-------------------[-6, -4, 0, 10, 12, 15, 16, 34] <class 'list'>
>>> t1=tuple(l1)
>>> print(t1,type(t1))---------------(-6, -4, 0, 10, 12, 15, 16, 34) <class 'tuple'>
>>>t1=t1[::-1]
>>> print(t1,type(t1))----------------(34, 16, 15, 12, 10, 0, -4, -6) <class 'tuple'>
==================x================================.

day = 21

=================================================
Inner (OR) Nested tuple
==================================================
=>The Process of Defining One tuple in another tuple is called Inner or Nested tuple
=>Syntax:- tplobj1=( Val1,Val2....(Val11,Val12....Val1n).....(Val21,Val22...Val2n)..........Val-n )

=>Here (Val11,Val12....Val1n) is called One Inner OR Nested tuple


(Val21,Val22...Val2n) is called another Inner OR Nested tuple
=> ( Val1,Val2....(Val11,Val12....Val1n).....(Val21,Val22...Val2n)....Val-n ) is called Outer tuple
=>All the pre-defined Functions of tuple can be applied on Inner or Nested tuple.
=>On Inner or Nested tuple we can perform Index and Slicing Operations.
----------------------------------------------------------------------------------------------------------
Examples:
----------------------------------------------------------------------------------------------------------
>>> sf=(10,"RS",(17,18,16),(78,66,79),"OUCET")
>>> print(sf,type(sf))------------(10, 'RS', (17, 18, 16), (78, 66, 79), 'OUCET') <class 'tuple'>
>>> print(sf[0])-----10
>>> print(sf[2],type(sf[2]),type(sf))---------(17, 18, 16) <class 'tuple'> <class 'tuple'>
>>> print(sf[0:3])------------(10, 'RS', (17, 18, 16))
---------------------------------------------------------------------------
>>> sf=(10,"RS",[17,18,16],(78,66,79),"OUCET")
>>> print(sf,type(sf))----------------(10, 'RS', [17, 18, 16], (78, 66, 79), 'OUCET') <class 'tuple'>
>>> print(sf[2],type(sf[2]),type(sf))------------[17, 18, 16] <class 'list'> <class 'tuple'>
>>> sf[2].append(12)
>>> print(sf[2],type(sf[2]),type(sf))------------[17, 18, 16, 12] <class 'list'> <class 'tuple'>
>>> print(sf,type(sf))---------(10, 'RS', [17, 18, 16, 12], (78, 66, 79), 'OUCET') <class 'tuple'>
>>> sf[3].append(12)---AttributeError: 'tuple' object has no attribute 'append'
-------------------------------------------------------
>>> sf=[10,"RS",[17,18,16],(78,66,79),"OUCET"]
>>> print(sf,type(sf))-------------[10, 'RS', [17, 18, 16], (78, 66, 79), 'OUCET'] <class 'list'>
>>> print(sf[2],type(sf[2]),type(sf))--------[17, 18, 16] <class 'list'> <class 'list'>
>>> print(sf[3],type(sf[3]),type(sf))-------(78, 66, 79) <class 'tuple'> <class 'list'>
-----------------------------------------------------------------------------------------------------------
NOTE:
--------
=>One can define One List in another List
=>One can define One Tuple in another Tuple
=>One can define One List in another Tuple ( tuple of lists)
=>One can define One tuple in another List (list of tuples)
---------------------------------------------------------------------------------------------------------
>>> print(t1,type(t1))
(10, 'Rossum', [16, 18, 17], ('CSE', 'AI', 'DS'), 'OUCET') <class 'tuple'>
>>> print(t1[2],type(t1[2]))-------[16, 18, 17] <class 'list'>
>>> print(t1[3],type(t1[3]))------('CSE', 'AI', 'DS') <class 'tuple'>
>>> t1[2].append("KVR")
>>> print(t1,type(t1))--(10, 'Rossum', [16, 18, 17, 'KVR'], ('CSE', 'AI', 'DS'), 'OUCET') <class 'tuple'>
>>> t1[3].append("Python")-----AttributeError: 'tuple' object has no attribute 'append'
>>> t1[2][1]--------18
>>> t1[2][-2]------17
>>> t1[2][-3]------18
>>> k=sorted(t1[-2])
>>> k------------['AI', 'CSE', 'DS']
>>> t1[3]=k---------TypeError: 'tuple' object does not support item assignment
>>> l1=list(t1)----
>>> l1----------[10, 'Rossum', [16, 18, 17, 'KVR'], ('CSE', 'AI', 'DS'), 'OUCET']
>>> l1[3]=k
>>> l1-----[10, 'Rossum', [16, 18, 17, 'KVR'], ['AI', 'CSE', 'DS'], 'OUCET']
>>> y=tuple(l1[3])
>>> l1[3]=y
>>> l1-----[10, 'Rossum', [16, 18, 17, 'KVR'], ('AI', 'CSE', 'DS'), 'OUCET']
>>> t2=tuple(l1)
>>> t2-----(10, 'Rossum', [16, 18, 17, 'KVR'], ('AI', 'CSE', 'DS'), 'OUCET')
-------------------------------
>>> t1=('AI', 'cSE', 'DS')
>>> k=sorted(t1)
>>> k-------['AI', 'DS', 'cSE']
----------------------------------------------------------------------------------.

=========================================================
Set Category Data Types (Collection or Data Structures)
=========================================================
=>The purpose of Set Category Data Types is that " To store Multiple Values either of Same Type or
Different Type or Both the Types in Single Object with Unique Values (No Duplicates are allowed)."
=>We have 2 data type in Set Category. They are

1. set (mutable and immutable)


2. frozenset (immutable)
================================x=======================================
======.

==========================================
1. set
==========================================
Properties
------------------
=>'set' is one of the Pre-defined class and treated as set data type.
=>The purpose of set data type is that " To store Multiple Values either of Same Type or Different
Type or
Both the Types in Single Object with Unique Values (No Duplicates are allowed).
=>The Elements of set must be stored within Curly Braces { } and the elements must be separated by
comma.
=>An object of set does not maintain Insertion Order bcoz PVM displays any possibility of set
elements.
=>On the object set, we can't perform Both Indexing and Slicing Operations bcoz set never maintains
Insertion order.
=>An object of set belongs to Both Mutable in the case of Add and immutable in the case of Item
Assigment.
=>w.r.t set , we can create Two Types of set objects. They are
a) Empty Set
b) Non-Empty Set
----------------------------------
a) Empty Set
----------------------------------
=>An Empty Set is One, which does not contain any Elements and whose length is 0
=>Syntax: varname=set()
-------------------------------------------
b) Non-Empty Set
-------------------------------------------
=>An Nn-Empty Set is One, which contains Elements and whose length is>0
=>Syntax1: varname={Val1,Val2,...Val-n}
=>Syntax2: varname=set(object)
======================================x=================================
==
Examples
--------------------------------------------------------------------------------------------------------------------------
------
>>> s1={10,20,30,40,10,50,60,20}
>>> print(s1,type(s1))---------------{50, 20, 40, 10, 60, 30} <class 'set'>
>>> print(s1,type(s1))--------------{50, 20, 40, 10, 60, 30} <class 'set'>
>>> s2={10,"Travis",44.44,True,"Numpy"}
>>> print(s2,type(s2))-----------{'Numpy', True, 'Travis', 10, 44.44} <class 'set'>
----------------------
>>> s2={10,"Travis",44.44,True,"Numpy"}
>>> print(s2,type(s2))-----------{'Numpy', True, 'Travis', 10, 44.44} <class 'set'>
>>> s2[0]----------------TypeError: 'set' object is not subscriptable
>>> s2[0:3]---------------TypeError: 'set' object is not subscriptable
----------------------------------------
>>> s2={10,"Travis",44.44,True,"Numpy"}
>>> print(s2,type(s2))----------{'Numpy', True, 'Travis', 10, 44.44} <class 'set'>
>>> s2[0]=100-------------TypeError: 'set' object does not support item assignment--IMMUTABLE
------------------------------------------------
>>> s2={10,"Travis",44.44,True,"Numpy"}
>>> print(s2,type(s2),id(s2))-------------{'Numpy', True, 'Travis', 10, 44.44} <class 'set'>
2485370854016
>>> s2.add("HYD") # MUTABLE
>>> print(s2,type(s2),id(s2))----{'Numpy', True, 'Travis', 10, 44.44, 'HYD'} <class 'set'>
2485370854016
------------------------------
>>> x={}
>>> print(x,type(x))--------------{} <class 'dict'>
>>> s=set()
>>> print(s,type(s),len(s))---------- set() <class 'set'> 0
------------------------------------
>>> l1=[10,20,30,10]
>>> print(l1,type(l1))-------------[10, 20, 30, 10] <class 'list'>
>>> s1=set(l1)
>>> print(s1,type(s1))------------{10, 20, 30} <class 'set'>
-----------------------------------
>>> s="MISSISSIPPI"
>>> s1=set(s)
>>> print(s1)-------------------{'M', 'S', 'P', 'I'}
=======================================x================================
===.
===================================================
Pre-Functions in set
===================================================
=>On the object of set, we can perform different type of Operations by using Functions present in ste
object. They are
--------------------------------------------------------------------------------------------------------------------------
------
1) clear()
--------------------------------------------------------------------------------------------------------------------------
------
=>Syntax: setobj.clear()
=>This Function is used for Removing all the values of set object.
Examples:
-------------------
>>> s1={10,20,30,40,50,10}
>>> print(s1,type(s1),id(s1))----------{50, 20, 40, 10, 30} <class 'set'> 2485370854240
>>> s1.clear()
>>> print(s1,type(s1),id(s1))--------set() <class 'set'> 2485370854240
------------------------------------
>>> print(s1,len(s1))----------set() 0
>>> s1.clear()---------------- No Output
>>> print(s1.clear())----------None
--------------------------------------------------------------------------------------------------------------------------
------
2) add()
--------------------------------------------------------------------------------------------------------------------------
------
Syntax: setobj.add(Value)
=>This Function is used for adding the values to set object.
Examples:
--------------------
>>> s1={10,"Rossum",34.56,"HYD"}
>>> print(s1,type(s1),id(s1))--------{10, 'Rossum', 34.56, 'HYD'} <class 'set'> 2485370853568
>>> s1.add("NL")
>>> print(s1,type(s1),id(s1))-------{34.56, 'Rossum', 'NL', 10, 'HYD'} <class 'set'> 2485370853568
>>> s1.add(True)
>>> s1.add(2+3j)
>>> print(s1,type(s1),id(s1))-----{True, 34.56, 'Rossum', 'NL', 10, (2+3j), 'HYD'} <class 'set'>
2485370853568
--------------------------------------
>>> s1=set()
>>> print(s1,type(s1),id(s1))------------set() <class 'set'> 2485370854240
>>> s1.add(100)
>>> s1.add("Naresh")
>>> s1.add(12345)
>>> s1.add("Python")
>>> print(s1,type(s1),id(s1))-----{'Naresh', 12345, 'Python', 100} <class 'set'> 2485370854240
--------------------------------------------------------------------------------------------------------------------------
------
3) remove()
--------------------------------------------------------------------------------------------------------------------------
------
Syntax: setobj.remove(Value)
=>This Function is used for removing the values of setobject.
=>if the specified Values does not exist in set object then we get KeyError
-----------------------
Examples:
-----------------------
>>> s1={10,"Rossum",34.56,"HYD"}
>>> print(s1,id(s1))----------{10, 'Rossum', 34.56, 'HYD'} 2485370853568
>>> s1.remove(10)
>>> print(s1,id(s1))-----------{'Rossum', 34.56, 'HYD'} 2485370853568
>>> s1.remove("HYD")
>>> print(s1,id(s1))------------{'Rossum', 34.56} 2485370853568
>>> s1.remove("BANG")-------------KeyError: 'BANG'
>>> set().remove(100)---------------KeyError: 100
DAY --- 22
---------------.

4) discard()
--------------------------------------------------------------------------------------------------------------------------
------
Syntax: setobj.discard(Value)
=>This Function is used for Removing the Vaue from setobject.
=>If the Specified Value does not exist then we never get any Error
------------------
Examples:
------------------
>>> s1={10,"Ankit",34.56,"Python","HYD"}
>>> print(s1,type(s1),id(s1))-----------{'Ankit', 34.56, 'HYD', 10, 'Python'} <class 'set'>
2705097791904
>>> s1.discard(10)
>>> print(s1,type(s1),id(s1))-------{'Ankit', 34.56, 'HYD', 'Python'} <class 'set'> 2705097791904
>>> s1.discard("HYD")
>>> print(s1,type(s1),id(s1))-------{'Ankit', 34.56, 'Python'} <class 'set'> 2705097791904
>>> s1.discard("Python")
>>> print(s1,type(s1),id(s1))---------{'Ankit', 34.56} <class 'set'> 2705097791904
>>> s1.discard(1000) # we wont' get KeyError
>>> print(s1,type(s1),id(s1))--------{'Ankit', 34.56} <class 'set'> 2705097791904
>>> s1.remove(1000)KeyError: 1000
--------------------------------------------------------------------------------------------------------------------------
-------------
5) pop()
--------------------------------------------------------------------------------------------------------------------------
-------------
Syntax: setobj.pop()
=>This Function is used for Removing Any Arbitrary Element from non-empty set object
=>When we call pop() upon empty set object then we get KeyError
-----------------
Example-1 ---set elemements are given and order of display not shown and pop() removes Arbitrary
Element always
-----------------
>>> s1={10,"Ankit",34.56,"Python","HYD"}
>>> s1.pop()--------------'Ankit'
>>> s1.pop()-------------34.56
>>> s1.pop()-------------'HYD'
>>> s1.pop()-------------10
>>> s1.pop()------------'Python'
>>> print(s1)------------set()
>>> s1.pop()----------KeyError: 'pop from an empty set'
>>> set().pop()-------KeyError: 'pop from an empty set'
--------------------------------------------------------------------------------
Example-2: set elemements are given and order of disply shown and pop() removes First Element
always
--------------------------------------------------------------------------------
>>> s1={100,200,300,150,450,-120}
>>> print(s1,id(s1))--------------{450, 100, -120, 150, 200, 300} 2705097791232
>>> s1.pop()-----------450
>>> s1.pop()-----------100
>>> s1.pop()------------120
>>> s1.pop()-----------150
>>> s1.pop()-----------200
>>> s1.pop()-----------300
>>> print(s1,id(s1))--------set() 2705097791232
>>> s1.pop()---------------------KeyError: 'pop from an empty set'
--------------------------------------------------------------------------------------------------------------------------
---------
6) isdisjoint()
--------------------------------------------------------------------------------------------------------------------------
---------
=>Syntax: setobj1.isdisjoint(setobj2)
=>This Function Returns True Provided There is No Common Element in setobj1 and setobj2.
=>This Function Returns False Provided There is atleast one Common Element in setobj1 and
setobj2.
-------------------
Examples:
-------------------
>>> s1={10,20,30,40}
>>> s2={15,25,35}
>>> s3={10,100,200,300}
>>> s1.isdisjoint(s2)---------------True
>>> s1.isdisjoint(s3)---------------False
>>> s2.isdisjoint(s3)---------------True
--------------------------------------------------------------------------------------------------------------------------
---------
7) issubset()
--------------------------------------------------------------------------------------------------------------------------
---------
=>Syntax: setobj1.issubset(setobj2)
=>This function returns True Provided All the elements of setobj1 present in setobj2 (OR) setobj2
contains all the elements of setobj1
=>This function returns False Provided atleast one element of setobj1 not present in setobj2 (OR)
setobj2 not containing atleast one element of setobj1.
Examples:
---------------------
>>> s1={0,1,2,3,4,5,6,7,8,9}
>>> s2={3,4,5}
>>> s3={10,20,30}
>>> s2.issubset(s1)-----------True
>>> s3.issubset(s1)-----------False
>>> s1.issubset(s3)------------False
>>> s4={1,15,25}
>>> s4.issubset(s1)--------False
>>> s4={1,2,3,10}
>>> s4.issubset(s1)-------False
--------------------------------------------------------------------------------------------------------------------------
---------
8) issuperset()
--------------------------------------------------------------------------------------------------------------------------
---------
=>Syntax: setobj1.issuperset(setobj2)
=>This function returns True Provided setobj1 contains all the elements of setobj2 (OR) all elements
of setobj2 present in setobj1
=>This function returns False Provided atleast one element of setobj2 not present in setobj1 (OR)
setobj1 not containing atleast one element of setobj2.
-------------------
Examples:
-------------------
>>> s1={0,1,2,3,4,5,6,7,8,9}
>>> s2={3,4,5}
>>> s3={10,20,30}
>>> s1.issuperset(s2)----------True
>>> s1.issuperset(s3)----------False
>>> s4={1,2,3,10}
>>> s1.issuperset(s4)----------False

9) union()
--------------------------------------------------------------------------------------------------------------------------
---------
=>Syntax: setobj3=setobj1.union(setobj2)
(OR)
=>Syntax: setobj3=setobj2.union(setobj1)
=>This Function is used for Taking all Unique Elements of setobj1 and setobj2 and place them in
setobj3.
---------------------
Examples:
--------------------
>>> cp={"Sachin","Rohit","Kohli"}
>>> tp={"Kohli","Rossum","Travis"}
>>> print(cp,type(cp))------------{'Sachin', 'Kohli', 'Rohit'} <class 'set'>
>>> print(tp,type(tp))-------------{'Rossum', 'Travis', 'Kohli'} <class 'set'>
>>> allcptp=cp.union(tp)
>>> print(allcptp,type(allcptp))----{'Sachin', 'Kohli', 'Rohit', 'Rossum', 'Travis'} <class 'set'>
(OR)
>>> allcptp=tp.union(cp)
>>> print(allcptp,type(allcptp))---{'Sachin', 'Kohli', 'Rohit', 'Rossum', 'Travis'} <class 'set'>
--------------------------------------------------------------------------------------------------------------------------
---------
10) intersection()
--------------------------------------------------------------------------------------------------------------------------
---------
=>Syntax: setobj3=setobj1.intersection(setobj2)
(OR)
=>Syntax: setobj3=setobj2.intersection(setobj1)
=>This Function is used for Taking Common Elements of setobj1 and setobj2 and place them in
setobj3.
--------------------------
Examples
--------------------------
>>> cp={"Sachin","Rohit","Kohli"}
>>> tp={"Kohli","Rossum","Travis"}
>>> print(cp,type(cp))-----------------{'Sachin', 'Kohli', 'Rohit'} <class 'set'>
>>> print(tp,type(tp))------------------{'Rossum', 'Travis', 'Kohli'} <class 'set'>
>>> bothcptp=cp.intersection(tp)
>>> print(bothcptp,type(bothcptp))--------{'Kohli'} <class 'set'>
OR
>>> bothcptp=tp.intersection(cp)
>>> print(bothcptp,type(bothcptp))-------{'Kohli'} <class 'set'>
--------------------------
>>> a={10,20}
>>> b={30,40}
>>> a.intersection(b)----------set()
>>> {10,20,30}.intersection({'a','e','i','o','u'})-----------set()
>>> {10,20,30}.intersection({'a','e','i','o','u',10})---------{10}
--------------------------------------------------------------------------------------------------------------------------
---------
11) difference()
--------------------------------------------------------------------------------------------------------------------------
---------
Syntax1: setobj3=setobj1.difference(setobj2)
-------------
=>This Function Removes the common Elements from setobj1 and setobj2 and It takes Remaining
Elements from setobj1 and placed in setobj3.
----------------
Examples:
----------------
>>> cp={"Sachin","Rohit","Kohli"}
>>> tp={"Kohli","Rossum","Travis"}
>>> print(cp,type(cp))-----------------{'Sachin', 'Kohli', 'Rohit'} <class 'set'>
>>> print(tp,type(tp))------------------{'Rossum', 'Travis', 'Kohli'} <class 'set'>
>>> onlycp=cp.difference(tp)
>>> print(onlycp,type(onlycp))-------{'Sachin', 'Rohit'} <class 'set'>
------------------------------------------
Syntax2: setobj3=setobj2.difference(setobj1)
-------------
=>This Function Removes the common Elements from setobj2 and setobj1 and It takes Remaining
Elements from setobj2 and placed in setobj3.
----------------
Examples:
----------------
>>> cp={"Sachin","Rohit","Kohli"}
>>> tp={"Kohli","Rossum","Travis"}
>>> print(cp,type(cp))-----------------{'Sachin', 'Kohli', 'Rohit'} <class 'set'>
>>> print(tp,type(tp))------------------{'Rossum', 'Travis', 'Kohli'} <class 'set'>
>>> onlytp=tp.difference(cp)
>>> print(onlytp,type(onlytp))-----------{'Rossum', 'Travis'} <class 'set'>
------------------
>>> a={10,20}
>>> b={10,30,40,20}
>>> a.difference(b)-----------set()
>>> b.difference(a)-----------{40, 30}
--------------------------------------------------------------------------------------------------------------------------
---------
12) symmetric_difference()
--------------------------------------------------------------------------------------------------------------------------
---------
Syntax: setobj3=setobj1.symmetric_difference(setobj2)
(OR)
Syntax: setobj3=setobj2.symmetric_difference(setobj1)

=>This Function Removes the common Elements from setobj1 and setobj2 and It takes Remaining
Elements from both setobj1 and setobj2 and place them in setobj3.

--------------------------
Examples
--------------------------
>>> cp={"Sachin","Rohit","Kohli"}
>>> tp={"Kohli","Rossum","Travis"}
>>> print(cp,type(cp))--------------{'Sachin', 'Kohli', 'Rohit'} <class 'set'>
>>> print(tp,type(tp))---------------{'Rossum', 'Travis', 'Kohli'} <class 'set'>
>>> exclcptp=cp.symmetric_difference(tp)
>>> print(exclcptp,type(exclcptp))---------{'Rohit', 'Travis', 'Sachin', 'Rossum'} <class 'set'>
>>> exclcptp=tp.symmetric_difference(cp)
>>> print(exclcptp,type(exclcptp))----------{'Rohit', 'Travis', 'Sachin', 'Rossum'} <class 'set'>
OR
>>> exclcptp=tp.symmetric_difference(cp)
>>> print(exclcptp)------------{'Rohit', 'Travis', 'Sachin', 'Rossum'}
(OR)
>>> exclcptp=cp.union(tp).difference(cp.intersection(tp))
>>> print(exclcptp)-------{'Rossum', 'Sachin', 'Travis', 'Rohit'}
----------------------
Special Points
----------------------
>>> s1={10,20,30,40}
>>> s2={10,20,50,60}
>>> s3=s1.difference(s2)
>>> print(s3)------------{40, 30}
>>> s4=s2.difference(s1)
>>> print(s4)---------{50, 60}
>>> s5=s1.symmetric_difference(s2)
>>> print(s5)---------{40, 50, 60, 30}
(OR)
>>> s6=s1.union(s2).difference(s1.intersection(s2))
>>> print(s6)-----------{40, 50, 60, 30}
(OR)
>>> s7=s1.difference(s2).union(s2.difference(s1))
>>> print(s7)------------{40, 50, 60, 30}
=====================================================================
MOST IMP---Perform the above Set Operations without set Functions by Using Bitwise Operators
----------------------------------------------------
>>> cp={"Sachin","Rohit","Kohli"}
>>> tp={"Kohli","Rossum","Travis"}
>>> print(cp,type(cp))--------------{'Sachin', 'Kohli', 'Rohit'} <class 'set'>
>>> print(tp,type(tp))---------------{'Rossum', 'Travis', 'Kohli'} <class 'set'>
>>> allcptp=cp|tp # Bitwise OR Operator OR union()
>>> print(allcptp)-----------{'Sachin', 'Kohli', 'Rohit', 'Rossum', 'Travis'}
>>> botcptp=cp&tp # Bitwise AND Operator OR intersection()
>>> print(bothcptp)-----{'Kohli'}
>>> onlycp=cp-tp # - Operator OR difference()
>>> print(onlycp,type(onlycp))------------{'Sachin', 'Rohit'} <class 'set'>
>>> onlytp=tp-cp
>>> print(onlytp,type(onlytp))-------------{'Rossum', 'Travis'} <class 'set'>
>>> exclcptp=cp^tp # Bitwise XOR Operator OR symmetric_difference()
>>> print(exclcptp,type(exclcptp))-------{'Rohit', 'Travis', 'Sachin', 'Rossum'} <class 'set'>
--------------------------------------------------------------------------------------------------------------------------
---------
13) update()
--------------------------------------------------------------------------------------------------------------------------
---------
=>Syntax: setobj1.update(setobj2)
=>This Function is used Merging setobj2 values with setobj1
----------------------
Examples:
---------------------
>>> s1={10,20,30,40}
>>> s2={"Python","Java"}
>>> print(s1,type(s1))--------{40, 10, 20, 30} <class 'set'>
>>> print(s2,type(s2))--------{'Python', 'Java'} <class 'set'>
>>> s1.update(s2)
>>> print(s1)-----------------{20, 40, 10, 'Python', 'Java', 30}
--------------------------
>>> s1={10,20,30,40}
>>> s2={"Python","Java",10}
>>> s1.update(s2)
>>> print(s1)------------------{20, 40, 10, 'Python', 'Java', 30}
=================================x======================================
===

day – 23

==============================================
Nested or Inner Properties of Set
===============================================
=>We can define

a) Defining set inside of another set NOT POSSIBLE


b) Defining set inside of another Tuple POSSIBLE
c) Defining set inside of another List POSSIBLE
d) Defining tuple inside of Another Set POSSIBLE
e) Defining list inside of another set NOT POSSIBLE

----------------------
Examples:
----------------------
>>> s1={10,"Rossum",{10,15,16},"OUCET"}-----TypeError: unhashable type: 'set'
>>> s1={10,"Rossum",[10,15,16],"OUCET"}----TypeError: unhashable type: 'list'
>>> s1={10,"Rossum",(10,15,16),"OUCET"}-----Valid
>>> print(s1,type(s1))----{'Rossum', 10, 'OUCET', (10, 15, 16)} <class 'set'>
--------------------
>>> t1=(10,"Rossum",{10,15,16},"OUCET")
>>> print(t1[2],type(t1[2]),type(t1))----{16, 10, 15} <class 'set'> <class 'tuple'>
>>> l1=[10,"Rossum",{10,15,16},"OUCET"]
>>> print(l1[2],type(l1[2]),type(l1))----{16, 10, 15} <class 'set'> <class 'list'>
====================================x===================================
======.

==================================================
frozenset
==================================================
Properties
----------------
=>'frozenset' is one of the Pre-defined class and treated as set data type.
=>The purpose of frozenset data type is that " To store Multiple Values either of Same Type or
Different Type or Both the Types in Single Object with Unique Values (No Duplicates are allowed).
=>The Elements of frozenset set must be obtained from list,tuple and set by using a Type casting
Function fronset()
=>An object of frozenset does not maintain Insertion Order bcoz PVM displays any possibility of
frozenset elements.
=>On the object frozenset, we can't perform Both Indexing and Slicing Operations bcoz frozenset
never maintains Insertion order.
=>An object of frozenset belongs to immutable in the case of Item Assigment. and no functions are
allowed to modify/ update the values of frozenset object.
=>w.r.t frozenset , we can create Two Types of frozenset objects. They are
a) Empty frozenset
b) Non-Empty frozenset
----------------------------------
a) Empty frozenset
----------------------------------
=>An Empty frozenset is One, which does not contain any Elements and whose length is 0
=>Syntax: varname=frozenset()
-------------------------------------------
b) Non-Empty frozenSet
-------------------------------------------
=>An Nn-Empty Set is One, which contains Elements and whose length is > 0
=>Syntax1: varname=frozenset( [val1,val2...val-n])
(OR)
=>Syntax2: varname=frozenset( (val1,val2...val-n) )
(OR)
=>Syntax3: varname=frozenset( {val1,val2...val-n})
--------------------------------------------------------------------------------------------------------------------------
---------------------
NOTE:- The functionality of frozenset is exactly similar to set type but an object of set belongs to
Both
Mutable(in the case add() and other Functions) and Immutable (in the case of Item
Assignment), where as an object of frozenset belongs to Immutable bcoz Item Assigment does not
support and No Functions are allowed which are modifying the values of frozenset.
--------------------------------------------------------------------------------------------------------------------------
---------------------
Examples:
--------------------------------------------------------------------------------------------------------------------------
-----------------------
>>> fs=frozenset()
>>> print(fs,type(fs),len(fs))---------frozenset() <class 'frozenset'> 0
>>> fs=frozenset([10,20,10,10,10,10])
>>> print(fs,type(fs),len(fs))---------frozenset({10, 20}) <class 'frozenset'> 2
>>> fs=frozenset((10,20,10,10,10,10))
>>> print(fs,type(fs),len(fs))-------------frozenset({10, 20}) <class 'frozenset'> 2
>>> fs=frozenset({10,20,10,10,10,10})
>>> print(fs,type(fs),len(fs))--------------frozenset({10, 20}) <class 'frozenset'> 2
--------------------------------------------------------
>>> fs=frozenset([10,"Travis",45.67,True])
>>> print(fs,type(fs))----------------frozenset({True, 10, 45.67, 'Travis'}) <class 'frozenset'>
>>> fs[0]------------------------------------TypeError: 'frozenset' object is not subscriptable
>>> fs[0:2]----------------------------------TypeError: 'frozenset' object is not subscriptable
>>> fs[0]=100-----------------TypeError: 'frozenset' object does not support item assignment
>>> fs.add(100)--------------AttributeError: 'frozenset' object has no attribute 'add'
================================x=======================================
========.

=====================================
Pre-Defined Functions in frozenset
=====================================
=>frozenset contains the following Functions
a) copy()
b) isdisjoint()
c) issuperset()
d) issubset()
e) union()
f) intersection()
g) difference()
h) symmertic_difference()

NOTE:
-------------
>>> fs1=frozenset({10,20,30,409})
>>> print(fs1,type(fs1),id(fs1))--------frozenset({409, 10, 20, 30}) <class 'frozenset'>

2068835340960
>>> fs2=fs1.copy()
>>> print(fs2,type(fs2),id(fs2))-----frozenset({409, 10, 20, 30}) <class 'frozenset'>

2068835340960

=>In General, Immutable Object content is Not Possible to copy( in the case of tuple). Where as in
the case of frozenset, we are able to copy its content to another frozenset object. Here Original
frozenset object and copied frozenset object contains Same Address and Not at all possible to Modify
/ Change their content.
-------------------
Examples:
-----------------
>>> s1={10,"RS",3.4,"PYTHON"}
>>> fs1=frozenset(s1)
>>> print(fs1,type(fs1),id(fs1))---------frozenset({10, 3.4, 'RS', 'PYTHON'}) <class 'frozenset'>
1774317640096
>>> fs2=fs1.copy()
>>> print(fs2,type(fs2),id(fs2))-------frozenset({10, 3.4, 'RS', 'PYTHON'}) <class 'frozenset'>
1774317640096

=>frozenset does not contain the following Functions


a) clear()
b) add()
c) remove()
d) discard()
e) pop()
f) update()
=========================================x==============================
===========.

====================================================
V) Dict Categeory Data Types ( Collection Data Types or Data Structures)
=====================================================
Properties
---------------------------
=>'dict' is one of the pre-defined class and treated as Dict Data Type.
=>The purpose of dict data type is that "To store (Key,value) in single variable"
=>In (Key,Value), the values of Key is Unique and Values of Value may or may not be unique.
=>The (Key,value) must be organized or stored in the object of dict within Curly Braces {} and they
separated by comma.
=>An object of dict does not support Indexing and Slicing bcoz Values of Key itself considered as
Indices.
=>In the object of dict, Values of Key are treated as Immutable and Values of Value are treated as
mutable.
=>Originally an object of dict is mutable bcoz we can add (Key,Value) externally.
=>We have two types of dict objects. They are
a) Empty dict
b) Non-empty dict
-------------------------
a) Empty dict
-------------------------
=>Empty dict is one, which does not contain any (Key,Value) and whose length is 0
=>Syntax:- dictobj1= { }
or
dictobj=dict()

=>Syntax for adding (Key,Value) to empty dict:


----------------------------------------------------------------
dictobj[Key1]=Val1
dictobj[Key2]=Val2
---------------------------
dictobj[Key-n]=Val-n
Here Key1,Key2...Key-n are called Values of Key and They must be Unique
Here Val1, Val2...Val-n are called Values of Value and They may or may not be unique.
-----------------------------------------------------------------------------------------------------------------------
b) Non-Empty dict
-----------------------------
=>Non-Empty dict is one, which contains (Key,Value) and whose length is >0
=>Syntax:- dictobj1= { Key1:Val1,Key2:Val2......Key-n:Valn}

Here Key1,Key2...Key-n are called Values of Key and They must be Unique
Here Val1, Val2...Val-n are called Values of Value and They may or may not be unique.
=================================================================
Examples:
-----------------
>>> d1={10:"Python",20:"Data Sci",30:"Django"}
>>> print(d1,type(d1))----------{10: 'Python', 20: 'Data Sci', 30: 'Django'} <class 'dict'>
>>> d2={10:3.4,20:4.5,30:5.6,40:3.4}
>>> print(d2,type(d2))------------{10: 3.4, 20: 4.5, 30: 5.6, 40: 3.4} <class 'dict'>
>>> len(d1)--------------3
>>> len(d2)------------4
-------------------------------------------------
>>> d3={}
>>> print(d3,type(d3))------------{} <class 'dict'>
>>> len(d3)-------------0
>>> d4=dict()
>>> print(d4,type(d4))-------------{} <class 'dict'>
>>> len(d4)---------------0
------------------------------------------------------------------------
>>> d2={10:3.4,20:4.5,30:5.6,40:3.4}
>>> print(d2)----------------------------------{10: 3.4, 20: 4.5, 30: 5.6, 40: 3.4}
>>> d2[0]----------------------------------------KeyError: 0
>>> d2[10]-------------------------------------3.4
>>> d2[10]=10.44
>>> print(d2)-------------------------------{10: 10.44, 20: 4.5, 30: 5.6, 40: 3.4}
-------------------------------------------------------------------------------------
>>> d2={10:3.4,20:4.5,30:5.6,40:3.4}
>>> print(d2,type(d2),id(d2))----{10: 3.4, 20: 4.5, 30: 5.6, 40: 3.4} <class 'dict'> 2090750380736
>>> d2[50]=5.5
>>> print(d2,type(d2),id(d2))---{10: 3.4, 20: 4.5, 30: 5.6, 40: 3.4, 50: 5.5} <class 'dict'>

2090750380736
-------------------------------------------------------------------------------------------------------------------------
>>> d3={}
>>> print(d3,type(d3),id(d3))-------------------{} <class 'dict'> 2090750332992
>>> d3["Python"]=1
>>> d3["Java"]=3
>>> d3["C"]=2
>>> d3["GO"]=1
>>> print(d3,type(d3),id(d3))-----{'Python': 1, 'Java': 3, 'C': 2, 'GO': 1} <class 'dict'>

2090750332992
-------------------------------------------------------------------------------------------------------
>>> d4=dict()
>>> print(d4,type(d4),id(d4))---------------{} <class 'dict'> 2090754532032
>>> d4[10]="Apple"
>>> d4[20]="Mango"
>>> d4[30]="Kiwi"
>>> d4[40]="Sberry"
>>> d4[50]="Orange"
>>> print(d4,type(d4),id(d4))---{10: 'Apple', 20: 'Mango', 30: 'Kiwi', 40: 'Sberry', 50: 'Orange'}
<class 'dict'> 2090754532032
>>> d4[10]="Guava"
>>> print(d4,type(d4),id(d4))----{10: 'Guava', 20: 'Mango', 30: 'Kiwi', 40: 'Sberry', 50: 'Orange'}
<class 'dict'> 2090754532032
--------------------------------------------------------------------------------------
>>> d2={10:3.4,20:4.5,30:5.6,40:3.4}
>>> print(d2,type(d2),id(d2))---{10: 3.4, 20: 4.5, 30: 5.6, 40: 3.4} <class 'dict'> 2090754531520
>>> d2[50]=1.2
>>> print(d2,type(d2),id(d2))---{10: 3.4, 20: 4.5, 30: 5.6, 40: 3.4, 50: 1.2} <class 'dict'>
2090754531520
----------------------------------------------------------------.

day – 24

=========================================================
Pre-Defined functions in dict
=========================================================
=>In dict object, we have the following function for performing Various Operations.
--------------------------------------------------------------------------------------------------------------------------
--------
1. clear()
--------------------------------------------------------------------------------------------------------------------------
--------
Syntax: dictobj.clear()
=>This Function is used for Removing all the elements of non-empty dict object
=>If we call this function upon empty dict object then we get None / No Output.
----------------
Examples
----------------
>>> d1={10:"Python",20:"Java",30:"C++",40:"C"}
>>> print(d1,type(d1),id(d1))---{10: 'Python', 20: 'Java', 30: 'C++', 40: 'C'} <class 'dict'>
2364664861568
>>> d1.clear()
>>> print(d1,type(d1),id(d1))----{} <class 'dict'> 2364664861568
>>> print(d1.clear())----------None
>>> print(dict().clear())---------None
>>> print({}.clear())--------------None
--------------------------------------------------------------------------------------------------------------------------
--------
2. pop()
--------------------------------------------------------------------------------------------------------------------------
--------
=>Syntax: dictobj.pop(Key)
---------------
=>This Function is used for Removing (Key,value) from non-empty dictobject by passing Value of
Key.
=>If the Value of Key does not exist then we get KeyError
=>If we call this pop(), upon empty dict object then we get KeyError.
----------------
Examples:
----------------
>>> d1={10:"Python",20:"Java",30:"C++",40:"C"}
>>> print(d1,id(d1))---------------{10: 'Python', 20: 'Java', 30: 'C++', 40: 'C'} 2364669155776
>>> d1.pop(20)--------------------'Java'
>>> print(d1,id(d1))--------------{10: 'Python', 30: 'C++', 40: 'C'} 2364669155776
>>> d1.pop(30)------------------'C++'
>>> d1.pop(40)0---------------'C'
>>> print(d1,id(d1))--------------{10: 'Python'} 2364669155776
>>> d1.pop(50)------------------------KeyError: 50
>>> print(d1,id(d1))--------{10: 'Python'} 2364669155776
>>> d1.pop(10)-------------'Python'
>>> print(d1,id(d1))--------{} 2364669155776
>>> d1.pop(10)-----------KeyError: 10
>>> dict().pop(10)----------------KeyError: 10
>>> {}.pop("Python")-----KeyError: 'Python'
--------------------------------------------------------------------------------------------------------------------------
--------
3. popitem()
--------------------------------------------------------------------------------------------------------------------------
--------
Syntax: dictobj.popitem()
------------
=>This Function is used for Removing Last (Key,value) entry from non-empty dictobject.
=>If we call this popitem(), upon empty dict object then we get KeyError.
Examples:
---------------
>>> d1={10:"Python",20:"Java",30:"C++",40:"C"}
>>> print(d1,id(d1))-------------{10: 'Python', 20: 'Java', 30: 'C++', 40: 'C'} 2364669156096
>>> d1.popitem()---------------(40, 'C')
>>> print(d1,id(d1))------------{10: 'Python', 20: 'Java', 30: 'C++'} 2364669156096
>>> d1.popitem()--------------(30, 'C++')
>>> print(d1,id(d1))----------{10: 'Python', 20: 'Java'} 2364669156096
>>> d1.popitem()-----------(20, 'Java')
>>> print(d1,id(d1))-------------{10: 'Python'} 2364669156096
>>> d1.popitem()-------------(10, 'Python')
>>> print(d1,id(d1))--------------{} 2364669156096
>>> d1.popitem()-----------KeyError: 'popitem(): dictionary is empty'
>>> dict().popitem()----------KeyError: 'popitem(): dictionary is empty'
>>> {}.popitem()-----------KeyError: 'popitem(): dictionary is empty'
--------------------------------------------------------------------------------------------------------------------------
--------
4. copy()
--------------------------------------------------------------------------------------------------------------------------
--------
Syntax: dictobj2=dictobj1.copy()
------------
=>This function is used for Copying the content of One dict object into another dict object.
------------------
Examples:
------------------
>>> d1={10:"Python",20:"Java",30:"C++",40:"C"}
>>> print(d1,id(d1))---------{10: 'Python', 20: 'Java', 30: 'C++', 40: 'C'} 2364669156416
>>> d2=d1.copy() # Shallow Copy
>>> print(d2,id(d2))----{10: 'Python', 20: 'Java', 30: 'C++', 40: 'C'} 2364669156096
>>> d1[50]="Dsc"
>>> d2[60]="Django"
>>> print(d1,id(d1))----{10: 'Python', 20: 'Java', 30: 'C++', 40: 'C', 50: 'Dsc'} 2364669156416
>>> print(d2,id(d2))---{10: 'Python', 20: 'Java', 30: 'C++', 40: 'C', 60: 'Django'} 2364669156096
----------------
Deep Copy Process of dict objects
---------------------
>>> d1={10:"Python",20:"Java",30:"C++",40:"C"}
>>> print(d1,id(d1))---------{10: 'Python', 20: 'Java', 30: 'C++', 40: 'C'} 2364669155776
>>> d2=d1 # Deep Coy
>>> print(d2,id(d2))---------{10: 'Python', 20: 'Java', 30: 'C++', 40: 'C'} 2364669155776
>>> d1[50]="Dsc"
>>> print(d1,id(d1))---------{10: 'Python', 20: 'Java', 30: 'C++', 40: 'C', 50: 'Dsc'} 2364669155776
>>> print(d2,id(d2))---------{10: 'Python', 20: 'Java', 30: 'C++', 40: 'C', 50: 'Dsc'} 2364669155776
--------------------------------------------------------------------------------------------------------------------------
--------
5. get()
--------------------------------------------------------------------------------------------------------------------------
--------
Syntax: This Function is used for obtaining Value of Value by Passing Value of Key.
-----------
=>if the value of Key does not exist then we get None as a result
(OR)
Syntax: dictobj[Key]---->Will give Value of Value if Key Present otherwise get KeyError
----------------
Examples:
----------------
>>> d1={10:"Python",20:"Java",30:"C++",40:"C"}
>>> print(d1,id(d1))-------------{10: 'Python', 20: 'Java', 30: 'C++', 40: 'C'} 2364669156096
>>> v=d1.get(10)
>>> print(v)------------Python
>>> v=d1.get(20)
>>> print(v)-----------Java
#OR
>>> d1.get(10)--------'Python'
>>> d1.get(20)--------'Java'
>>> print(d1.get(200))-------None
>>> v=d1.get(200)
>>> print(v)--------------None
>>> print(dict().get(10))---------None
>>> print({}.get(10))------------None
-------------------------OR----------------------------
>>> d1={10:"Python",20:"Java",30:"C++",40:"C"}
>>> print(d1,id(d1))-----------------{10: 'Python', 20: 'Java', 30: 'C++', 40: 'C'} 2364669156288
>>> d1.get(10)--------------'Python'

>>> d1[10]--------------------'Python'
>>> d1[20]---------------------'Java'
>>> d1[40]--------------------'C'
>>> d1[400]-------------------KeyError: 400
>>> print(d1.get(400))--------None
--------------------------------------------------------------------------------------------------------------------------
--------
6. keys()
--------------------------------------------------------------------------------------------------------------------------
--------
Syntax: varname=dictobj.keys()
------------ (OR)
dictobj.keys()

=>This Function is used for obtaining set of Keys in the form of dict_keys object.
---------------
Examples:
-----------------
>>> d1={10:"Python",20:"Java",30:"C++",40:"C"}
>>> print(d1,id(d1))----------{10: 'Python', 20: 'Java', 30: 'C++', 40: 'C'} 2364669156096
>>> ks=d1.keys()
>>> print(ks,type(ks))---------dict_keys([10, 20, 30, 40]) <class 'dict_keys'>
>>> for k in ks:
... print(k)
...
10
20
30
40
>>> for k in d1.keys():
... print(k)
...
10
20
30
40
>>> for k in d1.keys():
... print(k,"-->",d1.get(k))
...
10 --> Python
20 --> Java
30 --> C++
40 --> C
>>> for k in d1.keys():
... print(k,"-->",d1[k])
...
10 --> Python
20 --> Java
30 --> C++
40 --> C
--------------------------------------------------------------------------------------------------------------------------
--------
7. values()
--------------------------------------------------------------------------------------------------------------------------
--------
Syntax: varname=dictobj.values()
------------ (OR)
dictobj.values()

=>This Function is used for obtaining set of Values in the form of dict_values object.
------------------
Examples
------------------
>>> d1={10:"Python",20:"Java",30:"C++",40:"C"}
>>> print(d1,id(d1))---------{10: 'Python', 20: 'Java', 30: 'C++', 40: 'C'} 2364669156288
>>> vs=d1.values()
>>> print(vs)---------dict_values(['Python', 'Java', 'C++', 'C'])
>>> for v in vs:
... print(v)
...
Python
Java
C++
C
>>> for v in d1.values():
... print(v)
...
Python
Java
C++
C
---------------------------------
MOST IMP
---------------------------------
>>> for x in d1:
... print(x)
...
10
20
30
40

>>> for x in d1:


... print(x,"-->",d1[x])
...
10 --> Python
20 --> Java
30 --> C++
40 --> C
--------------------------------------------------------------------------------------------------------------------------
--------
8. items()
--------------------------------------------------------------------------------------------------------------------------
--------
Syntax: varname=d1.items()
------------
This Function is used for obtaining (Key,value) in the form of tuples of list in the object of
dict_items.
------------------
Examples:
-----------------
>>> d1={10:"Python",20:"Java",30:"C++",40:"C"}
>>> kvs=d1.items()
>>> print(kvs)-------dict_items([(10, 'Python'), (20, 'Java'), (30, 'C++'), (40, 'C')])
>>> for kv in kvs:
... print(kv)
...
(10, 'Python')
(20, 'Java')
(30, 'C++')
(40, 'C')
>>> for kv in d1.items():
... print(kv)
...
(10, 'Python')
(20, 'Java')
(30, 'C++')
(40, 'C')
>>> for k,v in d1.items():
... print(k,"--->",v)
...
10 ---> Python
20 ---> Java
30 ---> C++
40 ---> C
--------------------------------------------------------------------------------------------------------------------------
--------
9. update()
--------------------------------------------------------------------------------------------------------------------------
--------
Syntax: dictobj1.update(dictobj2)

=>This Function isd used for Joining / Updating / Modifying the dictobj1 content with DictObj2
content.
------------------
Exmaples:
------------------
>>> d1={10:1.2,20:3.4,30:4.5}
>>> d2={100:"Apple",200:"Kiwi"}
>>> print(d1,type(d1))------------{10: 1.2, 20: 3.4, 30: 4.5} <class 'dict'>
>>> print(d2,type(d2))--------------{100: 'Apple', 200: 'Kiwi'} <class 'dict'>
>>> d1.update(d2)
>>> print(d1,type(d1))---------{10: 1.2, 20: 3.4, 30: 4.5, 100: 'Apple', 200: 'Kiwi'} <class 'dict'>
>>> print(d2,type(d2))------------{100: 'Apple', 200: 'Kiwi'} <class 'dict'>
---------------------------------------------------
>>> d1={10:1.2,20:3.4,30:4.5}
>>> d2={100:"Apple",20:13.4}
>>> print(d1,type(d1))-----------{10: 1.2, 20: 3.4, 30: 4.5} <class 'dict'>
>>> print(d2,type(d2))-----------{100: 'Apple', 20: 13.4} <class 'dict'>
>>> d1.update(d2)
>>> print(d1,type(d1))--------{10: 1.2, 20: 13.4, 30: 4.5, 100: 'Apple'} <class 'dict'>
>>> print(d2,type(d2))--------{100: 'Apple', 20: 13.4} <class 'dict'>
-------------------------------------------
>>> d1={10:1.2,20:3.4,30:4.5}
>>> d2={10:11.2,20:13.4,30:14.5}
>>> print(d1,type(d1))-----------{10: 1.2, 20: 3.4, 30: 4.5} <class 'dict'>
>>> print(d2,type(d2))-----------{10: 11.2, 20: 13.4, 30: 14.5} <class 'dict'>
>>> d1.update(d2)
>>> print(d1,type(d1))------------{10: 11.2, 20: 13.4, 30: 14.5} <class 'dict'>
>>> print(d2,type(d2))------------{10: 11.2, 20: 13.4, 30: 14.5} <class 'dict'>
==========================x=============================================
=======
Most Imp Points
-----------------------------------------------
=>Dict in Dict--->Possible to write
----------------------------------------------
>>> d1={"sno":10,"sname":"Rossum","imarks":{"cm":17,"cppm":16,"pym":18},"emarks":
{"cm":67,"cppm":78,"pym":70},"cname":"OUCET"}
>>> print(d1,type(d1))
{'sno': 10, 'sname': 'Rossum', 'imarks': {'cm': 17, 'cppm': 16,
'pym': 18}, 'emarks': {'cm': 67, 'cppm': 78, 'pym': 70}, 'cname': 'OUCET'} <class 'dict'>
>>> for k in d1.keys():
... print(k)
...
sno
sname
imarks
emarks
cname
>>> for v in d1.values():
... print(v)
...
10
Rossum
{'cm': 17, 'cppm': 16, 'pym': 18}
{'cm': 67, 'cppm': 78, 'pym': 70}
OUCET
>>> for v in d1.values():
... print(v,type(v))
...
10 <class 'int'>
Rossum <class 'str'>
{'cm': 17, 'cppm': 16, 'pym': 18} <class 'dict'>
{'cm': 67, 'cppm': 78, 'pym': 70} <class 'dict'>
OUCET <class 'str'>
>>> for kv in d1.items():
... print(kv)
...
('sno', 10)
('sname', 'Rossum')
('imarks', {'cm': 17, 'cppm': 16, 'pym': 18})
('emarks', {'cm': 67, 'cppm': 78, 'pym': 70})
('cname', 'OUCET')
>>> for k in d1.keys():
... print(k)
...
sno
sname
imarks
emarks
cname
>>> for k in d1.keys():
... print(k,"--->",d1.get(k))
...
sno ---> 10
sname ---> Rossum
imarks ---> {'cm': 17, 'cppm': 16, 'pym': 18}
emarks ---> {'cm': 67, 'cppm': 78, 'pym': 70}
cname ---> OUCET
>>> for v in d1.get("imarks"):
... print(v)
...
cm
cppm
pym
>>> for v in d1.get("imarks"):
... print(v,"-->",d1.get("imarks").get(v))
...
cm --> 17
cppm --> 16
pym --> 18
>>> for v in d1.get("imarks"):
... print(v,"-->",d1["imarks"][v])
...
cm --> 17
cppm --> 16
pym --> 18
========================================================================
=
In side of dict, we define list,tuple and set also
----------------
Examples:
---------------
>>> d1={"sno":10,"sname":"Rossum","imarks":[16,18,17],"emarks":(60,77,67),"crs":
{"B.Tech(cse)", "M.Tech(AI)"}, "cname":"OUECT"}
>>> for k,v in d1.items():
... print(k,"-->",v,"--->",type(v))
...
sno --> 10 ---> <class 'int'>
sname --> Rossum ---> <class 'str'>
imarks --> [16, 18, 17] ---> <class 'list'>
emarks --> (60, 77, 67) ---> <class 'tuple'>
crs --> {'B.Tech(cse)', 'M.Tech(AI)'} ---> <class 'set'>
cname --> OUECT ---> <class 'str'>
========================================================================
=
dict in list is Possible
----------------------------------
Examples
-----------------
>>> l1=[10,"Rossum",{"cm":16,"cppm":17,"pym":18},"OUCET"]
>>> print(l1,type(l1))---[10, 'Rossum', {'cm': 16, 'cppm': 17, 'pym': 18}, 'OUCET'] <class 'list'>
>>> for val in l1:
... print(val,type(val))
...
10 <class 'int'>
Rossum <class 'str'>
{'cm': 16, 'cppm': 17, 'pym': 18} <class 'dict'>
OUCET <class 'str'>
>>> for k,v in l1[2].items():
... print(k,"--->",v)
...
cm ---> 16
cppm ---> 17
pym ---> 18
------------------------------------------------------------------
dict in tuple is Possible
------------------------------------------------------------------
Examples:
---------------------------------------------
>>> t1=(10,"Rossum",{"cm":16,"cppm":17,"pym":18},"OUCET")
>>> print(t1,type(t1))----------(10, 'Rossum', {'cm': 16, 'cppm': 17, 'pym': 18}, 'OUCET') <class
'tuple'>
>>> for val in t1:
... print(val,type(val))
...
10 <class 'int'>
Rossum <class 'str'>
{'cm': 16, 'cppm': 17, 'pym': 18} <class 'dict'>
OUCET <class 'str'>
>>> for k,v in t1[-2].items():
... print(k,"-->",v)
...
cm --> 16
cppm --> 17
pym --> 18
--------------------------------------------------------------------------------------
dict in set not possible
--------------------------------------------------------------------------------------
>>> s1={10,"Rossum",{"cm":16,"cppm":17,"pym":18},"OUCET"}--TypeError: unhashable type:
'dict'
--------------------------------------------------------------------------------------------------------------------------
---------------

==========================
NoneType data type
=======================================
=>'NoneType' is one the pre-defined class and treated as None type Data type
=> "None" is keyword acts as value for <class,'NoneType'>
=>The value of 'None' is not False, Space , empty , 0
=>An object of NoneType class can't be created explicitly.
--------------------------------------------------------------------
Examples:
------------------
>>> a=None
>>> print(a,type(a))------------None <class 'NoneType'>
>>> a=NoneType()---------NameError: name 'NoneType' is not defined
>>> l1=[]
>>> print(l1.clear())------------None
>>> s1=set()
>>> print(s1.clear())---------None
>>> d1=dict()
>>> print(d1.clear())-----------None
>>> d1={10:1.2,20:3.4}
>>> print(d1.get(100))---------None
-------------------------------------------------------------------------------------------------------------------
--------------------------------.

DAY – 25
----.

number of approaches for developing python programs

def ---

set of optimized instructions is called program.


Optimized instructions are nothing but they takes less memory space and less Execution Time.
– the purpose of writing programs in any language is that ----
– two approaches
1. by using interactive Approach
2. By using Batch Mode Approach

1. by using interactive approach


– Interactive Approach can issue /write Programmer can issue /Write python program on ide

========================================================
Number of approaches for developing Python Programs
========================================================
---------------------------
=>Def. of Program:
---------------------------
=>Set of Optimized Instructions is Called Program.
=>Optimized Instructions are nothing but they takes Less Memory Space and Less Execution Time.
=>The Purpose of Writing Programs in any Language is that " To Solve Real Time Problems".
-----------------------------
=>In Python Programming, we have Two Approaches to write the Programs. They are
1. By using Interactive Approach
2. By using Batch Mode Approach
--------------------------------------------------------------------------------------------------------------------------
------
1. By using Interactive Approach
--------------------------------------------------------------------------------------------------------------------------
------
=>Interactive Approach, Python Programmer can Issue / Write Single Instruction at a time and gets
the
result Immediately.
=>Interactive Approach is recommended to test One Instruction at a Time But Not suitable for Big
Problem Solving approaches.
=>To Develop Big Problem Solving approaches, we must use Batch Mode Approach
------------------------------
Examples Softwares:
------------------------------
1) Python Command Prompt
2) Python IDLE Shell

=>The above Two Softwares Comes along with Python Software Installation
--------------------------------------------------------------------------------------------------------------------------
------
2. By using Batch Mode Approach
--------------------------------------------------------------------------------------------------------------------------
------
=>In Batch Mode Approach, we Define / Write set of Optmized Instructions in an Editor and we must
save on some File name with extension .py (FileName.py) and It is called Program.
=>Batch Mode Approach is always Useful for Developing Big Problem Solving approaches.
---------------------------------
Examples Softwares
---------------------------------
1) Python IDLE Shell---->ThisSoftwares Comes along with Python Software
Installation
=>In Real Time we may not Use PYTHON IDLE SHELL bcoz It may be poor in Providing in-buitlt
facilities
to the Python Programmer and Hence Industry is recommeded to use Third Party IDES
=>Some of the Third Party IDEs are
1) PyCharm
2) Ankonda Jupiter Note Book
3) VS Code
4) Spider
5) Sublime Text
6) Atom
7) Google Calb
8) Eclipse...etc
--------------------------------------------------------------------------------------------------------------------------
------.

# Program for computing sum of two numbers


a = 10
b = 20
c = a+b
print("------------------------")
print("Val of a=", a)
print("Val of b=", b)
print("Sum=", c)
print("------------------------")
#program for computing Mul of Two Numbers
a=int(input("Enter Value of a:"))
b=int(input("Enter value of b:"))
c=a*b
print("********************************")
print("Val of a=",a)
print("Val of b=",b)
print("Multiplication=",c)
print("********************************")

DAY = 26

Displaying the Result of Python Program on the Console

– To display the result of Python on the Console ,we use a pre-defined Function called print().
– In
Otherwords,print()=====================================================
=
– Displaying the Result of Python Program on the Console
– =======================================================
– =>To Display the Result of Python Program on the Console, we use a pre-defined Function
called print().
– =>In Otherwords, print() is used for Display the Result of Python Program on the Console.
– =>we can print() with the following Syntaxes
– ===================================================================
=============
– Syntax-1 : print(Variable)
– OR
– print(Var1,Var2,....Var-n)
– ===================================================================
=============
– =>This Syntax generates either Single Variable Val or Multiple variable values.
– ---------------------
– =>Examples:
– ---------------------
– >>> a=10
– >>> print(a)------10
– >>> b=20
– >>> print(b)------20
– >>> c=a+b
– >>> print(a,b,c)-----10 20 30
– ===================================================================
=============
– Syntax-2: print(Message)
– (OR)
– print(msg1,msg2,...msg-n)
– ===================================================================
=============
– =>Here Mssage, msg1,msg2....msg-n are called str type
– =>This Syntax display the Message(s)
– ----------------------
– Examples
– ----------------------
– >>> print("hello Python world")----------hello Python world
– >>> print('hello Python world')-----------hello Python world
– >>> print('''hello Python world''')-------hello Python world
– >>> print("""hello Python world""")-----hello Python world
– >>> print("Hello","Python","World")-------Hello Python World
– >>> print("Hello" + "Python" + "World")---HelloPythonWorld
– >>> print("Hello"+" "+"Python"+" "+"World")---Hello Python World
– NOTE: Here + operator is used for concatination of str values
– >>> print("Python"+3.11)---TypeError: can only concatenate str (not "float") to str
– >>> print("Python"+str(3.11))---------Python3.11
– ===================================================================
=============
– Syntax-3: print(Messages Cum Values)
– (OR)
– print(Values cum Messages)
– ===================================================================
=============
– =>This Syntax displays Values Cum Messages OR Messages Cum Values.
– -----------------
– Examples:
– -----------------
– >>> a=10
– >>> print("Val of a="+a)--------TypeError: can only concatenate str (not "int") to str
– >>> print("Val of a="+str(a))-----Val of a=10
– OR
– >>> print("Val of a=",a)-----------Val of a= 10
– OR
– >>> a=10
– >>> print(a,"is the value of a")-------10 is the value of a
– >>> print(str(a)+" is the value of a")--10 is the value of a
– ---------------------------
– >>> a=10
– >>> b=20
– >>> c=a+b
– >>> print("sum=",c)-----------sum= 30
– >>> print(c,"is the sum")-------30 is the sum
– >>> print("sum of",a,"and",b,"=",c)-------sum of 10 and 20 = 30
– -----------------------------------------------------------------------------------
– >>> a=10
– >>> b=20
– >>> c=30
– >>> d=a+b+c
– >>> print("Sum of",a,",",b,"and",c,"=",d)---------Sum of 10 , 20 and 30 = 60
– ===================================================================
=============
– Syntax-4: print(Messages Cum Values with format() )
– (OR)
– print(Values cum Messages with format() )
– ===================================================================
=============
– =>This Syntax displays Values Cum Messages OR Messages Cum Values with format()
– -------------------------
– Examples
– -------------------------
– >>> a=10
– >>> print("Val of a={}".format(a) )--------Val of a=10
– >>> print("{} is the value of a".format(a))----10 is the value of a
– -------------------
– >>> sno=10
– >>> name="Ram"
– >>> print("My Number is {} and name is {}".format(sno,name))--My Number is 10 and
name is Ram
– -----------------------
– >>> a=10
– >>> b=20
– >>> c=a+b
– >>> print("Sum of {} and {}={}".format(a,b,c))---Sum of 10 and 20=30
– >>> print("sum({},{})={}".format(a,b,c))---sum(10,20)=30
– ===================================================================
=============
– Syntax-5: print(Messages Cum Values with format specifier )
– (OR)
– print(Values cum Messages with format specifier )
– ===================================================================
=============
– =>This Syntax displays Values Cum Messages OR Messages Cum Values with format
Specifiers
– =>In Python Programming, we Use %d for displying Integer data, %f for displying float data
and %s for
– displaying str data.
– =>In Any Value does not contain any format specifier and if we want to dispay such type of
Values then
– we must convert them into str by using str() and use %s.
– ---------------------------------
– Examples
– ---------------------------------
– >>> sno=10
– >>> sname="Ram"
– >>> marks=44.56
– >>> print("My Number is %d and name is %s and marks is %f" %(sno,sname,marks))
– My Number is 10 and name is Ram and marks is
44.560000
– >>> print("My Number is %d and name is %s and marks is %0.2f" %(sno,sname,marks))
– My Number is 10 and name is Ram and marks is 44.56
– >>> print("My Number is %d and name is %s and marks is %0.3f" %(sno,sname,marks))
– My Number is 10 and name is Ram and marks is 44.560
– ------------------------------------------------
– >>> a=10
– >>> b=20
– >>> c=a+b
– >>> print("sum of %d and %d=%d" %(a,b,c))---sum of 10 and 20=30
– >>> print("sum of %f and %f=%f" %(a,b,c))-----sum of 10.000000 and
20.000000=30.000000
– >>> print("sum of %0.2f and %0.2f=%0.3f" %(a,b,c))--sum of 10.00 and 20.00=30.000
– -----------------------------
– >>> lst=[100,"Ram",45.67,"Python",True]
– >>> print("Content of list=",lst)----------Content of list= [100, 'Ram', 45.67, 'Python', True]
– >>> print("Content of list={}".format(lst))-----Content of list=[100, 'Ram', 45.67, 'Python',
True]
– >>> print("Content of list=%d" %lst)---TypeError: %d format: a real number is required, not
list
– >>> print("Content of list=%s" %str(lst))---Content of list=[100, 'Ram', 45.67, 'Python', True]
– ----------------------------------------
– >>> d1={10:"Dinesh",20:"Ram",30:"Naresh"}
– >>> print("Content of dict=%s" %str(d1))-----Content of dict={10: 'Dinesh', 20: 'Ram', 30:
'Naresh'}
– ===================================================================
=============
– Syntax-6: print(Value, end=" ")
– ===================================================================
=============
– =>This Syntax displays the values on the console in same Line.
– -----------------
– Examples:
– -----------------
– >>> r=range(10,101,20)
– >>> for val in r:
– ... print(val)
– ...
– 10
– 30
– 50
– 70
– 90
– >>> for val in r:
– ... print(val,end=" ")---- 10 30 50 70 90
– --------------
– >>> for val in r:
– ... print(val,end="->")-------- 10->30->50->70->90
– =============================x===============================
– Most Imp
– =============================================================
– >>> s="PYTHON"
– >>> print(s)------------PYTHON
– >>> s=s+s+s
– >>> print(s)------------PYTHONPYTHONPYTHON
– -----------------------
– >>> s="PYTHON"
– >>> print(s)-----------PYTHON
– >>> s=s*3 # Here * is called Repetation Operator
– >>> print(s)----------PYTHONPYTHONPYTHON
– >>> print(2*3) # Here * is called Mul Operator
– 6
– >>> print("KVR"*5)------------KVRKVRKVRKVRKVR
– >>> print("22"*4)-------------22222222
– >>> print("22"*"4")--------------TypeError: can't multiply sequence by non-int of type 'str'
– ----------------------------------
– >>> print("=")------ =
– >>> print("="*25) # ==========================================
– ===============================================/

DAY – 27

===========================================================
Reading the Data Dynamically from Key Board
===========================================================
=>To Read the Data Dynamically from Key Board, we Have 2 Pre-defined Functions. They are

1. input()
2. input(message)
--------------------------------------------------------------------------------------------------------------------------
-------
1. input()
--------------------------------------------------------------------------------------------------------------------------
-------
=>Syntax: varname=input()
=>The purpose of input() is that to read any type of data from Key Board in the form of str.
=>The str value can be converted into other data type value by using Type Casting functions.
--------------------------------------------------------------------------------------------------------------------------
-------
2. input(Message)
--------------------------------------------------------------------------------------------------------------------------
-------
=>Syntax: varname=input(Message)
=>Here Message represents User-Prompting Message and it is of type str
=>The input(Message) is used for reading any type of data from Key board in the form of str and
Additionally It will prompt User Messages.
------------------------------------------------------------------------------.

#program for Multiplication of two Numbers


print("Enter First value:")
s1=input()
print("Enter Second Value:")
s2=input()
#Convert s1 and s2 into float type
a=float(s1)
b=float(s2)
#multiply
c=a*b
#display the result
print("Mul({},{})={}".format(a,b,c))
-----------------------------------------------------------------------.

#DataReadEx2.py
print("Enter Two Values")
a=input()
b=input()
#convert a and b into float type
x=float(a)
y=float(b)
z=x*y
print("Mul({},{})={}".format(x,y,z))

-------------------------------------------------------------------------.

#DataReadEx3.py
print("Enter Two Values")
x=float(input()) # Reading the data and converting
y=float(input()) # Reading the data and converting
z=x*y
print("Mul({},{})={}".format(x,y,z))

-------------------------------------------------------------------------------.

#DataReadEx4.py
print("Enter Two Values")
x=float(input()) # Reading the data and converting
y=float(input()) # Reading the data and converting
print("Mul({},{})={}".format(x,y,x*y))

---------------------------------------------------------------------------------.

#program for Multiplication of two Numbers


#DataReadEx5.py
a=input("Enter First Value:")
b=input("Enter Second Value:")
#convert a and b into float type
x=float(a)
y=float(b)
z=x*y
print("Mul({},{})={}".format(x,y,z))
-----------------------------------------------------------------------------------.
#program for Multiplication of two Numbers
#DataReadEx6.py
x=float(input("Enter First Value:"))
y=float(input("Enter Second Value:"))
print("Mul({},{})={}".format(x,y,x*y))

hw.
1. write a python program which will calculate area of circle
#Program for cal area of Circle
2. #CircleArea.py
3. r=float(input("Enter Radious:"))
4. ac=3.14*r*r
5. print("="*50)
6. print("Radius:{}".format(r))
7. print("Area of Circle:%0.2f" %ac)
8. print("="*50)

write a python program which will calculate perimater are cercumfrance of circle

write a python program which will calculate area and crcumfrence of rectangle

#Program cal area and Perimeter of rectangle


#RectAreaPeri.py
l=float(input("Enter Length:"))
b=float(input("Enter Breadth:"))
#cal area and Peri of rectangle
ar=l*b
pr=2*(l+b)
print("="*50)
print("\tLength={}".format(l))
print("\tBreadth={}".format(b))
print("\tArea of Rect={}".format(ar))
print("\tPeri.of Rect:{}".format(pr))
print("="*50)

write a python program which will calculate area of triangle '

#Program for acl area of Triangle


#TriangleArea.py
b=float(input("Enter Base:"))
h=float(input("Enter Height:"))
#cal area of Triangle
at=1/2*b*h
print("="*50)
print("\tBase:{}".format(b))
print("\tHeight:{}".format(h))
print("\tArea of Triangle:{}".format(at))
print("="*50)

write a python program which will conver celsius temp into foren heat and kelvin.
Write a python program area and perimater of sequare
simple intrest and the total amount to pay
#program for cal simple Interest and total amount to pay
#SimpleInt.py
p=float(input("Enter Principle Amount:"))
t=float(input('Enter Time:'))
r=float(input("Enter rate of interest:"))
#cal si and totamt to pay
si=(p*t*r)/100
totamt=p+si
print("*"*50)
print("Simple Interest Calculations")
print("*"*50)
print("\tPrinciple Amount:{}".format(p))
print("\tTime:{}".format(t))
print("\tRate of Interest:{}".format(r))
print("\tSimple Interest:{}".format(si))
print("\tTOTAL AMOUNT TO PAY:%0.2f" %totamt)
print("*"*50)

day – 28

==================================================
Operators and Expressions in Python
==================================================
=>An operator is a symbol, which is used to perform Certain Operation on given data and gives
Result.
=>If Two or More Variables (Objects) Connected with an Operator then it is Called Expression,
=>In Otherwords, An Expression is a Collection of Variables (objects) connected with an an
Operator.
=>In Python Programming, we have 7 Operators. They are

1. Arithmetic Operators
2. Assignment Operator
3. Relational Operators (Comparision Operators)
4. Logical Operators (Comparision Operators)
5. Bitwise Operators ( Most Imp )
6. Membership Operators
a) in
b) not in
7. Identity Operators
a) is
b) is not
====================================================================

NOTE1: Python Programming does not Support Unary Operators ( ++ , - - )


------------
NOTE2: Python Programming does not Support Ternary Operator of C,C++,C#.net, Java ( ? : )
--------------------------------------------------------------------------------------------------------------------------
----------------
NOTE3: Python Programming Contains Short Hand Operators
------------------
NOTE4: Python Programming Contains Its own Ternary Operator-- if...else operator
--------------------------------------------------------------------------------------------------------------------------
---------------.

=======================================================
1. Arithmetic Operators
=======================================================
=>The purpose of Arithmetic Operators is that "To perform Arithmetic Operations such as
Addition,Substraction, Multiplicaion..etc".
=>If two or more Variables (Objects) connected with Arithmetic Operators then we call it as
Arithmetic
Expression.
=>In Python Programming, we have 7 Arithmetic Operators. They are given in the following table.
========================================================================
=========
SLNO SYMBOL MEANING EXAMPLE a=10 b=3
========================================================================
=========
1. + Addition print(a+b)----------
>13

2. - Substraction print(a-b)----------->7

3. * Multiplication print(a*b)----------->30

4. / Division print(a/b)----------
>3.333333333333335
(Float Quotient)

5. // Floor Division print(a//b)---------->3


(Integer Quotient)

6. % Modulo Division print(a%b)--------->1


(remainder)
7. ** Exponentiation print(a**b)--------->1000
(power of )
========================================================================
=========

#Program for deminstarting Arithmetic Operators


#ArithmeticOpEx1.py
a=int(input("Enter Value of a:"))
b=int(input("Enter Value of b:"))
print("="*50)
print("\tARITHMETIC OPERATORS RESULTS")
print("="*50)
print("\t{}+{}={}".format(a,b,a+b))
print("\t{}-{}={}".format(a,b,a-b))
print("\t{}*{}={}".format(a,b,a*b))
print("\t{}/{}={}".format(a,b,a/b))
print("\t{}//{}={}".format(a,b,a//b))
print("\t{}%{}={}".format(a,b,a%b))
print("\t{}**{}={}".format(a,b,a**b))
print("="*50)

write squaroot of a given number

#Program for cal square root of a given number


#ArithmeticOpEx2.py
n=int(input("Enter a number for cal Square Root:"))
res=n**0.5
print("sqrt({})={}".format(n,res))
print("===========OR==============")
res=n**(1/2)
print("sqrt({})={}".format(n,res))

write a python program which will calculate qube root ob given number

write a python program which will calculate (a+b) square

write a python program which will evaluate a^m/a^n

write a python program which will evaluate (a^m)^n

==================================================
2. Assigment Operator
==================================================
=>The purpose of assignment operator is that " To assign or transfer Right Hand Side (RHS) Value /
Expression Value to the Left Hand Side (LHS) Variable "
=>The Symbol for Assigment Operator is single equal to ( = ).
=>In Python Programming,we can use Assigment Operator in two ways.
1. Single Line Assigment
2. Multi Line Assigment

1. Single Line Assigment:


----------------------------------------
=>Syntax: LHS Varname= RHS Value
LHS Varname= RHS Expression

=>With Single Line Assigment at a time we can assign one RHS Value / Expression to the single
LHS Variable Name.
------------------
Examples:
-----------------
>>> a=10
>>> b=20
>>> c=a+b
>>> print(a,b,c)------------10 20 30
-----------------------------------------------------------------------------------
2. Multi Line Assigment:
----------------------------------------
=>Syntax: Var1,Var2.....Var-n = Val1,Val2....Val-n

Var1,Var2.....Var-n= Expr1,Expr2...Expr-n

Here The values of Val1, Val2...Val-n are assigned to Var1,Var2...Var-n Respectively.


Here The values of Expr1, Expr2...Expr-n are assigned to Var1,Var2...Var-n Respectively.

Examples:
-------------------
>>> a,b=10,20
>>> print(a,b)------------10 20
>>> c,d,e=a+b,a-b,a*b
>>> print(c,d,e)-------------30 -10 200
>>> sno,sname,marks=10,"Rossum",34.56
>>> print(sno,sname,marks)---------10 Rossum 34.56
===================================X====================================
==
ex:-
a=input(“enter”)
b=input(“value”)

DAY = 29

==================================================
3. Relational Operators (Comparision Operators)
=====================================================
=>The purpose of Relational Operators is that " To Compare Two Values OR Object Values".
=>If two or More Variables OR Objects Connected with Relational Operators then we it as Relational
Expression.
=>The Result of Relational Expression is Either True of False.
=>The Relational Expression is also Called Test Condition and it gives Either True or False.
=>In Python Programming, we have 6 Relational Operators. They are given in the following Table.
========================================================================
======
SLNO SYMBOL MEANING EXAMPLES
========================================================================
======
1. > Greater Than print(10>5)---------True
print(100>200)-----
False

2. < LessThan print(10<20)-------True


print(100<50)------
False

3. == Equality print(10==20)------
False
(double equal to) print(100==100)---True

4. != Not Equal to print(10!=20)-------True


print(100!=100)----
False

5. >= Greater Than print(10>=20)------False


or equal to print(10>=5)--------True

6. <= Less Than print(10<=20)-----True


or Equal to print(100<=50)----False
========================================================================
======.

#Program for demonstrating Relational Operators


#RelOpEx1.py
a=int(input("Enter Value of a:"))
b=int(input("Enter Value of b:"))
print("="*50)
print("Reuslts of Relational Operators")
print("="*50)
print("\t\t{} > {}={}".format(a,b,a>b)) # here a>b is called Rel Expr
print("\t\t{} < {}={}".format(a,b,a<b))
print("\t\t{} == {}={}".format(a,b,a==b))
print("\t\t{} != {}={}".format(a,b,a!=b))
print("\t\t{} >= {}={}".format(a,b,a>=b))
print("\t\t{} <= {}={}".format(a,b,a<=b))
print("="*50)

===================================================
4. Logical Operators (Comparision Operators)
===================================================
=>The purpose of Logical Operators is that "To Combine Two or More Relational Expressions".
=>If Two or More Rerlational Expressions are connected with Logical Operators then we call it as
Logical
Expressions OR Compound Condition.
=>The Result of Logical Expressions OR Compound Condition gives either True of False.
=>In Python Programming, we have 3 Types of Logical Operators and They are given in the
following Table.
========================================================================
=========
SLNO SYMBOL MEANING
========================================================================
=========
1. and Physical ANDing

2. or Physical ORing

3. not ------------------------
========================================================================
=========
1) and Operator
=================
=>The Functionality of 'and' Operator is given in the following Truth Table
-------------------------------------------------------------------------------------
RelExpr1 RelExpr2 RelExpr1 and RelExpr2
-------------------------------------------------------------------------------------
True False False

False True False

False False False

True True True


-------------------------------------------------------------------------------------
Examples:
------------------
>>> True and False----------False
>>> False and False---------False
>>> False and True----------False
>>> True and True-----------True
-------------------------------
>>> 10>5 and 20>40-------------False
>>> 10<30 and 30>3------------True
>>> 10<5 and 20>15------------False---Short Circuit Evaluation
>>> 10>20 and 45>30 and 45>20-------False--Short Circuit Evaluation
>>> 10>5 and 20>30 and 40>5 and -10>-20-----False---Short Circuit Evaluation
--------------------------------------------------------------------------------
Short Circuit Evaluation in the case of 'and' Operator
--------------------------------------------------------------------------------
=>If Two or More relational expressions are connected with 'and' Operator (Logical Expression) and
if
First Relational Expr result is False then PVM will not evaluate rest of the Relational Expressions
and PVM Gives result of Entire Logical Expression as False. This Process of Evaulation is called
"Short Circuit Evaluation".
========================================================================
=======
2) or Operator
=================
=>The Functionality of 'or' Operator is given in the following Truth Table
-------------------------------------------------------------------------------------
RelExpr1 RelExpr2 RelExpr1 or RelExpr2
-------------------------------------------------------------------------------------
True False True

False True True

False False False

True True True


-------------------------------------------------------------------------------------
Examples:
------------------
>>> True or False----------True
>>> False or True---------True
>>> False or False-------False
>>> True or True---------True
------------------------------------------------
>>> 10<5 or 30>20---------True
>>> 10>20 or 20>30 or 40>20-------True
>>> 10>20 or 20>30 or 40>40----False
>>> 10>5 or 20>40 or 40>30----True----Short Circuit Evaluation
>>> 100>200 or 500>2 or 500>1000 or -10>-5---True---Short Circuit Evaluation
--------------------------------------------------------------------------------
Short Circuit Evaluation in the case of 'or' Operator
--------------------------------------------------------------------------------
=>If Two or More relational expressions are connected with 'or' Operator (Logical Expression) and if
First Relational Expr result is True then PVM will not evaluate rest of the Relational Expressions
and PVM Gives result of Entire Logical Expression as True. This Process of Evaulation is called
"Short Circuit Evaluation".
========================================================================
=======
3) not Operator
=================
=>The Functionality of 'not' Operator is given in the following Truth Table
-------------------------------------------------------------------------------------
RelExpr1 not RelExpr1
-------------------------------------------------------------------------------------
True False

False True
-------------------------------------------------------------------------------------
Examples:
------------------
>>> a=True
>>> print(a,type(a))--------True <class 'bool'>
>>> b=not a
>>> print(b,type(b))-------False <class 'bool'>
-----------------------------
>>> print(10>20)--------False
>>> print(not 10>20)----True
>>> print(not 100)-------False
>>> print(not -100)------False
>>> print(not 0)---------True
>>> 10>20 and 30>40------False
>>> not(10>20 and 30>40)-----True
>>> 10>2 or 20>40----------------True
>>> not(10>2 or 20>40)---------False
-------------------
>>> print(not "Python")--------False
>>> print(not "")------------------True
========================================================================
=====
MOST IMP Questions
--------------------------------------------------------
>>> 100 and 200---------------200
>>> -100 and -150------------- -150
>>> 100 and 200 and 300---- 300
>>> 100 and 0 and 400-------- 0
>>> 100 and True and False and 234---- False
>>> "PYTHON" and "False" and "JAVA"----'JAVA'
>>> #----------------------------------------------
>>> 10 or 20---------------10
>>> 10 or 20 or 0---------10
>>> 0 or 20 or 30--------20
>>> 0 or 20 or 0---------20
>>> "False" or "True" or "False"-------'False'
>>> False or "True" or "False"---------'True'
>>> False or True or "False"-----------True
>> 100 and 200 or 300---------200
>>> 100 or 200 and 300 and -100 or 201---- 100
>>> "Python" and "Java" and "Django" or "Python-Dsc"---'Django'
>>> True and False or True or False and True and 100----True
========================================================================
========
day --- 30
---------------------.

===================================================
5. Bitwise Operators ( Most Imp )
===================================================
=>The Purpose of Bitwise Operators is that "To Perform operations on Binary data in the form of Bit
by
Bit.
=>The Bitwise Operators are applicable on Integer data only but not on floating point values bcoz
Integer values contains Certainity where as floating point values does not contain certainity.
=>The Execution Process of Bitwise Operators is that " First Given Integer data Converted into
Binary
Data, and Operations performed on Binary data in the form of Bit by Bit Depends on Bitwise
Operator and Hence these operator are named as Bitwise Operators ".
=>In Python Programming, we have 6 Types of Bitwise Operators. They are

1. Bitwise Left Shift Operator ( << )


2. Bitwise Right Shift Operator ( >> )
3. Bitwise OR Operator ( | )
4. Bitwise AND Operator ( & )
5. Bitwise Complement Operator ( ~ )
6. Bitwise XOR Operator ( ^ )
========================================================================
======.
\

=======================================
1. Bitwise Left Shift Operator ( << )
=======================================
------------
Syntax: varname=GivenNumber << No. of Bits
------------
Concept: The Bitwise Left Shift Operator ( << ) shifts No. of Bits Towards Left Side By
--------------adding No. of Zero at Right Side (depends on No. of Bits). So that result value will
displayed in
the form of decial number system.
-------------------
Examples:
------------------
>>> a=10
>>> b=3
>>> c=a<<b
>>> print(c)-----------80
>>> print(10<<3)--------80
>>> print(3<<2)---------12
>>> print(100<<2)-----400
>>>print(20<<2)-----80
>>> print(25<<3)-----200
-----------------------------------------------------------------------------------.

=======================================
2. Bitwise Right Shift Operator ( >> )
=======================================
------------
Syntax: varname=GivenNumber >> No. of Bits
--------------
Concept: The Bitwise Right Shift Operator ( >> ) shifts No. of Bits Towards Right Side
------------- By Adding No. of Zero at Left Side (depends on No. of Bits). So that
result value will displayed in the form of decial number system .

Examples:
-----------------
>>> a=10
>>> b=3
>>> c=a>>b
>>> print(c)----------------1
>>> print(10>>2)----------2
>>> print(25>>4)----------1
>>> print(24>>3)---------3
>>> print(50>>4)--------3
>>> print(45>>2)--------11
-------------------------------------------------------------------------------------------------.

3. Bitwise OR Operator ( | )
======================================
=>The Functionality of Bitwise OR Operator ( | ) is shown in the following Truth table.

=> ------------------------------------------------------------
var1 var2 var1 | var2
------------------------------------------------------------
0 1 1
1 0 1
0 0 0
1 1 1
------------------------------------------------------------
------------------------------
Examples
------------------------------
>>> 0|0-----------0
>>> 0|1-----------1
>>> 1|0-----------1
>>> 1|1-----------1
-------------------------------
>>> a=10
>>> b=12
>>> c=a|b
>>> print(c)--------14
>>> print(5|4)----5
-----------------------------
Most Imp Points
-----------------------------
>>>s1={10,20,30}
>>>s2={10,15,25}
>>> s3=s1|s2 # Bitwise OR Operator for UNION Operation
>>> print(s3,type(s3))--------{20, 25, 10, 30, 15} <class 'set'>
--------------------------
>>> s1={"Python","Data Sci"}
>>> s2={"C","C++","DSA"}
>>> print(s1,type(s1))------------{'Python', 'Data Sci'} <class 'set'>
>>> print(s2,type(s2))-----------{'C', 'DSA', 'C++'} <class 'set'>
>>> s3=s1|s2
>>> print(s3,type(s3))---------{'C', 'DSA', 'C++', 'Python', 'Data Sci'} <class 'set'>
=====================================x==================================
======================================
4. Bitwise AND Operator (& )
======================================
=>The Functionality of Bitwise AND Operator ( | ) is shown in the following Truth table.

=> ------------------------------------------------------------
var1 var2 var1 & var2
------------------------------------------------------------
0 1 0
1 0 0
0 0 0
1 1 1
------------------------------------------------------------

Examples
----------------------------------
>>> 0&1---------------0
>>> 1&0---------------0
>>> 0&0---------------0
>>> 1&1---------------1
-----------------------------------
>>> a=8
>>> b=6
>>> c=a&b
>>> print(c)-------0
------------------
>>> a=10
>>> b=12
>>> c=a&b
>>> print(c)--------8
-----------------------------
Most Imp Points
-----------------------------
>>>s1={10,20,30}
>>>s2={10,15,25}
>>> s3=s1&s2 # Bitwise AND Operator for INTERSECTION Operation
>>> print(s3,type(s3))-------{10} <class 'set'>
--------------------------------------------
>>> s1={"Python","Data Sci"}
>>> s2={"C","C++","DSA","Python"}
>>> s3=s1&s2
>>> print(s3,type(s3))----------{'Python'} <class 'set'>
-----------------------
>>> s1={"Python","Data Sci"}
>>> s2={"C","C++","DSA"}
>>> s3=s1&s2
>>> print(s3,type(s3))-----------set() <class 'set'>
======================================x===============================

=====================================x==================================.

day – 31
----------.

================================================
Bitwise Complement Operator ( ~ )
================================================
=Syntax: varname = ~Value
=>The Bitwise Complement Operator ( ~ ) will Invert the Binary Bits.
=>Inverting the Bits are nothing but 1 becomes 0 and 0 becomes 1
=>Formula:- Formula for ~Value = - ( Value+1 )
---------------------------------------------- ----------------------------------------------------------
Examples:
---------------------------------------------------------------------------------------------------------
>>>a=10
>>>b=~a
>>>print("Val of b=",b)--------------- -11
>>> a=35
>>> b=~a
>>> print("Val of b=",b)----------------Val of b= -36
>>> a=-101
>>> b=~a
>>> print("Val of b=",b)----------------Val of b= 100
---------------------------------------------------------------------------------------------------------.
======================================
6. Bitwise XOR Operator ( ^ )
======================================
=>The Functionality of Bitwise XOR Operator ( ^ ) is shown in the following Truth table.

=> ------------------------------------------------------------
var1 var2 var1 ^ var2
------------------------------------------------------------
0 1 1
1 0 1
0 0 0
1 1 0
------------------------------------------------------------
------------------------------
Examples
------------------------------
>>> 1^0-------------1
>>> 0^1-------------1
>>> 0^0-------------0
>>> 1^1-------------0
------------------------------
Examples:
-----------------------------
>>> a=10
>>> b=5
>>> c=a^b
>>> print(c)--------------15
----------------
>>> a=10
>>> b=4
>>> c=a^b
>>> print(c)------------14
>>> a=9
>>> b=8
>>> c=a^b
>>> print(c)--------------1
>>> print(4^4)-----------0
=====================================x==================================
Most Imp Points
----------------------------------
>>> a={10,20,30}
>>> b={-10,15,25}
>>> c=a.symmetric_difference(b)
>>> print(c,type(c))-------------{15, 20, 25, 30} <class 'set'>
>>> d=a^b
>>> print(d,type(d))--------{15, 20, 25, 30} <class 'set'>
===========================.

#SwapXOR.py
a=int(input("Enter Value of a:"))
b=int(input("Enter Value of b:"))
print("="*50)
print("Original value of a={}".format(a))
print("Original value of b={}".format(b))
print("="*50)
#Swapping Logic with XOR
a=a^b
b=a^b
a=a^b
print("Swapped value of a={}".format(a))
print("Swapped value of b={}".format(b))
print("="*50)

write a python program which will interchange or swaw two numerical value by using bitwise xor

#SwappwithAdd.py
a=int(input("Enter Value of a:"))
b=int(input("Enter Value of b:"))
print("="*50)
print("Original value of a={}".format(a))
print("Original value of b={}".format(b))
print("="*50)
#Swapping Logic with Addition
a=a+b
b=a-b
a=a-b
print("Swapped value of a={}".format(a))
print("Swapped value of b={}".format(b))
print("="*50)

#SwapWithThirdvar.py
a=int(input("Enter Value of a:"))
b=int(input("Enter Value of b:"))
print("="*50)
print("Original value of a={}".format(a))
print("Original value of b={}".format(b))
print("="*50)
#Swapping Logic with Third var
t=a
a=b
b=t
print("Swapped value of a={}".format(a))
print("Swapped value of b={}".format(b))
print("="*50)
=============================================
6. Membership Operators
=============================================
=>The purpose of membership operators is that "To Check whether the Specific Value present in
Iterable object Or Not".
=>An Iterable object is one, which contains More Number of Values
(Examples: Sequence Type,List Type,Set type,Duct type)
=>In Python Programming, we have 2 types of Membership Operators. They are
1. in
2. not in
--------------------------------------------------------------------------------------------------------------------------
---------------
1. in
--------------------------------------------------------------------------------------------------------------------------
---------------
Syntax: Value in IterableObject
-----------
=>"in" operator returns True Provided Value present in Iterable object
=>"in" operator returns False Provided Value not present in Iterable object
--------------------------------------------------------------------------------------------------------------------------
---------------
2. not in
--------------------------------------------------------------------------------------------------------------------------
---------------
Syntax: Value not in IterableObject
-----------
=>"not in" operator returns True Provided Value not present in Iterable object
=>"not in" operator returns False Provided Value present in Iterable object
--------------------------------------------------------------------------------------------------------------------------
---------------
Examples:
--------------------------------------------------------------------------------------------------------------------------
---------------
>>> s="PYTHON"
>>> print(s,type(s))------------PYTHON <class 'str'>
>>> "P" in s---------------------True
>>> "O" in s--------------------True
>>> "O" not in s--------------False
>>> "K" in s-------------------False
>>> "K" not in s--------------True
>>> "p" in s--------------------False
>>> "p" not in s--------------True
---------------------------------------------------------------
>>> s="PYTHON"
>>> print(s,type(s))--------------PYTHON <class 'str'>
>>> "PYT" in s-------------------True
>>> "PYTH" not in s-----------False
>>> "PYTH" in s-----------------True
>>> "THON" not in s------------False
>>> "THON" in s----------------True
>>> s="PYTHON"
>>> print(s,type(s))-------------PYTHON <class 'str'>
>>> "PON" in s------------------False
>>> "HON" in s------------------True
>>> "PON" not in s-------------True
>>> "NOH" in s-----------------False
>>> "NOH" not in s------------True
>>> "PTO" in s-----------------False
>>> s="PYTHON"
>>> print(s,type(s))---------------PYTHON <class 'str'>
>>> "NOH" in s[::-1]---------------True
>>> "PTO" not in s[::2]----------False
>>> "PTO" in s[::2]---------------True
>>> "OTP" not in s[1::-2]----------True
>>> s[1::-2]-----------------------------'Y'
--------------------------------------------------------------
>>> lst=[10,"Rossum",True,2+3j]
>>> print(lst,type(lst))----------------[10, 'Rossum', True, (2+3j)] <class 'list'>
>>> 10 in lst-----------------------------True
>>> True not in lst----------------------False
>>> 2+3j in lst---------------------------True
>>> "Ros" in lst------------------------False
>>> "Ros" in lst[1]-------------------True
>>> "mus" not in lst[1][::-1]---------False
>>> lst[::-1] not in lst[::]---------------True
>>> lst[1][::-1] in lst[::]----------------False
>>> lst[1][::-1] in lst[-3][::-1][::-1]-----False
-------------------------------------------------------------------
>>> lst=[10,"Rossum",True,2+3j]
>>> print(lst,type(lst))-------------------------[10, 'Rossum', True, (2+3j)] <class 'list'>
>>> 2+3j in lst----------------------------------True
>>> 2+3j not in lst----------------------------False
-------------------------
>>> 2 in lst[-1]---------------------TypeError: argument of type 'complex' is not iterable
>>> 3 in lst[-1].imag------------TypeError: argument of type 'float' is not iterable
------------------------------------------------------------------------
>>> d1={10:"Python",20:"Java",30:"C++"}
>>> print(d1,type(d1))---------------{10: 'Python', 20: 'Java', 30: 'C++'} <class 'dict'>
>>> 10 in d1----------------True
>>> 30 not in d1-----------False
>>> 40 in d1----------------False
>>> "Python" in d1---------False
>>> "Python" in d1[10]----True
>>> "C++" in d1.get(30)---------True
>>> "C++"[::-1] not in d1.get(30)[::-1]----False
>>> "C++"[::-1] in d1.get(30)[::-1]---------True
==============================x=========================================
======.

day – 32

=====================================================
Identity Operators--Python Command / IDLE Shell Basis
=====================================================
=>The purpose of Identity Operators is that "To Compare Memory Address of Two Objects".
=>In Python Programming, we have Two Types of Identity Operators. They are
1. is
2. is not
--------------------------------------------------------------------------------------------------------------------------
--------------
1. is
--------------------------------------------------------------------------------------------------------------------------
--------------
=>Syntax: Object1 is Object2
=>"is" Operator returns True Provided Both the objects Contains SAME Address.
=>"is" Operator returns False Provided Both the objects Contains Different Address.
--------------------------------------------------------------------------------------------------------------------------
--------------
2. is not
--------------------------------------------------------------------------------------------------------------------------
--------------
Syntax: Object1 is not Object2
=>"is not " Operator returns True Provided Both the objects Contains Different Address.
=>"is not " Operator returns False Provided Both the objects Contains Same Address.
--------------------------------------------------------------------------------------------------------------------------
--------------
Examples:
--------------------------------------------------------------------------------------------------------------------------
--------------
>>> a=None
>>> b=None
>>> print(a,type(a),id(a))---------None <class 'NoneType'> 140704386324472
>>> print(b,type(b),id(b))--------None <class 'NoneType'> 140704386324472
>>> a is b---------True
>>> a is not b---------False
--------------------------------------------------------------------------------------------------------------------------
----------
>>> d1={10:"Apple",20:"Mango",30:"Kiwi"}
>>> d2={10:"Apple",20:"Mango",30:"Kiwi"}
>>> print(d1,type(d1),id(d1))-----{10: 'Apple', 20: 'Mango', 30: 'Kiwi'} <class 'dict'> 2864804287360
>>> print(d2,type(d2),id(d2))-----{10: 'Apple', 20: 'Mango', 30: 'Kiwi'} <class 'dict'> 2864804287488
>>> d1 is d2--------False
>>> d1 is not d2--True
--------------------------------------------------------------------------------------------------------------------------
----------
>>> s1={10,20,30,40}
>>> s2={10,20,30,40}
>>> print(s1,type(s1),id(s1))---------{40, 10, 20, 30} <class 'set'> 2864805025088
>>> print(s2,type(s2),id(s2))---------{40, 10, 20, 30} <class 'set'> 2864805024640
>>> s1 is s2-------------------False
>>> s1 is not s2-------------True
>>> fs1=frozenset(s1)
>>> fs2=frozenset(s1)
>>> print(fs1,type(fs1),id(fs1))--------frozenset({40, 10, 20, 30}) <class 'frozenset'> 2864805026208
>>> print(fs2,type(fs2),id(fs2))-------frozenset({40, 10, 20, 30}) <class 'frozenset'> 2864805026656
>>> fs1 is fs2-------------------------False
>>> fs1 is not fs2-------------------True
--------------------------------------------------------------------------------------------------------------------------
----------
>>> l1=[10,"Rossum",22.22]
>>> l2=[10,"Rossum",22.22]
>>> print(l1,type(l1),id(l1))----------[10, 'Rossum', 22.22] <class 'list'> 2864804317696
>>> print(l2,type(l2),id(l2))---------[10, 'Rossum', 22.22] <class 'list'> 2864804318400
>>> l1 is l2------------------False
>>> l1 is not l2-----------True
>>> t1=(10,20,30,40)
>>> t2=(10,20,30,40)
>>> print(t1,type(t1),id(t1))------------(10, 20, 30, 40) <class 'tuple'> 2864804748304
>>> print(t2,type(t2),id(t2))------------(10, 20, 30, 40) <class 'tuple'> 2864804752304
>>> t1 is t2--------------------------------False
>>> t1 is not t2--------------------------True
--------------------------------------------------------------------------------------------------------------------------
----------
>>> r1=range(10,20)
>>> r2=range(10,20)
>>> print(r1,type(r1),id(r1))--------range(10, 20) <class 'range'> 2864804444656
>>> print(r2,type(r2),id(r2))--------range(10, 20) <class 'range'> 2864804444224
>>> r1 is r2----------------------False
>>> r1 is not r2---------------True
>>> ba1=bytearray([10,20,30,40])
>>> ba2=bytearray([10,20,30,40])
>>> print(ba1,type(ba1),id(ba1))---bytearray(b'\n\x14\x1e(') <class 'bytearray'> 2864808582512
>>> print(ba2,type(ba2),id(ba2))---bytearray(b'\n\x14\x1e(') <class 'bytearray'> 2864808582896
>>> ba1 is ba2--------False
>>> ba1 is not ba2---True
>>> ba1=bytes([10,20,30,40])
>>> ba2=bytes([10,20,30,40])
>>> print(ba1,type(ba1),id(ba1))----b'\n\x14\x1e(' <class 'bytes'> 2864804444320
>>> print(ba2,type(ba2),id(ba2))---b'\n\x14\x1e(' <class 'bytes'> 2864804442592
>>> ba1 is ba2-----False
>>> ba1 is not ba2----True
---------------------
>>> s1="PYTHON"
>>> s2="PYTHON"
>>> print(s1,type(s1),id(s1))---PYTHON <class 'str'> 2864808583024
>>> print(s2,type(s2),id(s2))---PYTHON <class 'str'> 2864808583024
>>> s1 is s2-----True
>>> s1 is not s2---False
----------------------------
>>> s1="JAVA"
>>> s2="JAVa"
>>> print(s1,type(s1),id(s1))--------JAVA <class 'str'> 2864808582000
>>> print(s2,type(s2),id(s2))-------JAVa <class 'str'> 2864808582512
>>> s1 is s2------------False
>>> s1 is not s2------True
--------------------------------------------------------------------------------------------------------------------------
------------
>>> a=2+3j
>>> b=2+3j
>>> print(a,type(a),id(a))--------(2+3j) <class 'complex'> 2864803995536
>>> print(b,type(b),id(b))-------(2+3j) <class 'complex'> 2864803999280
>>> a is b-----------False
>>> a is not b-----True
>>> a=True
>>> b=True
>>> print(a,type(a),id(a))---------True <class 'bool'> 140704386272104
>>> print(b,type(b),id(b))--------True <class 'bool'> 140704386272104
>>> a is b--------True
>>> a is not b---False
>>> c=False
>>> print(c,type(c),id(c))-----False <class 'bool'> 140704386272136
>>> a is c-------False
>>> a is not c-------True
>>> a=1.2
>>> b=1.2
>>> print(a,type(a),id(a))---------1.2 <class 'float'> 2864803995984
>>> print(b,type(b),id(b))--------1.2 <class 'float'> 2864803999280
>>> a is b--------------------False
>>> a is not b--------------True
----------------------------
>>> a=300
>>> b=300
>>> print(a,type(a),id(a))-----300 <class 'int'> 2864803995600
>>> print(b,type(b),id(b))----300 <class 'int'> 2864803999184
>>> a is b-----------False
>>> a is not b------True
>>> a=10
>>> b=10
>>> print(a,type(a),id(a))--------10 <class 'int'> 2864802955792
>>> print(b,type(b),id(b))-------10 <class 'int'> 2864802955792
>>> a is b---------True
>>> a is not b------False
>>> a=256
>>> b=256
>>> print(a,type(a),id(a))----256 <class 'int'> 2864802963664
>>> print(b,type(b),id(b))----256 <class 'int'> 2864802963664
>>> a is b--------True
>>> a is not b---False
>>> a=257
>>> b=257
>>> print(a,type(a),id(a))----257 <class 'int'> 2864803995600
>>> print(b,type(b),id(b))---257 <class 'int'> 2864803999248
>>> a is b-------False
>>> a is not b----True
>>> a=0
>>> b=0
>>> print(a,type(a),id(a))------0 <class 'int'> 2864802955472
>>> print(b,type(b),id(b))-----0 <class 'int'> 2864802955472
>>> a is b------------True
>>> a is not b-------False
---------------------------------------
>>> a=-1
>>> b=-1
>>> print(a,type(a),id(a))---------- -1 <class 'int'> 2864802955440
>>> print(b,type(b),id(b))--------- -1 <class 'int'> 2864802955440
>>> a is b--------True
>>> a is not b---False
>>> a=-5
>>> b=-5
>>> print(a,type(a),id(a))------------ -5 <class 'int'> 2864802955312
>>> print(b,type(b),id(b))------------ -5 <class 'int'> 2864802955312
>>> a is b--------------True
>>> a is not b---------False
>>> a=-6
>>> b=-6
>>> print(a,type(a),id(a))-------- -6 <class 'int'> 2864803999248
>>> print(b,type(b),id(b))------ -6 <class 'int'> 2864803995600
>>> a is b-----------------False
>>> a is not b----------True
---------------------------------------------------------------------------------------------
MOST IMP
---------------------------------------------------------------------------------------------
>>> a,b=400,400 # Multi Line Assigment
>>> print(a,type(a),id(a))-----400 <class 'int'> 2864803995728
>>> print(b,type(b),id(b))----400 <class 'int'> 2864803995728
>>> a is b-----True
>>> a is not b---False
>>> a,b=1.2,1.2 # # Multi Line Assigment
>>> print(a,type(a),id(a))---------1.2 <class 'float'> 2864803999120
>>> print(b,type(b),id(b))---------1.2 <class 'float'> 2864803999120
>>> a is b---------True
>>> a is not b----False
>>> a,b=2+3j,2+3j
>>> print(a,type(a),id(a))-------(2+3j) <class 'complex'> 2864803999344
>>> print(b,type(b),id(b))------(2+3j) <class 'complex'> 2864803999344
>>> a is b--------------------True
>>> a is not b--------------False
---------------------------------------------------------------------------------------------
MOST MOST IMP
---------------------------------------------------------------------------------------------
>>> l1,l2=[10,20,30],[10,20,30]
>>> print(l1,type(l1),id(l1))---------[10, 20, 30] <class 'list'> 2864804318400
>>> print(l2,type(l2),id(l2))--------[10, 20, 30] <class 'list'> 2864808577600
>>> l1 is l2---------------False
>>> l1 is not l2--------True
>>> d1,d2={10:"Python",20:"Java"},{10:"Python",20:"Java"}
>>> print(d1,type(d1),id(d1))---{10: 'Python', 20: 'Java'} <class 'dict'> 2864804318976
>>> print(d2,type(d2),id(d2))---{10: 'Python', 20: 'Java'} <class 'dict'> 2864804287872
>>> d1 is d2----------False
>>> d1 is not d2-----True
--------------------------------------------------------------------------------------------------------------------------
-------------
NOTE:
----------
=>What are all the objects Participates in DEEP Copy then Those Objects Contains Same Address
and "is" operator Returns True and "is not" operator Returns False.
=>What are all the objects Participates in SHALLOW DEEP Copy then Those Objects Contains
Different Address and "is" operator Returns False and "is not" operator Returns True.
--------------------------------------------------------------------------------------------------------------------------
-------------.

In Python, the ternary operator is a way to write conditional expressions in a single line.
It’s often used to assign a value based on a condition, similar to an if-else statement but
more concise.

Syntax:

value_if_true if condition else value_if_false

Example:

age = 20
status = "Adult" if age &gt;= 18 else "Minor"
print(status) # Output: Adult

Use Cases:

• Assigning values based on conditions


• Returning values from functions
• Inline logic in list comprehensions or lambda functions

Would you like to see how it compares to a regular if-else block or how to use it in more
complex scenarios like nested conditions or with functions?

==================================================
Ternary Operator in Python
==================================================
=>Python Programming contains a Ternary operator.
=>The Name of Ternary Operator in Pythin is "if ... else ".
----------------
=>Syntax varname = Expr1 if Test Cond else Expr2
----------------
Explanation
-------------------
=>Here if and else are the Keywords
=>Here Test Cond can be Either True Or False
=>Here Expr1 and Expr2 are Executable Statements
=>If the Result of Test Cond is True then PVM executes Expr1 and whose Placed in varname
=>If the Result of Test Cond is False then PVM executes Expr2 and whose Placed in varname
=>At any Point of Time PVM Executes Either Expr1 Or Expr2 and whose Result places in varname.
----------------------------------------------------------------------------------

#program for Finding Biggest of Two Numbers


#BigEx1.py
a=int(input("Enter First value:"))
b=int(input("Enter Second value:"))
#Logic for Finding biggest
bv= a if a>b else b
print("big({},{})={}".format(a,b,bv))

#program for Finding Biggest of Two Numbers and Check for equality
#BigEx2.py
a=int(input("Enter First value:"))
b=int(input("Enter Second value:"))
#Logic for Finding biggest and for equality
bv=a if a>b else b if b>a else "VALUES ARE EQUAL"
print("Big({},{})={}".format(a,b,bv))

day – 33

write a python program which will be excepted three integer values and find biggest among them
check for the equality by using ternary operator

#Program for accepting Three valuea and find Biggest among them and check for equality
#BigThreeEx1.py
a=int(input("Enter Value of a:")) # 100
b=int(input("Enter Value of b:")) # 500
c=int(input("Enter Value of c:")) # 4000
#Logic for big among three
bv=a if a>=b and a>c else b if b>a and b>=c else c if c>=a and c>b else "All values are equal"
print("big({},{},{})={}".format(a,b,c,bv))

write a python program which will except three intger value and find the smallest among them by
using ternary operator

#Program for accepting Three valuea and find Biggest among them and check for equality
#BigThreeEx3.py
a=int(input("Enter Value of a:")) # 100
b=int(input("Enter Value of b:")) # 500
c=int(input("Enter Value of c:")) # 4000
#Logic for big among three
bv=a if b<=a>c else b if a<b>=c else c if a<=c>b else "All values are equal"
print("big({},{},{})={}".format(a,b,c,bv))

write a pyhton program which will except a word and decide whether it is palindrome or not

#PanlindromeEx.py
word=input("Enter Word:")
res="PALINDROME" if word==word[::-1] else "NOT PALINDROME"
print("{} is {}".format(word,res))

write a python program which will except a numerical integr value and decide whether it is positive
negative are zero – 3 condition

#PosNegZero.py
n=int(input("Enter any Number:")) # +ve -ve 0
res="+VE" if n>0 else "-VE" if n<0 else "ZERO"
print("{} is {}".format(n,res))

wite a pythn program whic h will ecept a numerical integer value and decide whether it even or odd

====================================
String Handling Part-2
====================================
=>On String Data, we can perform Indexing, Slicing Operations and with these operations, we can
also perform different type of operations by using pre-defined functions present in str object.
--------------------------------------------------------------------------------------------------------------------------
------
Pre-defined Functions in str object
--------------------------------------------------------------------------------------------------------------------------
------
1) capitalize()
--------------------------------------------------------------------------------------------------------------------------
------
=>This Function is used for capitalizing the first letter First word of a given Sentence only.
=>Syntax: strobj.capitalize()
(OR)
strobj=strobj.capitalize()
-----------------
Examples:
-----------------
>>> s="python"
>>> print(s,type(s))-------------------python <class 'str'>
>>> s.capitalize()--------------------'Python'
>>> s="python is an oop lang"
>>> print(s,type(s))-------------------------python is an oop lang <class 'str'>
>>> s.capitalize()-----------------------------'Python is an oop lang'
-------------------------------------
>>> s="python"
>>> print(s,type(s))--------------------python <class 'str'>
>>> s.capitalize()--------------------'Python'
>>> print(s,type(s))----------------python <class 'str'>
>>> s=s.capitalize()
>>> print(s,type(s))-----------------Python <class 'str'>
--------------------------------------------------------------------------------------------------------------------------
------
2) title():
--------------------------------------------------------------------------------------------------------------------------
------
=>This is used for obtaining Title Case of a Given Sentence (OR) Making all words First
Letters are capital.
Syntax: s.title()
(OR)
s=s.title()

------------------
Examples:
------------------
>>> s="python"
>>> print(s,type(s))-------------------python <class 'str'>
>>> s.capitalize()---------------------'Python'
>>> s.title()-----------------------------'Python'
----------------------------------------------------------
>>> s="python is an oop lang"
>>> print(s,type(s))------------------python is an oop lang <class 'str'>
>>> s.capitalize()--------------------'Python is an oop lang'
>>> s.title()----------------------------'Python Is An Oop Lang'
>>> print(s)----------------------------python is an oop lang
>>> s=s.title()
>>> print(s)--------------------------Python Is An Oop Lang
--------------------------------------------------------------------------------------------------------------------------
------
3) index()
--------------------------------------------------------------------------------------------------------------------------
------
=>This Function obtains Index of the specified Value
=>If the specified value does not exist then we get ValueError
=>Syntax: strobj.index(Value)
=>Syntax: indexvalue=strobj.index(value)

Examples:
-----------------
>>> s="python"
>>> s.index("p")------------------0
>>> s.index("y")-------------------1
>>> s.index("o")-----------------4
>>> s.index("n")----------------5
>>> s.index("K")----------------ValueError: substring not found

=>enumerate() is one the general function, which is used for finding Index and Value of anu
Iterable object.
NOTE:
------------
>>> for i,v in enumerate(s):
... print("Index:{} and Value:{}".format(i,v))
---------------
OUTPUT
---------------
Index:0 and Value:p
Index:1 and Value:y
Index:2 and Value:t
Index:3 and Value:h
Index:4 and Value:o
Index:5 and Value:n
-----------------------------
>>> lst=[10,"Rossum",23.45,True]
>>> for i,v in enumerate(lst):
... print("Index:{} and Value:{}".format(i,v))
---------------
OUTPUT
---------------
Index:0 and Value:10
Index:1 and Value:Rossum
Index:2 and Value:23.45
Index:3 and Value:True
--------------------------------------------------------------------------------------------------------------------------
------
4) upper()
--------------------------------------------------------------------------------------------------------------------------
------
=>It is used for converting any type of Str Data into Upper Case.
=>Syntax:- strobj.upper()
OR
strobj=strobj.upper()
-----------------
Examples:
=---------------
>>> s="python"
>>> print(s)------------------------------python
>>> s.upper()-----------------------'PYTHON'
>>> s="python is an oop lang"
>>> print(s)---------------------------------python is an oop lang
>>> s.upper()--------------------------------'PYTHON IS AN OOP LANG'
>>> s="Python IS an OOP lang"
>>> print(s)-------------------------------Python IS an OOP lang
>>> s.upper()--------------------------'PYTHON IS AN OOP LANG'
>>> s="AbCdEf"
>>> print(s)------------------------AbCdEf
>>> s.upper()----------------------'ABCDEF'
>>> s="PYTHON"
>>> print(s)--------------------PYTHON
>>> s.upper()-----------------'PYTHON'
>>> s="123"
>>> print(s)------------------123
>>> s.upper()----------------'123'
--------------------------------------------------------------------------------------------------------------------------
------
5) lower()
--------------------------------------------------------------------------------------------------------------------------
------
=>It is used for converting any type of Str Data into lower Case.
=>Syntax:- strobj.lower()
OR
strobj=strobj.lower()
Examples:
-----------------
>>> s="Data Science"
>>> print(s)--------------Data Science
>>> s.lower()------------'data science'
>>> s="python"
>>> print(s)-------------python
>>> s.lower()-----------'python'
>>> s="PYTHON"
>>> print(s)-------------PYTHON
>>> s.lower()------------'python'
>>> s="PYThon"
>>> print(s)----------PYThon
>>> s.lower()---------'python'
--------------------------------------------------------------------------------------------------------------------------
------
6) isupper()
--------------------------------------------------------------------------------------------------------------------------
------
=>This Function returns True provided the given str object data is purely Upper Case otherwise it
returns False.
Syntax: strobj.isupper()

Examples:
-----------------
>>> s="PYTHON"
>>> s.isupper()-----------True
>>> s="python"
>>> s.isupper()----------False
>>> s="Python"
>>> s.isupper()----------False
>>> s="PYThon"
>>> s.isupper()----------False
>>> s="123"
>>> s.isupper()------------False
>>> s="%$#^&@"
>>> s.isupper()-----------False

--------------------------------------------------------------------------------------------------------------------------
------
7)islower()
--------------------------------------------------------------------------------------------------------------------------
------
=>This Function returns True provided the given str object data is purely lower Case otherwise it
returns False.
Syntax: strobj.islower()
-----------------
Examples:
-----------------
>>> s="pythopn"
>>> s.islower()------------True
>>> s="pythOn"
>>> s.islower()------------False
>>> s="PYTHON"
>>> s.islower()-----------False
>>> s="123"
>>> s.islower()----------False
--------------------------------------------------------------------------------------------------------------------------
------
8) isalpha()
--------------------------------------------------------------------------------------------------------------------------
------
=>This Function returns True provided str object contains Purely Alphabets otherwise returns False.

Syntax: strobj.isalpha()
-------------------
Examples:
-------------------
>>> s="Ambition"
>>> s.isalpha()--------------------True
>>> s="Ambition123"
>>> s.isalpha()-------------------False
>>> s="1234"
>>> s.isalpha()------------------False
>>> s=" "
>>> s.isalpha()------------------False
>>> s="#$%^@"
>>> s.isalpha()-----------------False
>>> s="AaBbZz"
>>> s.isalpha()----------------True
--------------------------------------------------------------------------------------------------------------------------
------
9) isdigit()
--------------------------------------------------------------------------------------------------------------------------
------
=>This Function returns True provided given str object contains purely digits otherwise returns False
Examples:
--------------------
>>> s="python"
>>> s.isdigit()------------------False
>>> s="python123"
>>> s.isdigit()----------------False
>>> s="123"
>>> s.isdigit()-----------------True
>>> s="123 456"
>>> s.isdigit()---------------False
>>> s="1_2_3"
>>> s.isdigit()---------------False
>>> s="123KV"
>>> s.isdigit()-------------False
--------------------------------------------------------------------------------------------------------------------------
------
10) isalnum()
--------------------------------------------------------------------------------------------------------------------------
------
=>This Function returns True provided str object contains either Alpabets OR Numerics or Alpha-
Numerics only otherwise It returns False.
=>Syntax: strobj. isalphanum()
---------------------------
=>Examples:
---------------------------
>>> s="python310"
>>> s.isalnum()-----------------True
>>> s="python"
>>> s.isalnum()-----------------True
>>> s="310"
>>> s.isalnum()-----------------True
>>> s="$python310"
>>> s.isalnum()-----------------False
>>> s="python 310"
>>> s.isalnum()----------------False
>>> s="$python3.10"
>>> s.isalnum()----------------False
>>> s="python3.10"
>>> s.isalnum()-------------False
--------------------------------------------------------------------------------------------------------------------------
-----
11) isspace()
--------------------------------------------------------------------------------------------------------------------------
-----
=>This Function returns True provided str obj contains purely space otherwise it returns False.
=>Syntax: strobj.isspace()
------------------------
Examples:
----------------------
>>> s=" "
>>> s.isspace()-----------True
>>> s=""
>>> s.isspace()--------------False
>>> s="python Prog"
>>> s.isspace()-------------False
>>> s="Prasana Laxmi"
>>> s.isspace()--------------False
>>> s.isalpha()-----------False
>>> s.isalpha() or s.isspace()-----------False
--------------------------------------------------------------------------------------------------------------------------
-----
12) split()
--------------------------------------------------------------------------------------------------------------------------
-----
=>This Function is used for splitting the given str object data into different words base specified
delimter ( - _ # % ^ ^ , ; ....etc)
=>The dafeult deleimter is space
=>The Function returns Splitting data in the form of list object
=>Syntax: strobj.split("Delimter")
(OR)
strobj.split()
(OR)
listobj= strobj.split("Delimter")
(OR)
listobj=strobj.split()
----------------
Examples:
----------------
>>> s="Python is an oop lang"
>>> print(s)----------------Python is an oop lang
>>> s.split()----------------['Python', 'is', 'an', 'oop', 'lang']
>>> len(s.split())-----------5
>>> x=s.split()
>>> print(x,type(x))---------['Python', 'is', 'an', 'oop', 'lang'] <class 'list'>
>>> len(x)---------------5
>>> s="12-09-2022"
>>> print(s)-------------12-09-2022
>>> s.split("-")----------['12', '09', '2022']
>>> s="12-09-2022"
>>> dob=s.split("-")
>>> print(dob,type(dob))------------['12', '09', '2022'] <class 'list'>
>>> print("Day",dob[0])----------Day 12
>>> print("Month ",dob[1])---------Month 09
>>> print("Year ",dob[2])----------Year 2022
---------------------------------------------------------
>>> s="Apple#Banana#kiwi/Guava"
>>> words=s.split("#")
>>> print(words)-----------['Apple', 'Banana', 'kiwi/Guava']
>>> words=s.split("/")
>>> print(words)------------------['Apple#Banana#kiwi', 'Guava']
-------------------------------------------------------------------------------
13) join():
-------------------------------------------------------------------------------
=>This Function is used for combining or joining list of values from any Iterable object
=>Syntax: strobj.join(Iterableobject)
Examples:
------------------------------
>>> lst=["HYD","BANG","AP","DELHI"]
>>> print(lst,type(lst))------------------['HYD', 'BANG', 'AP', 'DELHI'] <class 'list'>
>>> s=""
>>> s.join(lst)---------------'HYDBANGAPDELHI'
>>> s=" "
>>> s.join(lst)------------------'HYD BANG AP DELHI'
-------------------------------------------------------------------
>>> t=("Rossum","is", "Father" "of" ,"Python")
>>> print(t,type(t))
('Rossum', 'is', 'Fatherof', 'Python') <class 'tuple'>
>>> k=" "
>>> k.join(t)
'Rossum is Fatherof Python'
>>> t=("Rossum","is", "Father", "of" ,"Python")
>>> k=" "
>>> k.join(t)
'Rossum is Father of Python'
>>>

---------------------------------------------------------------------------------------------------------------------

--------------------------------------------------------------------------------------------------------------------------
-----

day – 34
-----------.

Flow Control Statements in Python


(OR)
Control Structures in Python--Most Imp--10 days
=====================================================
Index
------------
=>Purpose of Flow Control Statements in Python
=>Types of Flow Control Statements in Python
1) Conditional OR Selection OR Branching Statements
a) Simple if Statements
b) if..else statement
c) if..elif..else statement
d) match ...case (Python 3.10 Version)
=>Programming Examples
2) Looping OR Iterative OR Repetative Statements
a) while loop OR while..else loop
b) for loop OR for ..else Loop
=>Programming Examples
3) Transfer Flow Control Statements
a) break
b) continue
c) pass
d) return
=>Programming Examples
=>Combined Programming Examples on Conditional, Looping and Transfer
Flow Control Statements
--------------------------------------------------------------------------------------------------------------------------
-------------
=>Nested OR Inner Loops
a) while loop in while loop
b) for loop in for loop
c) while loop in for loop
d) for loop in while loop
=>Programming Examples
==================================x====================================

====================================================
Flow Control Statements in Python
(OR)
Control Structures in Python
=====================================================
=>The Purpose of Flow Control Statements in Python is that " To Perform Certain Operation( X
Operation or Y-Operation) OnlyOnce (depends on Cond-True Or False) OR To Perform Certain
Operation Repeatedly for Finite Number of Times Until Condition Becomes False."
=>In Python Programming, We have 3 types of Flow Control Statements. They are

1. Conditional OR Selection OR Branching Statements.


2. Looping OR Iterative OR Repetative Statements.
3. Transfer Flow Control Statements.
========================================================================
=====

====================================================
1. Conditional OR Selection OR Branching Statements
====================================================
=>The Purpose of Conditional OR Selection OR Branching Statements is that "To Perform either
X-Operation in the case of True of Perform Y-Operation in the case of False Only Once."
=>In Python Programming, we have 4 types of Conditional Statements. They are

1. Simple if statement
2. if..else statement
3. if..elif..else statement
4. match ... case statement ( Python 3.10 Version onwards)
--------------------------------------------------------------------------------------------------------------------------
---------------------.

#MovieeEx1.py
tkt=input("Do u have Ticket(yes/no):")
if (tkt=="yes"):
print("enter into theater")
print("watch the moviee")
print("eat pop corn!!")
print("Goto Home")

---------------------------------------------------------------------------.

write a python program which will decide wheter the given number is even or odd by using simple if
statement.

-------------------------------------------------------------------------------.
#Program for deciding wether the number is even or odd
#EvenOddIfEx1.py
n=int(input("Enter a Number:")) # 100
if(n%2==0):
print('{} is EVEN'.format(n))
if(n%2!=0):
print("{} is ODD".format(n))
print("Program execution Completed")

---------------------------------------------------------------------------.
write a python program which will except any numerical intger value
and decide wheteher it is positive or negave by using if .

#program for deciding whether the given number is +ve or -ve or Zero
#PosNegZeroIfEx.py
n=float(input("Enter a Number:"))
if(n>0):
print("{} is +VE".format(n))
if(n<0):
print("{} is -VE".format(n))
if(n==0):
print("{} is ZERO ".format(n))
print("Program execution Completed")

write a python program which except a word and decide whether the word is palidrom or not by
using if statements.

Text = input(“enter your word or number:”)


if text[0]==text[2]:
print(“palildrome”)
else:
print(not)

Day – 35

syntax =
if (tests cond):
Indentation Block of Statemwnts-I
else:
indentation block of statements – II

other statements in program

writea a python program which will except any digit and decide wheter it positive and negative by
using if else statement .

#program for accepting whether a given number of +ve or negative or Zero


#IfElseEx1.py
n=int(input("Enter a Number:")) # +ve or -ve or zero
if(n>0):
print("{} is +VE".format(n))
else:
if(n<0):
print("{} is -VE".format(n))
else:
print("{} is Zero".format(n))
print("Program execution Completed")

writea python program which will except any numerical integer and decide even or odd by using if
else

write a python program which will except any word and decide whether it is palllidrom or not by
using if else stattement

write a pyhton program which will except any word and decide whether is vowel word or not
#Programing for accepting a word amd decide wehether It is Vowel word or not.
#IfElseEx2.py
word=input("Enterv a Word:")
if('a'in word.lower() or 'e'in word.lower() or 'i'in word.lower() or 'o' in word.lower() or 'u' in
word.lower()):
print("{} is Vowel Word".format(word))
else:
print("{} is not Vowel Word".format(word))

write a python program which will except any digit and prinnt names

#program for accepting any digit and print its name


#IfElseEx3.py
n=int(input("Enter a Digit:"))#0 1 2 3 4 5 6 7 8 9
if(n==0):
print("{} is Zero".format(n))
else:
if(n==1):
print("{} is One".format(n))
else:
if(n==2):
print("{} is TWO".format(n))
else:
if(n==3):
print("{} is THREE".format(n))
else:
if(n==4):
print("{} is FOUR".format(n))
else:
if(n==5):
print("{} is FIVE".format(n))
else:
if(n==6):
print("{} is SIX".format(n))
else:
if(n==7):
print("{} is SEVEN".format(n))
else:
if(n==8):
print("{} is EIGHT".format(n))
else:
if(n==9):
print("{} is NINE".format(n))
else:
print("{} is a Number".format(n))
print("Program execution Completed")

#program for accepting any digit and print its name


#IfELIFElseEx1.py
n=int(input("Enter a Digit:"))#0 1 2 3 4 5 6 7 8 9
if(n==0):
print("{} is Zero".format(n))
elif(n==1):
print("{} is ONE".format(n))
elif(n==2):
print("{} is TWO".format(n))
elif(n==3):
print("{} is THREE".format(n))
elif(n==4):
print("{} is FOUR".format(n))
elif(n==5):
print("{} is FIVE".format(n))
elif(n==6):
print("{} is SIX".format(n))
elif(n==7):
print("{} is SEVEN".format(n))
elif(n==8):
print("{} is EIGHT".format(n))
elif(n==9):
print("{} is NINE".format(n))
elif( n in [-1,-2,-3,-4,-5,-6,-7,-8,-9]):
print("{} is -Ve Digit".format(n))
elif( n not in [-1,-2,-3,-4,-5,-6,-7,-8,-9] and n not in [0,1,2,3,4,5,6,7,8,9] ):
print("{} is NUMBER".format(n))
print("Program execution Completed")

#DigitEx1.py
d={0:"ZERO",1:"ONE",2:"TWO",3:"THREE",4:"FOUR",5:"FIVE",6:"SIX",7:"SEVEN",8:"EIGHT"
,9:"NINE"}
digit=int(input("Enter a Digit:")) # 0 1 2 3 4 5 6 7 8 9
res=d.get(digit)
if(res!=None):
print("{} is {}".format(digit,res))
else:
print("{} is a Number".format(digit))

#DigitEx2.py
d={0:"ZERO",1:"ONE",2:"TWO",3:"THREE",4:"FOUR",5:"FIVE",6:"SIX",7:"SEVEN",8:"EIGHT"
,9:"NINE"}
digit=int(input("Enter a Digit:")) # 0 1 2 3 4 5 6 7 8 9
res=d.get(digit) if(d.get(digit)!=None) else "Its a Number"
print("{} is {}".format(digit,res))

#DigitEx2.py
d={0:"ZERO",1:"ONE",2:"TWO",3:"THREE",4:"FOUR",5:"FIVE",6:"SIX",7:"SEVEN",8:"EIGHT"
,9:"NINE"}
digit=int(input("Enter a Digit:")) # 0 1 2 3 4 5 6 7 8 9
print("{} is {}".format(digit,d.get(digit) if(d.get(digit)!=None) else "Its a Number"))

#EvenOddEx1.py
n=int(input("Enter a Number:"))
if(n<=0):
print("{} is Invalid Input:".format(n))
else:
if(n%2==0):
print("{} is EVEN".format(n))
else:
print("{} is ODD".format(n))

#EvenOddEx2.py
n=int(input("Enter a Number:"))
if(n<=0):
print("{} is Invalid Input:".format(n))
elif(n%2==0):
print("{} is EVEN".format(n))
elif(n%2!=0):
print("{} is ODD".format(n))

write a python program which will will calculate area of circle by accepting the radius where radius
must be positive .

a=float(input("enter your radius "))


if a >0:
area = 3.14159*a**2
print("{} your fibal radius".format(a))
else:
print("wrong radius")

Write a python program which will caluculte area of circle by acepting radius where radius must be
positive .
import math

while True:
radius = float(input("Enter the radius of the circle (positive): "))
if radius > 0:
area = math.pi * radius ** 2
print(f"Area of circle with radius {radius} is: {area:.2f}")
break
else:
print("❌ Radius must be positive! Try again.")

Write a pyhton program which will calculate area of rectangle by accepting length and breadth where
they can be postitive .

# Program to calculate area of a rectangle

# take input
length = float(input("Enter the length: "))
breadth = float(input("Enter the breadth: "))

# check if both are positive


if length > 0 and breadth > 0:
area = length * breadth
print(f"Area of rectangle = {area:.2f}")
else:
print("❌ Invalid input: Length and breadth must be positive!")

day --- 36

==================================================
d) match case statement.
==================================================
=>Here "match case" is one the new feature in Python 3.10 Version onwards
=>match case statement is recommeded to take in deciding Pre-designed Conditions in
Menu Driven Applications.
-------------------
=>Syntax:
-------------------
match(Choice Expr):
case Choice Label1:
Block of Stements-1
case Choice Label2:
Block of Stements-2
case Choice Label3:
Block of Stements-3
----------------------------
case Choice Label-n:
Block of Stements-n
case _: # Default Case Block
default Block of Statements
-------------------------------------------------------
Other Statements in Program
-------------------------------------------------------
----------------------
Explanation:
----------------------
=>here "match" and "case" are the keywords
=>"Choice Expr" represents either int or str or bool
=>If "Choice Expr" is matching with "case label1" then PVM executes Block of Statements-1 and
later executes Other statements in program.
=>If "Choice Expr" is matching with "case label2" then PVM executes Block of Statements-2 and
later executes Other statements in program.
=>In General "Choice Expr" is trying match with case label-1, case label-2,....case label-n then PVM
executes corresponding block of statements and later executes Other statements in program.
=>If "Choice Expr" is not matching with any of the specified case labels then PVM executes
Default Block of Statements which are written under default case block(case _ ) and later executes
Other statements in program.
=>Writing default case block is optional and If we write then it must be written at last (Otherwise we
get SyntaxError)
=>When we represent multiple case labels under one case then those case labels must be combined
with Bitwise OR Operator ( | ) .
=====================================x==================================
==========

#Program implementaing all Arithmetic Operations by Using match case


#MatchCaseEx1.py
print("="*50)
print("\tARITHMETIC OPERATIONS")
print("="*50)
print("\t1.Addtion")
print("\t2.Substraction")
print("\t3.Multiplication")
print("\t4.Division")
print("\t5.Floor Division")
print("\t6.Modulo Division")
print("\t7.Exponentiation")
print("\t8.Exit")
print("="*50)
ch=int(input("Enter ur Choice:"))
match(ch):
case 1:
print("Enter Two values for Addtion:")
a,b=int(input()),int(input())
print("sum({},{})={}".format(a,b,a+b))
case 2:
print("Enter Two values for Sub:")
a, b = int(input()), int(input())
print("sub({},{})={}".format(a, b, a - b))
case 3:
print("Enter Two values for Mul:")
k,v = int(input()), int(input())
print("Mul({},{})={}".format(k, v, k*v))
case 4:
print("Enter Two values for Div:")
k, v = int(input()), int(input())
print("Div({},{})={}".format(k, v, k/v))
case 5:
print("Enter Two values for Floor Div:")
k, v = int(input()), int(input())
print("Floor Div({},{})={}".format(k, v, k//v))
case 6:
print("Enter Two values for Mod Div:")
k, v = int(input()), int(input())
print("Mod({},{})={}".format(k, v, k % v))
case 7:
k, v = int(input("Enter Base:")), int(input("Enter Power"))
print("pow({},{})={}".format(k, v, k**v))
case 8:
print("Thx for using program")
case _: # default case block
print("Ur Selection of Opeartion is wrong-try again")
print("Program exeution Completed")

write a python program which will implement following usecase

airthmatic ''

#MatchCaseEx2.py
wkn=input("Enter Week Name:")
match(wkn.upper()):
case "MONDAY":
print("{} is Working Day".format(wkn))
case "TUESDAY":
print("{} is Working Day".format(wkn))
case "WEDNESDAY":
print("{} is Working Day".format(wkn))
case "THURSDAY":
print("{} is Working Day".format(wkn))
case "FRIDAY":
print("{} is Working Day".format(wkn))
case "SATURDAY":
print("{} is WEEK END".format(wkn))
case "SUNDAY":
print("{} is HOLI Day".format(wkn))
case _:
print("{} is not a week day".format(wkn))

write a python program which will implement the following

rectangle
square
circle
triangle
exit

#MatchCaseEx3.py
wkn=input("Enter Week Name:")
match(wkn.upper()):
case "MONDAY" | 'TUESDAY'|'WEDNESDAY'|"THURSDAY"|"FRIDAY":
print("{} is Working Day".format(wkn))
case "SATURDAY":
print("{} is WEEK END".format(wkn))
case "SUNDAY":
print("{} is HOLI Day".format(wkn))
case _:
print("{} is not a week day".format(wkn))

#MatchCaseEx4.py
wkn=input("Enter Week Name:")
if wkn.upper() in
["MON",'TUE','WED',"THU","FRI","SAT","SUN","MONDAY","TUESDAY","WEDNESDAY","T
HURSDAY","FRIDAY","SATURDAY","SUNDAY"]:
match(wkn[0:3].upper()):
case "MON" | 'TUE'|'WED'|"THU"|"FRI":
print("{} is Working Day".format(wkn))
case "SAT":
print("{} is WEEK END".format(wkn))
case "SUN":
print("{} is HOLI Day".format(wkn))
else:
print("{} is not a week day".format(wkn))
day --- 37

===================================================
2. Looping OR Iterative OR Repetative Statements
====================================================
=>The purpose of Looping OR Iterative OR Repetative Statements "To Perform Certain Operation
Repeatedly for Finite Number of Times Until Condition Becomes False."
=>In Python Programming, we have 2 types of Looping Statements. They are

1. while Loop OR while..else Loop


2. for Loop OR for..else Loop

=>At the time of dealing with Looping Statementsm, Programmer must ensure 3 Points. They are
1. Initlization Part (From Where to Start)
2. Condtional Part ( Where to Stop)
3. Updation Part ( Increment or Decrement)
4.

while loop or while else loop

syntax:-

while (test cind)


statement -1
statement – 2
--------------.
statement -n
--------------------.
other staement in prog
or

while ( test cond)

statemt 1

statement 2

statement n

else :

Else block of statements

write a python program which will genearate 1 to n numbers whwrw n id + postive integers value
#Program for generating 1 to 1 n numbers where n is +ve
#NumGenEx1.py
n=int(input("Enter How Many Numbers u want to generate:"))
if(n<=0):
print("{} is invalid input".format(n))
else:
i=1 # Initlization
while(i<=n): # test Cond
print("\t{}".format(i))
i=i+1 # Updation
print("Program execution completed")

#Program for generating n to 1 numbers where n is +ve


#NumGenEx2.py
n=int(input("Enter How Numbers u want to generate:"))
if(n<=0):
print("{} is Invalid input".format(n))
else:
i=n # Initlization Part
while(i>0):
print("\t{}".format(i))
i=i-1
else:
print("I am from else part of while loop")
print("Program Execution Completed")

write a python program genrate all even number with in n

write a python program odd number with in n where n is positive intger value

write a python program which will except a numerical positive integer value and genrate a
multiplication table

#program for generating Mul Table for a given +ve number


#MulTableEx1.py
n=int(input("Enter a Number for generating Mul Table:"))
if(n<=0):
print("{} is Invalid Input".format(n))
else:
print('-'*50)
print("Mul Table for:{}".format(n))
print('-' * 50)
i=1 # Init Part
while(i<11):
print("\t{} x {}={}".format(n,i,n*i))
i=i+1
else:
print("*"*50)
#program for generating Mul Table for a given +ve number
#MulTableEx2.py
n=int(input("Enter a Number for generating Mul Table:"))
if(n<=0):
print("{} is invalid input".format(n))
else:
print("-"*50)
print("Mul table for {}".format(n))
print("-" * 50)
for i in range(1,11):
print("\t{} x {}={}".format(n,i,n*i))
else:
print("*" * 50)

write a python program which will find the sum of n number where n is positive integr value

#Program for finding Sum of First Natural Numbers


#NatNumsSumEx1.py
n=int(input("Enter How Numbers Sum u want to Find:"))
if(n<=0):
print("{} is Invalid Input".format(n))
else:
print("-"*50)
print("{} First Natural Numbers Sum".format(n))
print("-" * 50)
s=0
i=1
while(i<=n):
print("\t{}".format(i))
s=s+i
i=i+1
else:
print("-"*50)
print("Sum={}".format(s))
print("-" * 50)

write a python program which will find the sum of sqaures of first n natural number

#Program for finding Sum of Squares of First Natural Numbers


#NatNumsSquaresSumEx.py
n=int(input("Enter How Numbers Sum u want to Find:"))
if(n<=0):
print("{} is Invalid Input".format(n))
else:
print("-"*50)
print("\tNatNums\tSquares\tCubes")
print("-" * 50)
s,ss,cs=0,0,0
i=1
while(i<=n):
print("\t{}\t\t{}\t\t{}".format(i,i**2,i**3))
s=s+i
ss = ss + i ** 2
cs=cs+i**3
i=i+1

else:
print("-" * 50)
print("\t{}\t\t{}\t\t{}".format(s,ss,cs))
print("-" * 50)

#Program for finding product First Natural Numbers


#ProductNumberEx1.py
n=int(input("Enter How Numbers Product u want to Find:"))
if(n<=0):
print("{} is Invalid Input".format(n))
else:
print("-"*50)
print("Product of First {} Natural Nums:".format(n))
print("-" * 50)
p=1
i=1
while(i<=n):
print("\t{}".format(i))
p=p*i
i=i+1
else:
print("-" * 50)
print("Product={}".format(p))
print("-" * 50)

write a python program which will except a line of text and split into word and display those words
and their lenght

#LineintoWordsEx1.py
line=input("Enter Line of Text:")
print("----------------------------------------")
print("Given Line:{}".format(line))
print("----------------------------------------")
words=line.split() # here words is an obj of list
print('Given Words={}'.format(words))
print("----------------------------------------")
print("\tWords\t\tLength")
print("----------------------------------------")
i=0
while(i<len(words)):
print("\t{}\t\t{}".format(words[i],len(words[i])))
i=i+1
else:
print("----------------------------------------")

day – 38

write a python program which will except a word or line or text and display each and every character

==============================================
2. for loop or for ...else loop
==============================================
Syntax1:-
-----------
for varname in Iterable_object:
----------------------------------------
Indentation block of stmts
----------------------------------------
---------------------------------------------------
Other statements in Program
---------------------------------------------------

---------------
Syntax2:
---------------
for varname in Iterable_object:
----------------------------------------
Indentation block of stmts
----------------------------------------
else:
----------------------------------------
else block of statements
----------------------------------------
---------------------------------------------------
Other statements in Program
---------------------------------------------------

Explanation:
-----------------------
=>Here 'for' , "in" and 'else' are keywords
=>Here Iterable_object can be Sequence(bytes,bytearray,range,str),
list(list,tuple),set(set,frozenset) and dict.
=>The execution process of for loop is that " Each of Element of Iterable_object selected , placed in
varname and executes Indentation block of statements".This Process will be repeated until all
elements of Iterable_object completed.
=> when all the elements of Iterable Object completed then PVM comes out of for loop and
executes else block of statements which are written under else block
=>Writing else block is optional.
========================================================================
==========
#program for generating Mul Table for a given +ve number
#MulTableEx2.py
n=int(input("Enter a Number for generating Mul Table:"))
if(n<=0):
print("{} is invalid input".format(n))
else:
print("-"*50)
print("Mul table for {}".format(n))
print("-" * 50)
for i in range(1,11):
print("\t{} x {}={}".format(n,i,n*i))
else:
print("*" * 50)

write a python proram which will except a numwerical intefger value genrate amultiplitaion table by
using while loop.

#FactEExWhile1.py
n=int(input("Enter a Number for Cal factorial:"))
if(n<0):
print("{} is Invalid Input".format(n))
else:
f=1
i=1
while(i<=n):
f=f*i
i=i+1
else:
print("Factorial({})={}".format(n,f))

#Program for finding product First Natural Numbers


#ProductNumberEx1.py
n=int(input("Enter How Numbers Product u want to Find:"))
if(n<=0):
print("{} is Invalid Input".format(n))
else:
print("-"*50)
print("Product of First {} Natural Nums:".format(n))
print("-" * 50)
p=1
i=1
while(i<=n):
print("\t{}".format(i))
p=p*i
i=i+1
else:
print("-" * 50)
print("Product={}".format(p))
print("-" * 50)
#FactEExWhile1.py
n=int(input("Enter a Number for Cal factorial:"))
if(n<0):
print("{} is Invalid Input".format(n))
else:
f=1
i=1
while(i<=n):
f=f*i
i=i+1
else:
print("Factorial({})={}".format(n,f))

#FactEExWhile2.py
n=int(input("Enter a Number for Cal factorial:"))
if(n<0):
print("{} is Invalid Input".format(n))
else:
f=1
i=n
while(i>0):
f=f*i
i=i-1
else:
print("Factorial({})={}".format(n,f))

#Program for finding Sum of Squares of First Natural Numbers


#NatNumsSquaresSumEx.py
n=int(input("Enter How Numbers Sum u want to Find:"))
if(n<=0):
print("{} is Invalid Input".format(n))
else:
print("-"*50)
print("\tNatNums\tSquares\tCubes")
print("-" * 50)
s,ss,cs=0,0,0
i=1
while(i<=n):
print("\t{}\t\t{}\t\t{}".format(i,i**2,i**3))
s=s+i
ss = ss + i ** 2
cs=cs+i**3
i=i+1

else:
print("-" * 50)
print("\t{}\t\t{}\t\t{}".format(s,ss,cs))
print("-" * 50)

#Program for finding Sum of First Natural Numbers


#NatNumsSumEx1.py
n=int(input("Enter How Numbers Sum u want to Find:"))
if(n<=0):
print("{} is Invalid Input".format(n))
else:
print("-"*50)
print("{} First Natural Numbers Sum".format(n))
print("-" * 50)
s=0
i=1
while(i<=n):
print("\t{}".format(i))
s=s+i
i=i+1
else:
print("-"*50)
print("Sum={}".format(s))
print("-" * 50)

#FactExForLoop1.py
n=int(input("Enter a Number for Cal factorial:"))
if(n<0):
print("{} is Invalid Input".format(n))
else:
f=1
for i in range(1,n+1):
f=f*i
else:
print("\t{}!={}".format(n,f))

#FactExForLoop2.py
n=int(input("Enter a Number for Cal factorial:"))
if(n<0):
print("{} is Invalid Input".format(n))
else:
f=1
for i in range(n,0,-1):
f=f*i
else:
print("Factorial({})={}".format(n,f))

write a python program which will generate list of even numbers with in a given number n by using
for loop

or odd
write a python program which will except any positve numerical integer value and display its factor.

#Program for obtaining Factors of a given number


#FactorEx1.py
n=int(input("Enter a Number for getting its Factors:"))
if(n<=0):
print("{} is Inavlid Input".format(n))
else:
print("-"*50)
print("Factor of {}".format(n))
print("-" * 50)
for i in range(1,n+1):
if(n%i==0):
print("\t{}".format(i))
else:
print("-" * 50)

#Program for obtaining Factors of a given number


#FactorEx2.py
n=int(input("Enter a Number for getting its Factors:"))
if(n<=0):
print("{} is Inavlid Input".format(n))
else:
print("-"*50)
print("Factor of {}".format(n))
print("-" * 50)
for i in range(1,(n//2)+1):
if(n%i==0):
print("\t{}".format(i))
else:
print("\t{}".format(n))
print("-" * 50)

write a python program which will find sum of the digit of the given number .

#Program for finding sum of digits of a given number


#DigitsSumEx1.py
n=int(input("Enter a Number:"))
if(n<=0):
print("{} is invalid Input".format(n))
else:
s=0
while(n>0):
r=n%10
s=s+r
n=n//10
else:
print("Digits Sum={}".format(s))
#Program for finding sum of digits of a given number
#DigitsSumEx2.py
n=input("Enter a Number:")
if(int(n)<=0):
print("{} is invalid Input".format(n))
else:
s=0
print("Given Number:{} ".format(n))
digits=n.split()
for digit in digits[0]:
s=s+int(digit)
else:
print("Sum of Digits={}".format(s))

#Program for finding sum of digits of a given number


#DigitsSumEx2.py
n=input("Enter a Number:")
if(int(n)<=0):
print("{} is invalid Input".format(n))
else:
s=0
print("Given Number:{} ".format(n))
digits=list(n) # Type Casting str into digits
for digit in digits:
s=s+float(digit)
else:
print("sum of digits={}".format(s))

Day – 39

===========================================
Transfer Flow Control Statements
===========================================
=>The purpose of Transfer Flow Control Statements in Python is that " To change the control of
PVM
from One Part of the Program another part of Program".
=>In Python Programming, we have 4 types of Transfer Flow Control Statements. They are
1. break
2. continue
3. pass
4. return
=================================x======================================.

---------------------------------
break statement
---------------------------------
=>break is a key word
=>The purpose of break statement is that "To terminate the execution of loop logically when certain
condition is satisfied and PVM control comes of corresponding loop and executes other statements
in the program".
=>when break statement takes place inside for loop or while loop then PVM will not execute
corresponding else block(bcoz loop is not becming False) but it executes other statements in the
program
=>Syntax1:
-------------------
for varname in Iterable_object:
------------------------------
if (test cond):
break
------------------------------
------------------------------
------------------
=>Syntax2:
-------------------
while(Test Cond-1):
------------------------------
if (test cond-2):
break
------------------------------
------------------------------
================================X.========================.

#program for Demonstrating Break statement


#BreakEx1.py
s="PYTHON"
#Display all the letter of s--Part-1
for ch in s:
print("\t{}".format(ch))
else:
print("i am from else of for loop")
print("Program execution Completed")
print("-------------------------------------")
#want to display PYT without using slicing and indexing-Part-2
for ch in s:
if(ch=="H"):
break
else:
print("\t{}".format(ch))
else:
print("i am from else of for loop")
print("Program execution Completed")

#program for Demonstrating Break statement


#BreakEx2.py
s="PYTHON"
#Display all the letter of s--Part-1
i=0
while(i<len(s)):
print("\t{}".format(s[i]))
i=i+1
else:
print("i am from else part of while")
print("Program execution completed")
print("-------------------------------------")
#want to display PYT without using slicing and indexing-Part-2
i=0
while(i<len(s)):
if(s[i]=="H"):
break
else:
print("\t{}".format(s[i]))
i=i+1
else:
print("i am from else part of while")
print("Program execution completed")

writea python which will except a numerical integer int value and decide whether it is prime or not

#Program deciding wtheter the given number is Prime or Not


#PrimeEx1.py
n=int(input("Enter a Number:"))
if(n<=1):
print("{} is Invalid Input".format(n))
else:
res="PRIME"
for i in range(2,n):
if(n%i==0):
res="NOT PRIME"
break
if(res=="PRIME"):
print("{} is {}".format(n,res))
else:
print("{} is {}".format(n, res))

#Program deciding wtheter the given number is Prime or Not


#PrimeEx2.py
n=int(input("Enter a Number:"))
if(n<=1):
print("{} is Invalid Input".format(n))
else:
res=True
for i in range(2,n):
if(n%i==0):
res=False
break
if(res):
print("{} is PRIME".format(n))
else:
print("{} is Not PRIME ".format(n))

-------------------------------------
continue statement
-------------------------------------
=>continue is a keyword
=>continue statement is used for making the PVM to go to the top of the loop without executing the
following statements which are written after continue statement for that current Iteration only.
=>continue statement to be used always inside of loops.
=>when we use continue statement inside of loop then else part of corresponding loop also executes
provided loop condition becomes false.
-----------------
=>Syntax:-
----------------
for varname in Iterable-object:
------------------------------------------
if ( Test Cond):
continue
statement-1 # written after continue statement
statement-2
statement-n
-----------------------------------------
-----------------------------------------

=>Syntax:-
----------------
while (Test Cond):
------------------------------------------
if ( Test Cond):
continue
statement-1 # written after continue stateemnt
statement-2
statement-n
-----------------------------------------
-----------------------------------------

===========================X==================================.

#Program for Demonstating Continue statement


#ContinueEx1.py
s="PYTHON"
#Display all the letter of s--Part-1
for ch in s:
print("\t{}".format(ch))
else:
print("i am from else of for loop")
print("Program execution Completed")
print("-------------------------------------")
#Want to display PYHON
for ch in s:
if(ch=="T"):
continue
print(ch)
else:
print("i am from else of for loop")
print("Program execution Completed")

#Program for Demonstating Continue statement


#ContinueEx2.py
s="PYTHON"
#Display all the letter of s--Part-1
i=0
while(i<len(s)):
print("\t{}".format(s[i]))
i=i+1
else:
print("i am from else of while loop")
print("Program execution Completed")
print("-------------------------------------")
#Want to display PYHON
i=0
while(i<len(s)):
if(s[i]=="T"):
i=i+1
continue

else:
print("\t{}".format(s[i]))
i=i+1
else:
print("i am from else of while loop")
print("Program execution Completed")

#Program for Demonstating Continue statement


#ContinueEx3.py
s="PYTHON"
#Want to display PTON
i=0
while(i<len(s)):
if(s[i]=="Y") or (s[i]=="H"):
i=i+1
continue
else:
print("\t{}".format(s[i]))
i=i+1
else:
print("i am from else of while loop")
print("Program execution Completed")
#Program for Demonstating Continue statement
#ContinueEx4.py
s="PYTHON"
#Want to display PTON
i=0
while(i<len(s)):
if(s[i] in ["Y","H"]):
i=i+1
continue
else:
print("\t{}".format(s[i]))
i=i+1
else:
print("i am from else of while loop")
print("Program execution Completed")

#ContinueEx5.py
lst=[10,-34,56,-23,0,-2,45,67,-56,12]
print("--------------------------------")
print("Given Numbers:{}".format(lst))
print("--------------------------------")
print("List of +Ve values")
print("--------------------------------")
for val in lst:
if(val<=0):
continue
print("\t{}".format(val))
print("--------------------------------")

#ContinueEx6.py
lst=[10,-34,56,-23,0,-2,45,67,-56,12]
print("--------------------------------")
print("Given Numbers:{}".format(lst))
print("--------------------------------")
print("List of -Ve values")
print("--------------------------------")
for val in lst:
if(val>=0):
continue
print("\t{}".format(val))
print("--------------------------------")

list of numerical value and display only positive value

print for reading the values from keyboard


DAY --- 40

#InnerLoopsEx1.py--for loop in for loop


for i in range(1,6): # Outer Loop
print("value of i outer loop:{}".format(i))
print("------------------------------")
for j in range(1,4): # Inner Loop
print("\tvalue of j-Inner Loop:{}".format(j))
else:
print("\tI am coming out of inner loop")
print("------------------------------")
else:
print("I am coming out of outer loop")

#InnerLoopsEx2.py--while loop in while loop


i=1
while(i<=5): #Outer Loop
print("value of i outer loop:{}".format(i))
print("------------------------------")
j=1
while(j<=3): # Inner Loop
print("\tvalue of j-Inner Loop:{}".format(j))
j=j+1
else:
i=i+1
print("\tI am coming out of inner loop")
print("------------------------------")
else:
print("I am coming out of outer loop")

#InnerLoopsEx2.py--for loop in while loop


i=1
while(i<=5): #Outer Loop
print("value of i outer loop:{}".format(i))
print("------------------------------")
for j in range(3,0,-1): # inner loop
print("\tvalue of j-Inner Loop:{}".format(j))
else:
i=i+1
print("\tI am coming out of inner loop")
print("------------------------------")
else:
print("I am coming out of outer loop")

#InnerLoopsEx4.py--while loop in for loop


for i in range(5,0,-1): # Outer Loop
print("value of i outer loop:{}".format(i))
print("------------------------------")
j=3
while(j>0): # Inner Loop
print("\tvalue of j-Inner Loop:{}".format(j))
j=j-1
else:
print("\tI am coming out of inner loop")
print("------------------------------")
else:
print("I am coming out of outer loop")

write a python program which will display 1 to n multiplication table

#InnerLoopsMultables.py
n=int(input("How Many Mul tables u want:"))
if(n<=0):
print("{} is Invalid Input:".format(n))
else:
for num in range(1,n+1): # Outer Loop--Supply Number
print("------------------------------")
print("Mul Table for {}".format(num))
print("------------------------------")
for i in range(1,11): # Inner Loop--displays Mul table
print("\t{} x {}={}".format(num,i,num*i))
else:
print("------------------------------")

write a python prohram which will display num of random multiplication table

#Innerrandmonmultables.py
n=int(input("How Many Mul tables u want:"))
if(n<=0):
print("{} is Invalid Input:".format(n))
else:
lst=list()
for i in range(1,n+1):
val=int(input("Enter {} Number:".format(i)))
lst.append(val)
else:
print("-"*50)
print("Given List of Values:{}".format(lst))#[12, 19, 9, -5, 0]
print("-" * 50)
for num in lst: # Outer Loop--supply the value from list obj
if(num<=0):
print("{} invalid input".format(num))
else:
print("-" * 50)
print("Mul table for {}".format(num))
print("-" * 50)
for i in range(1,11):#Inner loop-- display Mul table
print("\t{} x {}={}".format(num,i,num*i))
else:
print("-" * 50)

write a python program which will dispaly list of prime with in the given range

#InnerLoopsPrimes.py
n=int(input("Enter the Range of Prime Numbers:"))
if(n<=1):
print("{} is Invalid".format(n))
else:
lst=list()
for num in range(2,n+1):
res="PRIME"
for i in range(2,num):
if(num%i==0):
res="NOTPRIME"
break # From inner Loop
if(res=="PRIME"):
lst.append(num) # placing primes in list
else:
print("List of Primes")
for v in lst:
print("\t{}".format(v))

#InnerLoopsPrimes1.py
n=int(input("Enter the Range of Prime Numbers:"))
if(n<=1):
print("{} is Invalid".format(n))
else:
lst=list()
for num in range(2,n+1):
res=False
for i in range(2,num):
if(num%i==0):
res=True
break # From inner Loop
if(res==False):
lst.append(num) # placing primes in list
else:
print("List of Primes")
for v in lst:
print("\t{}".format(v))
DAY – 41

write a python program which will decide whether citzen elgible or vote or not

print("voter age list ")


while(True)
age = int (input("enter your age "))
if(age >=18):
break
print("\t {} years invalid age ,try again".format(age))

print("{} years voter is eligable to vote".format(age))

write a python program which will emplement the following except student number student name and
marks in three subjects such as c ,c++ and python
1. compute total marks
2. tot marks (cmm+cppm+pym)
3. compute the percentage of marks (%=tot marks )
4. student is fail provide student secured less than 40 in any one of the subject
5. give the student grade is distriction provided total marks ranges from 300 and 250
6. student grade is first provided total marks ranges from 249 and 200
7. tudent grade is second provided total marks ranges from 199 and 150
8. tudent grade is third provided total marks ranges from 149 and 120

display

#program for Generating student Marks Report


#StudentMarksReport1.py
#Validation of Student Number
while(True):
sno=int(input("Enter Student Number:"))
if(sno>0):
break
print("\t{} Is Invalid Student Number:".format(sno))
#Accept Student Name
sname=input("Enter Student Name:")
#Validation of C lang Marks(0-100)
while(True):
cm=int(input("Enter Marks in C:"))
if(cm>=0) and (cm<=100):
break
print("\t{} Is Invalid Marks in C:".format(cm))
#Validation of CPP lang Marks(0-100)
while(True):
cppm=int(input("Enter Marks in C++:"))
if(0<=cppm<=100):
break
print("\t{} Is Invalid Marks in C++:".format(cppm))
#Validation of PYTHON lang Marks(0-100)
while(True):
pym=int(input("Enter Marks in PYTHON:"))
if(0<=pym<=100):
break
print("\t{} Is Invalid Marks in PYTHON:".format(pym))
#Compute TotalMarks and Percentage
totmarks=cm+cppm+pym
percent=(totmarks/300)*100
#Decide the grade
if(cm<40) or (cppm<40) or (pym<40):
grade="FAIL"
else:
if(totmarks>=250) and (totmarks<=300):
grade="DISTINCTION"
elif(totmarks>=200) and (totmarks<=249):
grade="FIRTST"
elif(totmarks>=150) and (totmarks<=199):
grade="SECOND"
elif(totmarks>=120) and (totmarks<=149):
grade="THIRD"
#Display Student Marks Report
print("="*50)
print("\t\tStudent Marks Report:")
print("="*50)
print("\tStudent Number:{}".format(sno))
print("\tStudent Name:{}".format(sname))
print("\tStudent Marks in C:{}".format(cm))
print("\tStudent Marks in C++:{}".format(cppm))
print("\tStudent Marks in PYTHON:{}".format(pym))
print("-"*50)
print("\tStudent Total Marks:{}".format(totmarks))
print("\tStudent Percentage of Marks:{}".format(percent))
print("\tStudent Grade:{}".format(grade))
print("="*50)

#program for Generating student Marks Report


#StudentMarksReport2.py
#Validation of Student Number
while(True):
while(True):
sno=int(input("Enter Student Number:"))
if(sno>0):
break
print("\t{} Is Invalid Student Number:".format(sno))
#Accept Student Name
sname=input("Enter Student Name:")
#Validation of C lang Marks(0-100)
while(True):
cm=int(input("Enter Marks in C:"))
if(cm>=0) and (cm<=100):
break
print("\t{} Is Invalid Marks in C:".format(cm))
#Validation of CPP lang Marks(0-100)
while(True):
cppm=int(input("Enter Marks in C++:"))
if(0<=cppm<=100):
break
print("\t{} Is Invalid Marks in C++:".format(cppm))

#Validation of PYTHON lang Marks(0-100)


while(True):
pym=int(input("Enter Marks in PYTHON:"))
if(0<=pym<=100):
break
print("\t{} Is Invalid Marks in PYTHON:".format(pym))
#Compute TotalMarks and Percentage
totmarks=cm+cppm+pym
percent=(totmarks/300)*100
#Decide the grade
if(cm<40) or (cppm<40) or (pym<40):
grade="FAIL"
else:
if(totmarks>=250) and (totmarks<=300):
grade="DISTINCTION"
elif(totmarks>=200) and (totmarks<=249):
grade="FIRTST"
elif(totmarks>=150) and (totmarks<=199):
grade="SECOND"
elif(totmarks>=120) and (totmarks<=149):
grade="THIRD"
#Display Student Marks Report
print("="*50)
print("\t\tStudent Marks Report:")
print("="*50)
print("\tStudent Number:{}".format(sno))
print("\tStudent Name:{}".format(sname))
print("\tStudent Marks in C:{}".format(cm))
print("\tStudent Marks in C++:{}".format(cppm))
print("\tStudent Marks in PYTHON:{}".format(pym))
print("-"*50)
print("\tStudent Total Marks:{}".format(totmarks))
print("\tStudent Percentage of Marks:{}".format(percent))
print("\tStudent Grade:{}".format(grade))
print("="*50)
ch=input("\nDo u want to Enter Another Student Data(yes/no):")
if(ch.lower()=="no"):
print("Thx for using Program")
break
write a python program which will except employee no emplyee name and basic salery
salery +
write a python program list of palidrom which is highest in length

#Program for finding Largest Palindrome from list of words


#PalindromeLenEx1.py
lst=["MOM","DAD","RACECAR","NAN","MALAYALAM","MADAM","LIRIL"]
d=dict() # create an empty dict
for word in lst:
d[word]=len(word)
else:
print("-----------------------------------------")
for pname,plen in d.items():
print("\t{}--->{}".format(pname,plen))
else:
plist=[] #empty list for adding Largest Palindrome name
print("-----------------------------------------")
#Logic for finding Largest palindrome
mpl=max(d.values()) # 9
for dw,dwlen in d.items():
if(dwlen==mpl):
plist.append(dw)
else:
print("Largest Palindrome:",end=" ")
for val in plist:
print(val)

day 42
=========================================================
Functions in Python--8 days
=========================================================
Index
-----------
=>Purpose of Functions
=>Types of languages
a) Un-Structured Programming Lang
b) Structured Programming Lang
=>Definition of Function
=>Parts of Function
=>Phases in Functions
=>Syntax for Defining Functions
=>Programming Examples
=>Number of approaches to define Functions
=>Programming Examples
--------------------------------------------------------------------------------------------------------------------------
-
=>Arguments and Parameters
=>Types of Arguments
1. Posstional Arguments
2. Default Arguments
3. Keyword Arguments
4. Variable Length Arguments
5. Keyword Variable Length Arguments
=>Programming Examples
---------------------------------------------------------------------------------------------------------------------
=>Global and Local Variables
=>Programming Examples
=>global keyword
=>globals()
=>Programming Examples
=>Anonymous OR Lambda Functions
=>Implementation of Anonymous OR Lambda Functions
=>Programming Examples
----------------------------------------------------------------------------------------------------------------------
=>Special Functions in Python
a) filter() with Normal and Anonymous Function
b) map() with Normal and Anonymous Function
c) reduce() with Normal and Anonymous Function
=>Programming Examples
==================================x=====================================
=====
======================================================
Types of languages
======================================================
=>In the content of Functions, we have Two Types of programming Languages. They are

a) Un-Structured Programming Lang


b) Structured Programming Lang
--------------------------------------------------------------------------------------------------------------------------
-------------
a) Un-Structured Programming Lang
--------------------------------------------------------------------------------------------------------------------------
-------------
=>In Un-Structured Programming Lang, We don't have the concept of FUNCTIONS.
=>Since Un-Structured Programming Lang does not contains the concept of FUNCTIONS and
Hence
whose Applications having the following Limitations.

1. Application development Time is More


2. Application takes More memory Space
3. Application execution time is More
4. Application Performance Degraded
5. Redundency ( Duplication or Replication) of the Code is More.

Examples: GW-BASIC
--------------------------------------------------------------------------------------------------------------------------
-------------
b) Structured Programming Lang
--------------------------------------------------------------------------------------------------------------------------
-------------
=>In Structured Programming Lang, We have the concept of FUNCTIONS.
=>Since Structured Programming Lang contains the concept of FUNCTIONS and Hence
whose Applications having the following Advantages.
1. Application development Time is Less
2. Application takes Less memory Space
3. Application execution time is Less
4. Application Performance Enahnced (Improved)
5. Redundency ( Duplication or Replication) of the Code is Minimized.

Examples: C,C++,Java,PYTHON,C#.net...etc
--------------------------------------------------------------------------------------------------------------------------
-------------.

===========================================================
Functions in Python
===========================================================
=>The purpose of Functions is that " To Perform Certain Operation /Task and Provides Code
Re-Usability".
=>The Advantages of Functions in any languages are
1. Application Development time is Less
2. Application Memory Space is Less
3. Application Execution Time is Less
4. Application Performance is Enhanced
5. Redundency of the Code is Minimized
--------------------------------------------------------------------------------------------------------------------------
------
Definitions of Function
--------------------------------------------------------------------------------------------------------------------------
------
=>Sub Program of Main Program is Called Function.
(OR).
=>A Part of main program is Called Function.
--------------------------------------------------------------------------------------------------------------------------
------
Parts of Functions
--------------------------------------------------------------------------------------------------------------------------
------
=>At the time Developing functions in real time, we must ensure that, there must exist 2 Parts. they
are
1. Function Definition
2. Function Calls
=>Every Function Definition Exists Only Once
=>Every Function call must contains a Function Defintion Otherwise we get NameError.
=>Function Definition will execute when we call by using function calls OR Without calling the
Function
by using Function Calls PVM will not execute Function Definition.
--------------------------------------------------------------------------------------------------------------------------
------
Phases in Functions
--------------------------------------------------------------------------------------------------------------------------
------
=>At the time Defining the functions, the Programmer must ensure that there must exist the
following Phases.
1. Every Function Must take INPUT
2. Every Function Must PROCESS the Input
3. Every Function Must give OUTPUT or RESULT
--------------------------------------------------------------------------------------------------------------------------
-----.

#this program computes Sum of Two Numbers by using functions


#FunEx1.py
def addop(a,b):
print("i am inside of addop()")
c=a+b
return c
#main program
print("Line:8: I am here after Function definition:")
res=addop(3,4) # Function call
print("Line-10--Sum=",res)
res=addop(100,200) # Function call
print("sum=",res)

DAY ---- 43

#Program for defining a Function for cal Mul of two numbers


#ApproachEx1.py
#INPUT---------->Taking From Function Call
#PROCESS-------->Done in Function Body
#RESULT OR OUTPUT-->Given to Function Call
def mulop(a,b): # here a ,b are called formal parameters
c=a*b # here c is called local variable
return c
#main program
a=float(input("Enter First Value:"))
b=float(input("Enter Second Value:"))
res=mulop(a,b) # Function call
print("Mul({},{})={}".format(a,b,res))

#Program for defining a Function for cal Mul of two numbers


#ApproachEx2.py
#INPUT---------->Taking in Function Body
#PROCESS-------->Done in Function Body
#RESULT OR OUTPUT-->Displayed in Function Body
def mulop():
#Input
a=float(input("Enter First Value:"))
b=float(input("Enter Second Value:"))
#Procees
c=a*b
#result
print("Mul({},{})={}".format(a,b,c))

#main program
mulop() # Function call

#Program for defining a Function for cal Mul of two numbers


#ApproachEx3.py
#INPUT---------->TTaking From Function Call
#PROCESS-------->Done in Function Body
#RESULT OR OUTPUT-->Displayed in Function Body
def mulop(k,v):
r=k*v
print("mul({},{})={}".format(k,v,r))

#main program
a=float(input("Enter First Value:"))
b=float(input("Enter Second Value:"))
mulop(a,b) # Function call

##Program for defining a Function for cal Mul of two numbers


#ApproachEx4.py
#INPUT---------->Taking in Function Body
#PROCESS-------->Done in Function Body
#RESULT OR OUTPUT-->Given to Function Call
def mulop():
#Input
a = float(input("Enter First Value:"))
b = float(input("Enter Second Value:"))
# Procees
c=a*b
#Give the Result to Function call
return a,b,c

#main program
a,b,res=mulop() # Function call with Multipline assigment
print("mul({},{})={}".format(a,b,res))
print("-------------OR------------------")
res=mulop() #function call with Single Line assignment
#here res is type of tuple
print(res,type(res)) # (7.0, 8.0, 56.0) <class 'tuple'>
print("mul({},{})={}".format(res[-3],res[-2],res[-1]))

WRITE A PYHON PROGRAM FOR DEFING FUNCTION TO CLACULATE SIMPLE INTRESET


AND TOTAL AMOUNT TOPAY .

WRITE A PYTHON WHICH WILL CALCULATE FACTORIAL OF GIVEN NUMBER BY


USING FUNCTION \

#Function for cal factorial of a number


#FactEx1.py
def factcal(n):
if(n<0):
return "{} Is -VE and No Factorial".format(n)
else:
f=1
for i in range(1,n+1):
f=f*i
return f

#main program
n=int(input("Enter a Number for cal factorial:"))
result=factcal(n)
print("Fact({})={}".format(n,result))

which will except any word decide whether it is palindrom or not by using function

write a python program which will caliculate area and parimeter of circle by using function

#CircleAreaPeriEx.py
def circlearea():
r=float(input("Enter Radius for Cal Area of Circle"))
ac=3.14*r**2
print("Area of Circle:{}".format(ac))
def circleperi():
r = float(input("Enter Radius for Cal Peri. of Circle"))
pc = 2*3.14 * r
print("Perimeter of Circle:{}".format(pc))
def menu():
print("=========================")
print("\t\t1.Circle Area:")
print("\t\t2.Circle Perimeter:")
print("\t\t3.Exit")
print("=========================")

#main program
while(True):
menu()
ch=int(input("Enter Ur Choice:"))
match(ch):
case 1:
circlearea()
case 2:
circleperi()
case 3:
print("Thx for using this program")
break
case _:

def table(r):
print("table {}".format(r))
for i in range (1,11):
print("{} x {} = {}".format(r,i,r*i))
num=input("enter by user value ")
table(num)

DAY --- 44

===\
===============================================
Parameters and Arguments
===============================================
--------------
Parameter:
---------------
=>The variables used in Function Heading are called Formal Parameters and They are used for
Stroing
the inputs coming Function Calls.
=>The Variables Used in Function Body are called Local Variables / Parameters and They are used
for
Storing Temporary Results / Function Processing Logic Results.
=>The Values Formal Parameters and Local parameters can be accessed within corresponding
Function
Definition but not possible to access in Other Part of the Program

Examples: def sumop(a,b): # Here a, b are called Formal parameters


c=a+b # Here c is local Parameter/Variable
----------
-----------------
Arguments:
-----------------
=>Arguments are the variables / Values which are used as Variables in Function Calls.
Examples: sumop(10,20) # Here 10 20 are called Argument Values
(OR)
a=10
b=20
sumop(a,b) # Here a,b are called Arguments (Actual variables)
=>The relationship between Arguments and Parameters is that all the Values of arguments are passing
to Parameters. This Mechanism is called Arguments Passing.

Types of Arguments and Parameters


=================================================
=>As we Know that all the Values of arguments are passing to Parameters.
=>Based on Passing the values of Arguments from Function to Formal Parameters of Function
Definition, The arguments are classified into 5 Types. They are
1. Possitional Arguments.
2. Default Arguments
3. Keyword Arguments
4. Variables Length Arguments
5. Keyword Variables Length Arguments
========================================================================
========
=========================================
1) Possitional Arguments (or) Parameters
=========================================
=>The Concept of Possitional Parameters (or) arguments says that "The Number of Arguments of
Function Call must be equal to the number of formal parameters in Function Heading".
=>This Parameter mechanism also recommends to follow Order and Meaning of Parameters for
Higher accuracy.
=>To pass the Specific Data from Function Call to Function Definition then we must take Possitional
Argument Mechanism.
=>The default Argument Passing Mechanism is Possitional Arguments (or) Parameters.
-----------------------------------------------
Syntax for Function Definition :
-----------------------------------------------
def functionname(param1,param2.....param-n):
-------------------------------------------------
-------------------------------------------------

-----------------------------------------------
Syntax for Function Call:
-----------------------------------------------
functionname(arg1,arg2....arg-n)

=>Here the values of arg1,arg2...arg-n are passing to param-1,param-2..param-n respectively.


=>PVM gives First Priority to Possitional Arguments.
========================x================================

#PROGRAM FOR DEMONSTRATING THE CONCEPT OF POSSITIONAL ARGUMENTS .

def dispstudioinfo(sno,sname,marks):pass
print("\t{}\t{}\t{}".format(sno,sname,marks))
print("="*50)
print("\tsno\tsname\tmarks")
dispstudinfo(100,"rs",34.56)
dispstudinfo(100,"rs",34.56)
dispstudinfo(100,"rs",34.56)
dispstudinfo(100,"rs",34.56)
print("="*50)
#Program for Demonstarting the concept of Possitional Arguments.
#PossArgsEx1.py
def dispstudinfo(sno,sname,marks):
print("\t{}\t{}\t{}".format(sno,sname,marks))

#main program
print("="*50)
print("\tSNO\tNAME\tMARKS")
print("="*50)
dispstudinfo(100,"RS",34.56) # Function Call
dispstudinfo(200,"TR",44.55) # Function Call
dispstudinfo(300,"DR",14.55) # Function Call
dispstudinfo(400,"KV",11.11) # Function Call
print("="*50)

#Program for Demonstarting the concept of Possitional Arguments.


#PossArgsEx2.py
def dispstudinfo(sno,sname,marks,crs):
print("\t{}\t{}\t{}\t{}".format(sno,sname,marks,crs))

#main program
print("="*50)
print("\tSNO\tNAME\tMARKS\tCOURSE")
print("="*50)
dispstudinfo(100,"RS",34.56,"PYTHON") # Function Call
dispstudinfo(200,"TR",44.55,"PYTHON") # Function Call
dispstudinfo(300,"DR",14.55,"PYTHON") # Function Call
dispstudinfo(400,"KV",11.11,"PYTHON") # Function Call
print("="*50)

#Program for Demonstarting the concept of default Arguments.


#DefArgsEx1.py
def dispstudinfo(sno,sname,marks,crs="PYTHON"):
print("\t{}\t{}\t{}\t{}".format(sno,sname,marks,crs))

#main program
print("="*50)
print("\tSNO\tNAME\tMARKS\tCOURSE")
print("="*50)
dispstudinfo(100,"RS",34.56) # Function Call
dispstudinfo(200,"TR",44.55) # Function Call
dispstudinfo(300,"DR",14.55) # Function Call
dispstudinfo(400,"KV",11.11) # Function Call
print("="*50)

#Program for Demonstarting the concept of default Arguments.


#DefArgsEx2.py
def dispstudinfo(sno,sname,marks,crs="PYTHON"):
print("\t{}\t{}\t{}\t{}".format(sno,sname,marks,crs))

#main program
print("="*50)
print("\tSNO\tNAME\tMARKS\tCOURSE")
print("="*50)
dispstudinfo(100,"RS",34.56) # Function Call
dispstudinfo(200,"TR",44.55) # Function Call
dispstudinfo(300,"DR",14.55) # Function Call
dispstudinfo(400,"KV",11.11) # Function Call
dispstudinfo(500,"TRUMP",10.11) # Function Call
dispstudinfo(600,"BIDEN",30.11,"POLITICS") # Function Call
dispstudinfo(700,"VIVEK",40.11) # Function Call
print("="*50)

#Program for Demonstarting the concept of default Arguments.


#DefArgsEx3.py
def dispstudinfo(sno,sname,marks,crs="PYTHON",cnt="INDIA"):
print("\t{}\t{}\t{}\t{}\t{}".format(sno,sname,marks,crs,cnt))

#main program
print("="*50)
print("\tSNO\tNAME\tMARKS\tCOURSE\tCOUNTRY")
print("="*50)
dispstudinfo(100,"RS",34.56) # Function Call
dispstudinfo(200,"TR",44.55) # Function Call
dispstudinfo(300,"DR",14.55) # Function Call
dispstudinfo(400,"KV",11.11) # Function Call
dispstudinfo(500,"TRUMP",10.11,cnt="USA") # Function Call
dispstudinfo(600,"BIDEN",30.11,"POLITICS","USA") # Function Call
dispstudinfo(700,"VIVEK",40.11) # Function Call
print("="*50)

#Program for Demonstarting the concept of default Arguments.


#DefArgsEx4.py
def dispstudinfo1(sno,sname,marks,crs="PYTHON"):
print("\t{}\t{}\t{}\t{}".format(sno,sname,marks,crs))

def dispstudinfo2(sno,sname,marks,crs="JAVA"):
print("\t{}\t{}\t{}\t{}".format(sno,sname,marks,crs))

#main program
print("="*50)
print("\tSNO\tNAME\tMARKS\tCOURSE")
print("="*50)
dispstudinfo1(100,"RS",34.56) # Function Call
dispstudinfo1(200,"TR",44.55) # Function Call
dispstudinfo1(300,"DR",14.55) # Function Call
dispstudinfo1(400,"KV",11.11) # Function Call
print("="*50)
print("\tSNO\tNAME\tMARKS\tCOURSE")
print("="*50)
dispstudinfo2(500,"TRUMP",10.11) # Function Call
dispstudinfo2(600,"BIDEN",30.11) # Function Call
dispstudinfo2(700,"VIVEK",40.11) # Function Call
print("="*50)

#Program for Demonstarting the concept of default Arguments.


#DefArgsEx5.py
def circleareaperi(r,PI=3.14):
ac=PI*r**2
pc=2*PI*r
print("Radius:{}".format(r))
print("Area of Circle:{}".format(ac))
print("Peri of Circle:{}".format(pc))

#main program
circleareaperi(float(input("Enter Radius:")))

======================================
2) Default Parameters (or) arguments
======================================
=>When there is a Common Value for family of Similar Function Calls then Such type of Common
Value(s) must be taken as default parameter with common value (But not recommended to pass by
using Posstional Parameters)

Syntax for Function Definition with Default Parameters


----------------------------------------------------------------------------------------
def functionname(param1,param2,....param-n-1=Val1, Param-n=Val2):
------------------------------------------------------------------
------------------------------------------------------------------

Here param-n-1 and param-n are called "default Parameters".


and param1,param-2... are called "Possitional parameters".

Rule-: When we use default parameters in the function definition, They must be used as last
Parameter(s) otherwise we get Error( SyntaxError: non-default argument (Possitional ) follows
default argument).
========================================================================
====.

============================================
3) Keyword Parameters (or) arguments
============================================
=>In some of the circumstances, we know the function name and formal parameter names and we
don't know the order of formal Parameter names and to pass the data / values accurately we must use
the concept of Keyword Parameters (or) arguments.
=>The implementation of Keyword Parameters (or) arguments says that all the formal parameter
names used as arguments in Function call(s) as keys.

Syntax for function definition:-


-------------------------------------------------
def functionname(param1,param2...param-n):
---------------------------------------------
---------------------------------------------

Syntax for function call:-


-------------------------------------------------
functionname(param-n=val-n,param1=val1,param-n-1=val-n-1,.........)

Here param-n=val-n,param1=val1,param-n-1=val-n-1,...... are called Keywords arguments


=>When we specify Keyword arguments before Possitional Arguments in Function Calls(s) then we
get SyntaxError: positional argument follows keyword argument
========================================X===============================
=====
#Program for Demonstrating Keyword Arguments
#KeyWordArgsEx1.py
def disp(a,b,c,d):
print("\t{}\t{}\t{}\t{}".format(a,b,c,d))

#main program
print("="*50)
print("\tA\tB\tC\tD")
print("="*50)
disp(10,20,30,40) # Function call with Possitional Args
disp(d=40,a=10,c=30,b=20) # Function call with Keyword args
disp(b=20,c=30,d=40,a=10) # Function call with Keyword args
disp(10,20,d=40,c=30) # Function call with Possitional Args and Keyword args
#disp(d=40,c=30,10,20) # SyntaxError: positional argument follows keyword argument
disp(10,d=40,b=20,c=30)#Function call with Possitional Args and Keyword args
print("="*50)

#Program for Demonstrating Keyword Arguments


#KeyWordArgsEx2.py
def dispstudinfo(sno,sname,marks,crs="PYTHON"):
print("\t{}\t{}\t{}\t{}".format(sno,sname,marks,crs))

#main program
print("="*50)
print("\tSNO\tNAME\tMARKS\tCOURSE")
print("="*50)
dispstudinfo(100,"Monica",66.66) # Function call with Poss Args
dispstudinfo(marks=65.66,sno=200,sname="Sushma")# Function call with Keyword Args
dispstudinfo(crs="Java",sno=300,sname="sangita",marks=55.55)# Function call with Keyword Args
dispstudinfo(sname="Prajwala",marks=66.77,crs="Dsc",sno=400)# Function call with Keyword Args
dispstudinfo(500,"Udaya",crs="Java",marks=22.22)# Function call with Poss args and Keyword Args
print("="*50)

day --- 45

======================================
2) Default Parameters (or) arguments
======================================
=>When there is a Common Value for family of Similar Function Calls then Such type of Common
Value(s) must be taken as default parameter with common value (But not recommended to pass by
using Posstional Parameters)

Syntax for Function Definition with Default Parameters


----------------------------------------------------------------------------------------
def functionname(param1,param2,....param-n-1=Val1, Param-n=Val2):
------------------------------------------------------------------
------------------------------------------------------------------

Here param-n-1 and param-n are called "default Parameters".


and param1,param-2... are called "Possitional parameters".

Rule-: When we use default parameters in the function definition, They must be used as last
Parameter(s) otherwise we get Error( SyntaxError: non-default argument (Possitional ) follows
default argument).

#Program for demonstrating Variable Arguments


#VarArgsEx2.py
def disp(a,b,c,d): # Function Def-1
print(a,b,c,d)

disp(10,20,30,40) # Function Call-1


#-------------------------------------------------------------------------------------
def disp(a,b,c): # Function Def-2
print(a,b,c)

disp(10,20,30) # Function Call-2


#-------------------------------------------------------------------------------------
def disp(a,b): # Function Def-3
print(a,b)

disp(10,20) # Function Call-3


#-------------------------------------------------------------------------------------
def disp(a): # Function Def-4
print(a)

disp(10) # Function Call-4


#Program for demonstrating Variable Arguments
#This Program will not execute as it is
#VarArgsEx1.py
def disp(a,b,c,d): # Function Def-1
print(a,b,c,d)

def disp(a,b,c): # Function Def-2


print(a,b,c)

def disp(a,b): # Function Def-3


print(a,b)

def disp(a): # Function Def-4


print(a)

#main program
disp(10,20,30,40) # Function Call-1
disp(10,20,30) # Function Call-2
disp(10,20) # Function Call-3
disp(10) # Function Call-4

#Program for demonstrating Variable Arguments


#PureVarArgsEx1.py
def disp( *k ): # *param is called Variable Length parameter- whose type is tuple
print("-"*50)
print("Number of Values:{}".format(len(k)))
for v in k:
print("{}".format(v),end=" ")
print()
print("-"*50)

#main program
disp(10,20,30,40) # Function Call-1
disp(10,20,30) # Function Call-2
disp(10,20) # Function Call-3
disp(10) # Function Call-4
disp() # Function call-5
disp(10,"Rakesh",45.67,True,2+3j)

#Program for demonstrating Variable Arguments


#PureVarArgsEx2.py
def findsum(sno,sname, *vals):
print("="*50)
print("Student ID:{}".format(sno))
print("Student Name:{}".format(sname))
s=0
for val in vals:
print("\t{}".format(val))
s=s+val
print("="*50)
print("Sum={}".format(s))
print("="*50)

#main program
findsum(100,"Rossum",10,20,30,40,50) # Function call-1
findsum(200,"Travis",10,20,30,40) # Function call-2
findsum(300,"Kinney",10,20,30) # Function call-3
findsum(400,"Dennis",10,20) # Function call-4
findsum(500,"Kernigan",10) # Function call-5
findsum(600,"KVR") # Function call-6

#Program for demonstrating Variable Arguments


#PureVarArgsEx3.py
def findsum(sno,sname, *vals, city="HYD"):
print("="*50)
print("Student ID:{}".format(sno))
print("Student Name:{}".format(sname))
print("Living City:{}".format(city))
s=0
for val in vals:
print("\t{}".format(val))
s=s+val
print("="*50)
print("Sum={}".format(s))
print("="*50)

#main program
findsum(100,"Rossum",10,20,30,40,50) # Function call-1
findsum(200,"Travis",10,20,30,40) # Function call-2
findsum(300,"Kinney",10,20,30) # Function call-3
findsum(400,"Dennis",10,20) # Function call-4
findsum(500,"Kernigan",10) # Function call-5
findsum(600,"KVR") # Function call-6

#Program for demonstrating Variable Arguments


#PureVarArgsEx4.py
def findsum(sno,sname, *vals, city="HYD"):
print("="*50)
print("Student ID:{}".format(sno))
print("Student Name:{}".format(sname))
print("Living City:{}".format(city))
s=0
for val in vals:
print("\t{}".format(val))
s=s+val
print("="*50)
print("Sum={}".format(s))
print("="*50)

#main program
findsum(100,"Rossum",10,20,30,40,50) # Function call-1
findsum(200,"Travis",10,20,30,40) # Function call-2
findsum(300,"Kinney",10,20,30) # Function call-3
#findsum(400,"Dennis",city="RSA",10,20) # Function call-4--SyntaxError: positional argument
follows keyword argument
findsum(400,"Dennis",10,20,city="RSA")
findsum(500,"Kernigan",10,city="USA") # Function call-5
findsum(600,"KVR") # Function call-6

================================================
4) Variables Length Parameters (or) arguments
================================================
=>When we have familiy of multiple function calls with Variable number of values / arguments then
with normal python programming, we must define mutiple function defintions. This process leads to
more development time.
=>To overcome this process, we must use the concept of Variable length Parameters .
=>To Impelement, Variable length Parameters concept, we must define single Function Definition
and takes a formal Parameter preceded with a symbol called astrisk ( * param) and the formal
parameter with astrisk symbol is called Variable length Parameters and whose purpose is to hold /
store any number of values coming from similar function calls and whose type is <class, 'tuple'>.
---------------------------------------------------------------------------------------------------
Syntax for function definition with Variables Length Parameters:
--------------------------------------------------------------------------------------------------
def functionname(list of formal params, *param1,param2=value) :
--------------------------------------------------
--------------------------------------------------

=>Here *param1 is called Variable Length parameter and it can hold any number of argument values
(or) variable number of argument values and *param1 type is <class,'tuple'>

=>Rule:- The *param1 must always written at last part of Function Heading and it must be only one
(but not multiple)

=>Rule:- When we use Variable length and default parameters in function Heading, we use default
parameter as last and before we use variable length parameter and in function calls, we should not use
default parameter as Key word argument bcoz Variable number of values are treated as Posstional
Argument Value(s) .

================================================
5) Key Word Variables Length Parameters (or) arguments
================================================
=>When we have familiy of multiple function calls with Key Word Variable number of values /
arguments then with normal python programming, we must define mutiple function defintions. This
process leads to more development time.
=>To overcome this process, we must use the concept of Keyword Variable length Parameters .
=>To Implement, Keyword Variable length Parameters concept, we must define single Function
Definition and takes a formal Parameter preceded with a symbol called double astrisk ( ** param)
and the formal parameter with double astrisk symbol is called Keyword Variable length Parameters
and whose purpose is to hold / store any number of (Key,Value) coming from similar function calls
and whose type is <class, 'dict'>.
---------------------------------------------------------------------------------------------------
Syntax for function definition with Keyword Variables Length Parameters:
---------------------------------------------------------------------------------------------------
def functionname(list of formal params, **param) :
--------------------------------------------------
--------------------------------------------------

=>Here **param is called Keyword Variable Length parameter and it can hold any number of Key
word argument values (or) Keyword variable number of argument values and **param type is
<class,'dict'>

=>Rule:- The **param must always written at last part of Function Heading and it must be only one
(but not multiple)
---------------------------------------------------------------
Final Syntax for defining a Function
---------------------------------------------------------------
def funcname(PosFormal parms, *Varlenparams, default params, **kwdvarlenparams):
-------------------------------------------------
---------------------------------------------------

#Program for demonstrating Keyword Variable Length Arguments


#KwdVarLenArgsEx1.py--This Program will not execute as it is
def disp(a,b,c,d): #Function Def-1
print("-----------------------------------------------------")
print(a,b,c,d)
print("-----------------------------------------------------")

def disp(x,y,z): #Function Def-2


print("-----------------------------------------------------")
print(x,y,z)
print("-----------------------------------------------------")

def disp(K,L,M,N): #Function Def-3


print("-----------------------------------------------------")
print(K,L,M,N)
print("-----------------------------------------------------")

#main program
disp(c=30,d=40,a=10,b=20) # Function call-1
disp(x="HYD",y="BANG",z="MUM") # Function call-2
disp(K=100,L="ROSSUM",M="PYTHON",N=33.33) # Function call-3

#Program for demonstrating Keyword Variable Length Arguments


#KwdVarLenArgsEx2.py--This Program will execute
def disp(a,b,c,d): #Function Def-1
print("-----------------------------------------------------")
print(a,b,c,d)
print("-----------------------------------------------------")

disp(c=30,d=40,a=10,b=20) # Function call-1


#-------------------------------------------------------------------------------
def disp(x,y,z): #Function Def-2
print("-----------------------------------------------------")
print(x,y,z)
print("-----------------------------------------------------")

disp(x="HYD",y="BANG",z="MUM") # Function call-2


#-------------------------------------------------------------------------------------
def disp(K,L,M,N): #Function Def-3
print("-----------------------------------------------------")
print(K,L,M,N)
print("-----------------------------------------------------")

disp(K=100,L="ROSSUM",M="PYTHON",N=33.33) # Function call-3

#Program for demonstrating Keyword Variable Length Arguments


#PureKwdVarLenArgsEx1.py

def disp( ** k): # here **k is called variable Keyword Length args--whose type is dict
print("----------------------------------------")
print(k,type(k))
print("----------------------------------------")

#main program
disp(c=30,d=40,a=10,b=20) # Function call-1
disp(city1="HYD",city2="BANG",city3="MUM") # Function call-2
disp(id=100,name="ROSSUM",sub="PYTHON",marks=33.33) # Function call-3

#Program for demonstrating Keyword Variable Length Arguments


#PureKwdVarLenArgsEx2.py

def disp( ** k): # here **k is called variable Keyword Length args--whose type is dict
print("----------------------------------------")
for kv,vv in k.items():
print("\t{}-->{}".format(kv,vv))
print("----------------------------------------")

#main program
disp(c=30,d=40,a=10,b=20) # Function call-1
disp(city1="HYD",city2="BANG",city3="MUM") # Function call-2
disp(id=100,name="ROSSUM",sub="PYTHON",marks=33.33) # Function call-3
disp(sid=123, sname="Mahesh",hobby1="Eating",hobby2="Sleep",hobby3="Cahttin
#Program for demonstrating Keyword Variable Length Arguments
#PureKwdVarLenArgsEx3.py
def findtotalmarks(sno,sname,cls,**submarks):
print("-------------------------------------------------")
print("\tStudent Number:{}".format(sno))
print("\tStudent Name:{}".format(sname))
print("\tStudent Class:{}".format(cls))
print("-------------------------------------------------")
tm=0
print("\tSubject\t\tMarks")
print("-------------------------------------------------")
for sn,sm in submarks.items():
print(" \t{}\t\t{}".format(sn,sm))
tm=tm+sm
print("-------------------------------------------------")
print("\tTOTAL MARKS:{}".format(tm))
print("-------------------------------------------------")

#main program
findtotalmarks(100,"Rajesh","X",Tel=60,Hindi=70,English=67,Maths=60,Science=60,Social=75)
findtotalmarks(200,"Navenn","XII",Maths=73,Physics=58,Chemistry=60)
findtotalmarks(400,"Veersh","BE",OS=60,DBMS=75,CG=55,SET=62)
findtotalmarks(500,"Rossum","Reserch")

#Program for demonstrating Keyword Variable Length Arguments


#PureKwdVarLenArgsEx4.py
def findtotalmarks(sno,sname,cls,state="TS",**submarks):
print("-------------------------------------------------")
print("\tStudent Number:{}".format(sno))
print("\tStudent Name:{}".format(sname))
print("\tStudent Class:{}".format(cls))
print("\tStudent State:{}".format(state))
print("-------------------------------------------------")
tm=0
print("\tSubject\t\tMarks")
print("-------------------------------------------------")
for sn,sm in submarks.items():
print(" \t{}\t\t{}".format(sn,sm))
tm=tm+sm
print("-------------------------------------------------")
print("\tTOTAL MARKS:{}".format(tm))
print("-------------------------------------------------")

#main program
findtotalmarks(100,"Rajesh","X",Tel=60,Hindi=70,English=67,Maths=60,Science=60,Social=75)
findtotalmarks(200,"Navenn","XII",Maths=73,Physics=58,Chemistry=60)
findtotalmarks(400,"Veersh","BE",OS=60,DBMS=75,CG=55,SET=62,state="MUM")
findtotalmarks(500,"Rossum","Reserch",state="NL")
#Program for demonstrating Keyword Variable Length Arguments
#PureKwdVarLenArgsEx5.py
def findtotalmarks(sno,sname,cls,*vals,state="TS",**submarks):
print("================================")
print("Variable Length Values")
for val in vals:
print("\t\t{}".format(val))
print("================================")
print("-------------------------------------------------")
print("\tStudent Number:{}".format(sno))
print("\tStudent Name:{}".format(sname))
print("\tStudent Class:{}".format(cls))
print("\tStudent State:{}".format(state))
print("-------------------------------------------------")
tm=0
print("\tSubject\t\tMarks")
print("-------------------------------------------------")
for sn,sm in submarks.items():
print(" \t{}\t\t{}".format(sn,sm))
tm=tm+sm
print("-------------------------------------------------")
print("\tTOTAL MARKS:{}".format(tm))
print("-------------------------------------------------")

#main program
findtotalmarks(100,"Rajesh","X",1,2,3,4,5,Tel=60,Hindi=70,English=67,Maths=60,Science=60,Socia
l=75)
findtotalmarks(200,"Navenn","XII",10,20,30,40,Maths=73,Physics=58,Chemistry=60)
findtotalmarks(400,"Veersh","BE",100,200,OS=60,DBMS=75,CG=55,SET=62,state="MUM")
findtotalmarks(500,"Rossum","Reserch",-1,-2,-3,-4,-5,state="NL")
findtotalmarks(600,"KVR","Trainer")

DAY = 46

=============================================
Local variables and Global Variables
=============================================
Local Variables
-------------------
=>The Variables used inside of Function Body are called Local Variables.
=>The Purpose of Local Variables is that "To Store the Temporary results".
Syntax:
---------
def functionname(list of formal Params if any):
-------------------------------
var1=val1
var2=Val2
------------
var-n=val-n
---------------
=>here var1,var2..var-n are called Local Variables.
--------------------
Global Variables
--------------------
=>Global variables are those which are common values for different function calls.
=>In Other words, if the Value is common for all Different Function Calls then such type
of values must be taken as Global Variables.
=>To access the values of Global Variables then They Must be defined Before Function
Calls only otherwise we get NameError.

Syntax: var1=val1
var2=val2
-------------
var-n=val-n

def fun1():
-----------
-----------
def fun2():
-----------
-----------

def fun-n():
-----------
-----------

Here Var1, Var2..var-n are called Global variables and we can access those values inside of Fun1(),
fun2()....fun-n().

==================================================================
Examples:
============
#globalsfunex3.py
a=10
b=20
c=30
d=40
def operations():
obj=globals()
for gvn,gvv in obj.items():
print("\t{}---->{}".format(gvn,gvv))
print("="*50)
print("\nProgrammer-defined Global Variables")
print("="*50)
print("Val of a=", obj['a'])
print("Val of b=", obj['b'])
print("Val of c=", obj['c'])
print("Val of d=", obj['d'])
print("="*50)
print("\nProgrammer-defined Global Variables")
print("="*50)
print("Val of a=", obj.get('a'))
print("Val of b=", obj.get('b'))
print("Val of c=", obj.get('c'))
print("Val of d=", obj.get('d'))
print("="*50)
print("\nProgrammer-defined Global Variables")
print("="*50)
print("Val of a=", globals().get('a'))
print("Val of b=", globals().get('b'))
print("Val of c=", globals().get('c'))
print("Val of d=", globals().get('d'))
print("="*50)
print("\nProgrammer-defined Global Variables")
print("="*50)
print("Val of a=", globals()['a'])
print("Val of b=", globals()['b'])
print("Val of c=", globals()['c'])
print("Val of d=", globals()['d'])
print("="*50)
=================================================
#main program
operations()
==================================================
Examples:
-----------------------
#Program for demonstrating globals()
#globalsfunex2.py
a=10
b=20
c=30
d=40 # Here a,b,c,d are called Global Variables
def operation():
a=100
b=200
c=300
d=400 # Here a,b,c,d are called Local Variables
res=a+b+c+d+globals()['a']+globals().get('b')+globals()['c']+globals()['d']
print(res)

#main program
operation()

====================================X===================================
=.
#Program for demonstrating local and global variables
#GlobalLocalVarEx1.py
lang="PYTHON" # Global variable
def learnML():
sub1="ML"
print("To develop '{}' Programs, we Use '{}' Lang".format(sub1,lang))
#print(sub2) can't access bcoz sub2 is local in learnDL()

def learnDL():
sub2="DL"
print("To develop '{}' Programs, we Use '{}' Lang".format(sub2,lang))
#print(sub1) an't access bcoz sub1 is local in learnML()

#main program
learnML()
learnDL()

#Program for demonstrating local and global variables


#GlobalLocalVarEx2.py
def learnML():
sub1="ML"
print("To develop '{}' Programs, we Use '{}' Lang".format(sub1,lang))
#print(sub2) can't access bcoz sub2 is local in learnDL()

lang="PYTHON" # Global variable

def learnDL():
sub2="DL"
print("To develop '{}' Programs, we Use '{}' Lang".format(sub2,lang))
#print(sub1) an't access bcoz sub1 is local in learnML()

#main program
learnML()
learnDL()

#Program for demonstrating local and global variables


#GlobalLocalVarEx3.py
def learnML():
sub1="ML"
print("To develop '{}' Programs, we Use '{}' Lang".format(sub1,lang))
#print(sub2) can't access bcoz sub2 is local in learnDL()

def learnDL():
sub2="DL"
print("To develop '{}' Programs, we Use '{}' Lang".format(sub2,lang))
#print(sub1) an't access bcoz sub1 is local in learnML()

#main program
lang="PYTHON" # Global variable
learnML()
learnDL()

#Program for demonstrating local and global variables


#GlobalLocalVarEx4.py
def learnML():
sub1="ML"
print("To develop '{}' Programs, we Use '{}' Lang".format(sub1,lang))
#print(sub2) can't access bcoz sub2 is local in learnDL()

def learnDL():
sub2="DL"
print("To develop '{}' Programs, we Use '{}' Lang".format(sub2,lang))
#print(sub1) an't access bcoz sub1 is local in learnML()

#main program
#learnML()----here global variable lang can't be accessed in its body bcoz it was defined after its
function call
lang="PYTHON" # Global variable
learnDL()

======================================
global key word
======================================
=>When we want MODIFY the GLOBAL VARIABLE values in side of function defintion then
global variable names must be preceded with 'global' keyword otherwise we get
"UnboundLocalError: local variable names referenced before assignment"

Syntax:
-----------
var1=val1
var2=val2
var-n=val-n # var1,var2...var-n are called global variable names.
------------------
def fun1():
------------------------
global var1,var2...var-n
# Modify var1,var2....var-n
--------------------------
def fun2():
------------------------
global var1,var2...var-n
# Modify var1,var2....var-n
--------------------------

========================================================.

#Program for demonstrating global keyword


#GlobalKwdEx1.py
def incr1():
global a
a=a+1

def incr2():
global a
a=a*2
#main program
a=10 # global variable
print("Val of a in main program before incr1()=",a) # 10
incr1()
print("Val of a in main program after incr1()=",a) # 11
incr2()
print("Val of a in main program after incr2()=",a) # 22

#Program for demonstrating global keyword


#GlobalKwdEx2.py

def update1():
global a,b;
a=a+1
b=b+1

#main program
a=10
b=20 # Here a and b are called global variables
print("In main program before update1()-->a={} and b={}".format(a,b))
update1()
print("In main program before update1()-->a={} and b={}".format(a,b))

#Program for demonstrating global keyword


#GlobalKwdEx3.py
def update1():
#No Need to write global kwd bcoz we are updating global variables a and b values and Just
we are accessing
c=a+1
d=b+1
print("In Update1() c={} and d={}".format(c,d))

#main program
a=10
b=20 # Here a and b are called global variables
print("In main program before update1()-->a={} and b={}".format(a,b))
update1()
print("In main program before update1()-->a={} and b={}".format(a,b))

============================================
global and local variables and globals()
============================================
=>When we come acrosss same global Variable names and Local Variable Names in same function
definition then PVM gives preference for local variables but not for global variables.
=>In this context, to extract / retrieve the values of global variables names along with local variables,
we must use globals() and it returns an object of <class,'dict'> and this dict object stores all global
variable Names as Keys and global variable values as values of value.

=>Syntax:-
var1=val1
var2=val2
--------------
var-n=val-n # var1, var2...var-n are called global Variables
def functionname():
------------------------
var1=val11
var2=val22
-----------------
var-n=val-nn # var1, var2...var-n are called local Variables
# Extarct the global variables values
dictobj=globals()
------------------------
globalval1=dictobj['var1'] # or dictobj.get("var1") or globals()['var1'] or
global().get('var1')
globalval2=dictobj['var2'] # or dictobj.get("var2") or globals()['var2']
-----------------------------------------------------
-----------------------------------------------------
==================================================================
Examples:
============
#globalsfunex3.py
a=10
b=20
c=30
d=40
def operations():
obj=globals()
for gvn,gvv in obj.items():
print("\t{}---->{}".format(gvn,gvv))
print("="*50)
print("\nProgrammer-defined Global Variables")
print("="*50)
print("Val of a=", obj['a'])
print("Val of b=", obj['b'])
print("Val of c=", obj['c'])
print("Val of d=", obj['d'])
print("="*50)
print("\nProgrammer-defined Global Variables")
print("="*50)
print("Val of a=", obj.get('a'))
print("Val of b=", obj.get('b'))
print("Val of c=", obj.get('c'))
print("Val of d=", obj.get('d'))
print("="*50)
print("\nProgrammer-defined Global Variables")
print("="*50)
print("Val of a=", globals().get('a'))
print("Val of b=", globals().get('b'))
print("Val of c=", globals().get('c'))
print("Val of d=", globals().get('d'))
print("="*50)
print("\nProgrammer-defined Global Variables")
print("="*50)
print("Val of a=", globals()['a'])
print("Val of b=", globals()['b'])
print("Val of c=", globals()['c'])
print("Val of d=", globals()['d'])
print("="*50)
=================================================
#main program
operations()
==================================================
Examples:
-----------------------
#Program for demonstrating globals()
#globalsfunex2.py
a=10
b=20
c=30
d=40 # Here a,b,c,d are called Global Variables
def operation():
a=100
b=200
c=300
d=400 # Here a,b,c,d are called Local Variables
res=a+b+c+d+globals()['a']+globals().get('b')+globals()['c']+globals()['d']
print(res)

#main program
operation()

====================================X===================================
=
#program for demonstrating globals()
#GlobalsFunEx1.py
a=10
b=20
c=30
d=40 # here a,b,c, and d are called global variables
def operations():
x=100
y=200
z=300
k=400 # here x,y,z,k are called Local variables
res=x+y+z+k+a+b+c+d
print("Result=",res)
#main program
operations()

#program for demonstrating globals()


#GlobalsFunEx2.py
a=10
b=20
c=30
d=40 # here a,b,c, and d are called global variables
def operations():
a=100
b=200
c=300
d=400 # here a,b,c,d are called Local variables
res=a+b+c+d+globals()['a']+globals()['b']+globals()['c']+globals()['d']
print("Result=",res)

#main program
operations()

#program for demonstrating globals()


#GlobalsFunEx3.py
a=10
b=20
# here a,b are called global variables
def operations():
dictobj=globals()
print("Both Programmer and Implicit Global variables:")
for gvn,gvv in dictobj.items():
print("\t{}-->{}".format(gvn,gvv))
print("-----------------------------------------------------------------------")
print("Programmer-Defined Global variables-way1")
print("Val of a:", dictobj['a'])
print("Val of b:", dictobj['b'])
print("-----------------------------------------------------------------------")
print("Programmer-Defined Global variables-way2")
print("Val of a:", dictobj.get('a'))
print("Val of b:", dictobj.get('b'))
print("-----------------------------------------------------------------------")
print("Programmer-Defined Global variables-way3")
print("Val of a:", globals().get('a'))
print("Val of b:", globals().get('b'))
print("-----------------------------------------------------------------------")
print("Programmer-Defined Global variables-way4")
print("Val of a:", globals()['a'])
print("Val of b:", globals()['b'])
print("-----------------------------------------------------------------------")

#main program
operations()
#ReadValuesEx1.py
lst=[] # empty list
n=int(input("Enter How many value u want in list:"))
if(n<=0):
print("{} invalid input".format(n))
else:
for i in range(1,n+1):
val=float(input("Enter {} Value:".format(i)))
lst.append(val)
else:
print("List of Values:{}".format(lst))

DAY – 47

=================================================
Anonymous OR Lambda Functions (Most Imp )
==================================================
=>Anonymous Functions are those which does not contain any name explicitly.
=>The Purpose of Anonymous Functions is that " To Perform Instant Operations ".
=>Instant Operations are those which are used at that Point of time only and No Longer Interested to
use
in other part of the applications / project".
=>To Define Anonymous Functions, we use a key word called lambda and hence Anonymous
Functions
are also called Lambda Functions.
=>Anonymous Functions contains single executable statement(but not multiple statements)
=>Anonymous Functions automatically / Implcitly returns the value (No Need to use return
statement).
--------------------------------------------------------------------------------------------------------------------------
----------------
Syntax for Defining Anonymous Functions:
--------------------------------------------------------------------------------------------------------------------------
----------------
varname=lambda params-list : Statement
----------------------
Explanation
----------------------
=>varname reprseents an object of type <class,'function'>. Since varname acts as an object of
function
class and It can be used as Function call.
=>lambda is a keyword used for defining Anonymous Function.
=>params-list represents list of Variable Names used for storing the inputs coming from Function
call
=>statement represents Single Executable Statement and it gets executed and whose result returned
automatically by the pvm ( No Need to to use Return statements).
--------------------------------------------------------------------------------------------------------------------------
----------------
Question: Defining a Function for adding of Two Numbers
--------------------------------------------------------------------------------------------------------------------------
----------------
By using Normal Functions By using Anonymous Functions
--------------------------------------------------------- ---------------------------------------------------
-----
def sumop(a,b): addop=lambda a,b : a+b
c=a+b
return c

#main program #main program

res=sumop(10,20) res=addop(100,200)
print("sum=",res) print("sum=",res)

#Program for addition of two numbers by using Normal and anonymous Functions
#AnonymousFunEx1.py
def sumop(a,b): # Normal Function
c=a+b
return c

addop=lambda k,v:k+v # anonymous Functions

#main program
print("By using Normal Function:")
print("Types of sumop=",type(sumop)) # <class,'function'>
print("Enter Two Values")
res=sumop(float(input()),float(input()))
print("sum=",res)
print("------------------------------------------------------------------")
print("By using AnonymousFunction:")
print("Types of addop=",type(addop)) # <class,'function'>
print("Enter Two Values")
res1=addop(float(input()),float(input()))
print("sum=",res1)

#Program for finding Biggest Two Numbers by using anonymous Functions


#AnonymousFunEx2.py
big=lambda a,b: a if a>b else b if b>a else "Both Values Equal"

#main program
print("Enter Two Values:")
a,b=float(input()),float(input())
bv=big(a,b)
print("big({},{})={}".format(a,b,bv))

write a python program which will except two numerical integer value and find the biggest among
them by using anonyous function

#Program for finding Wthether the word is vowel or not


#AnonymousFunEx3.py
vowel=lambda word: "Vowel Word" if 'a' in word.lower() or 'e' in word.lower() or 'i' in word.lower()
or 'o' in word.lower() or 'u' in word.lower() else "NOT Vowel Word"

#main progra
word=input("Enter word:")
res=vowel(word)
print("{} is {}".format(word,res))

write a python program which will except a word and decide whether vowel word or not

write a python program which will except a word decide whether it is palindrom or not by using
anaonyums function

#ReadValuesEx1.py
lst=[] # empty list
n=int(input("Enter How many value u want in list:"))
if(n<=0):
print("{} invalid input".format(n))
else:
for i in range(1,n+1):
val=float(input("Enter {} Value:".format(i)))
lst.append(val)
else:
print("List of Values:{}".format(lst))

list comprehension
set ''
dict ''

syntax:\\

varname =[Expr1 for name ]

#listcomphensionex1.py
lst=[3,6,12,7,19,25]
sqlist=[ val**2 for val in lst ]
print("Type of sqlist=",type(sqlist))
print("Given List=",lst)
print("Square List=",sqlist)

#listcomphensionex2.py
lst=[3,6,-12,7,-19,25,-56,23,-78,89,0,12]
pslist=[ val for val in lst if val>0]
nglist=[ val for val in lst if val<0]
print("Given List=",lst)
print("List of +ve Elements=",pslist)
print("List of -ve Elements=",nglist)
#dictcomphensionex1.py
lst=[3,6,12,7,19,25]
sqlist=dict([ (val,val**2) for val in lst ])
print("Type of sqlist=",type(sqlist))
for n,s in sqlist.items():
print("\t{}-->{}".format(n,s))

#setcomphensionex1.py
lst=[3,6,12,7,19,25]
sqlist={ val**2 for val in lst }
print("Type of sqlist=",type(sqlist))
print("Given List=",lst)
print("Square List=",sqlist)

#tuplecomphensionex1.py
lst=[3,6,12,7,19,25]
sqlist=( val**2 for val in lst )
print("Type of sqlist=",type(sqlist)) # <class 'generator'>
#Type casr generator object into tuple type
tpl=tuple(sqlist)
print("Type of tpl=",type(tpl))
print("Given List=",lst)
print("Square List=",tpl)

#non-comphension.py
lst=[3,6,12,7,19,25]
sqlist=[]
for val in lst:
sqlist.append(val**2)
else:
print("Given List=",lst)
print("Square List=",sqlist)

#ReadValuesComprehenEx1.py
print("Enter List of values separated by space:")
lst=[ int(val) for val in input().split()]
print("Given List=",lst)

#ReadValuesComprehenEx2.py
print("Enter List of Values separated by comma:")
lst=[ val for val in input().split(",")]
print("Given List:{}".format(lst))
#ReadValuesComprehenEx2py
print("Enter List of Values separated by comma:")
lst=[ str(val) for val in input().split(",")]
print("Given List:{}".format(lst))

day --- 48
==========================================================
Special Functions in Python
==========================================================
=>In Python Programming, we have 3 types of Special Functions. They are

1. filter()
2. map()
3. reduce()
--------------------------------------------------------------------------------------------------------------------------
---------------------.

==================================
1) filter()
==================================
=>filter() is used for "Filtering out some elements from list of elements by applying to
function".
=>Syntax:- varname=filter(FunctionName, Iterable_object)

---------------------
Explanation:
---------------------
=>here 'varname' is an object of type <class,'filter'> and we can convert into any iteratable object by
using type casting functions.
=>"FunctionName" represents either Normal function or anonymous functions.
=>"Iterable_object" represents Sequence, List, set and dict types.
=>The execution process of filter() is that " Each Value of Iterable object sends to Function Name. If
the function return True then the element will be filtered. if the Function returns False then that
element will be neglected/not filtered ". This process will be continued until all elements of Iterable
object completed.
--------------------------------------------------------------------------------------------------.

#Program for demonstarting filter()


#FilterEx1.py
def posvalue(n):
if(n>0):
return True
else:
return False

#main program
lst=[10,23,-45,67,-68,-78,12,-34,28]
kvr=filter(posvalue,lst)
print("Type of kvr=",type(kvr)) # <class 'filter'>
#convert filter object into list type, tuple,set type
pslist=list(kvr)
print("Given List=",lst)
print("Possitive Elements List=",pslist)

#Program for demonstarting filter()


#FilterEx2.py
def posvalue(n):
if(n>0):
return True
else:
return False

#main program
lst=[10,23,-45,67,-68,-78,12,-34,28]
pslist=list(filter(posvalue,lst))
print("Given List=",lst)
print("Possitive Elements List=",pslist)

#Program for demonstarting filter()


#FilterEx3.py
def posvalue(n): # Normal Function
if(n>0):
return True
else:
return False

#main program
print("Enter List of Values Separated by Space:")
lst=[int(val) for val in input().split()]
pslist=tuple(filter(posvalue,lst))
print("Given List=",lst)
print("Possitive Elements List=",pslist)

#Program for demonstarting filter()


#FilterEx4.py

posvalue=lambda n: n>0 # Anonymous Function

#main program
print("Enter List of Values Separated by Space:")
lst=[int(val) for val in input().split()]
pslist=tuple(filter(posvalue,lst))
print("Given List=",lst)
print("Possitive Elements List=",pslist)

#Program for demonstarting filter()


#FilterEx5.py
print("Enter List of Values Separated by Space:")
lst=[int(val) for val in input().split()]
pslist=tuple(filter(lambda n:n>0 , lst))
nglist=set(filter(lambda n:n<0 , lst))
print("---------------------------------------------------")
print("Given List=",lst)
print("Possitive Elements List=",pslist)
print("Negative Elements=",nglist)
print("---------------------------------------------------")

#Program for demonstarting filter()


#FilterEx6.py
print("Enter List of Values Separated by Space:")
lst=[int(val) for val in input().split()]
evenlist=list(filter(lambda n: n%2==0,lst))
oddlist=list(filter(lambda n:n%2!=0,lst))
print("----------------------------------------------")
print("Given List:{}".format(lst))
print("Even List:{}".format(evenlist))
print("Odd List:{}".format(oddlist))
print("----------------------------------------------")

#Program for demonstarting filter()


#FilterEx7.py
line=input("Enter a Line of Text:")
print("-----------------------------------------------")
print("Given Line:{}".format(line))
print("-----------------------------------------------")
words=line.split()
print("Given Words=",words)
print("-----------------------------------------------")
words3len=list(filter(lambda word:len(word)>=3,words))
print("Words with 3 in Length={}".format(words3len))

write a python program which will except line of text and filters those words which does not contains
vowel words .

====================================
2) map()
====================================
=>map() is used for obtaining new Iterable object from existing iterable object by applying old
iterable elements to the function.
=>In otherwords, map() is used for obtaining new list of elements from existing list of elements by
applying old list elements to the function.

=>Syntax:- varname=map(FunctionName,Iterable_object)

=>here 'varname' is an object of type <class,map'> and we can convert into any iteratable object by
using type casting functions.
=>"FunctionName" represents either Normal function or anonymous functions.
=>"Iterable_object" represents Sequence, List, set and dict types.
=>The execution process of map() is that " map() sends every element of iterable object to the
specified function, process it and returns the modified value (result) and new list of elements will be
obtained". This process will be continued until all elements of Iterable_object completed.
--------------------------------------------------------------------------------------------------------------------------
-------

#Program for demonstrating map()


#MapEx2.py
def hike(sal):
return(sal+sal*(50/100))

#main program
oldsal=[10,15,5,20,30,16]
newsal=list(map(hike,oldsal))
print("---------------------------------------------")
print("Old Salary List:{}".format(oldsal))
print("New Salary List:{}".format(newsal))
print("---------------------------------------------")

#Program for demonstrating map()


#MapEx3.py

hike=lambda sal:sal+sal*(50/100) # Anonymous Function


#main program
print("Enter list of salaries of employees:")
oldsallist=[int(val) for val in input().split()]
oldsal=list(filter(lambda sal:sal>0,oldsallist))
newsal=list(map(hike,oldsal))
print("---------------------------------------------")
print("Old Salary List:{}".format(oldsal))
print("New Salary List:{}".format(newsal))
print("---------------------------------------------")

#Program for demonstrating map()


#MapEx1.py
def hike(sal):
return(sal+sal*(50/100))

#main program
oldsal=[10,15,5,20,30,16]
obj=map(hike,oldsal)
print("Type of obj=",type(obj)) # <class 'map'>
print("---------------------------------------------")
#convert map object into list object
newsal=list(obj)
print("Old Salary List:{}".format(oldsal))
print("New Salary List:{}".format(newsal))
print("---------------------------------------------")

#Program for demonstrating map()


#MapEx3.py

hike=lambda sal:sal+sal*(50/100) # Anonymous Function


#main program
print("Enter list of salaries of employees:")
oldsal=[int(val) for val in input().split() if int(val)>0 ]
newsal=list(map(hike,oldsal))
print("---------------------------------------------")
print("Old Salary List:{}".format(oldsal))
print("New Salary List:{}".format(newsal))
print("---------------------------------------------")

#Program for demonstrating map()


#MapEx5.py
print("Enter List of Words separated by space:")
words=[word for word in input().split()]
print("-----------------------------------------------------------")
print("Given Words=",words)
print("-----------------------------------------------------------")
rwords=list(map(lambda word:word[::-1],words))
print("Reversed Words=",rwords)

#Program for demonstrating map()


#MapEx6.py
line=input("Enter Line of text:")
words=line.split()
print("-----------------------------------------------------------")
print("Given Words=",words)
print("-----------------------------------------------------------")
rwords=list(map(lambda word:word[::-1],words))
print("Reversed Words=",rwords)

#Program for demonstrating map()


#MapEx7.py

def listsum(x,y):
return (x+y)

#main program
print("Enter List of values for First List:")
lst1=[int(val) for val in input().split()]
print("Enter List of values for Second List:")
lst2=[int(val) for val in input().split()]
lst3=list(map(listsum,lst1,lst2))
print("{}+{}={}".format(lst1,lst2,lst3))

#Program for demonstrating map()


#MapEx8.py

def listsum(x,y):
return (x+y)
#main program
print("Enter List of values for First List:")
lst1=[int(val) for val in input().split()]
print("Enter List of values for Second List:")
lst2=[int(val) for val in input().split()]
lst3=list(map(listsum,lst1,lst2))
print("--------------------------------------")
print("\tList1 + List2 = Lilst")
print("--------------------------------------")
for v1,v2,v3 in zip(lst1,lst2,lst3):
print("\t{} {} {}".format(v1,v2,v3))
print("--------------------------------------")

day --- 49

================================
reduce()
================================
=>reduce() is used for obtaining a single element / result from given iterable object by applying to a
function.
=>Syntax:-
varname=reduce(function-name,iterable-object)
=>here varname is an object of int, float,bool,complex,str only
=>The reduce() belongs to a pre-defined module called" functools".
---------------------------------------
Internal Flow of reduce()
---------------------------------------
step-1:- Initially, reduce() selects First Two values of Iterable object and place them in First
var and Second var .
step-2:- The function-name(lambda or normal function) utilizes the values of First var and
Second var and applied to the specified logic and obtains the result.
Step-3:- reduce () places the result of function-name in First variable and reduce()
selects the succeeding element of Iterable object and places in second variable.
Step-4: Repeat Step-2 and Step-3 until all elements completed in
Iterable object and returns the result of First Variable.
--------------------------------------------------------------------------------------------------------------------------
----.

write a python program which will except list of values and find their sum by using reduced function

write a python program which will except list of values frim keyboard find their product

which will find highest and lowest elements max and min elements from list of lements

write a python program which will except list of words seprated by comma and form a sentan
#ReduceFunEx1.py
import functools
def sumop(x,y):
return (x+y)

#main program
print("Enter List of Values separated by space: ")
lst=[int(val) for val in input().split()]
print("--------------------------------")
print("Given List={}".format(lst))
res=functools.reduce(sumop,lst)
print("sum({})={}".format(lst,res))
print("--------------------------------")

#ReduceFunEx2.py
import functools
print("Enter List of Values separated by space: ")
lst=[int(val) for val in input().split()]
print("--------------------------------")
print("Given List={}".format(lst))
res=functools.reduce(lambda x,y:x+y,lst)
print("sum({})={}".format(lst,res))
print("--------------------------------")

#ReduceFunEx3.py
import functools
print("Enter List of Values separated by space: ")
lst=[int(val) for val in input().split()] #[10,30,20,40]
print("--------------------------------")
bigv=functools.reduce(lambda x,y: x if x>y else y, lst)
smallv=functools.reduce(lambda x,y: x if x<y else y,lst)
print("big({})={}".format(lst,bigv))
print("small({})={}".format(lst,smallv))

#ReduceFunEx4.py
import functools
print("Enter List of words separated by comma: ")
lst=[word for word in input().split(",")]
print("--------------------------------")
print("Given Words={}".format(lst))
print("--------------------------------")
line=functools.reduce(lambda a,b:a+" "+b,lst)
print("Line:{}".format(line))
print("--------------------------------")

sum of positive or negative seprately


#FilterReduceFunEx1.py
import functools
print("Enter List of Values separated by Space: ")
lst=[int(val) for val in input().split()]
print("--------------------------------")
print("Given Values={}".format(lst))
print("--------------------------------")
#Filter +Ve values
poslist=list(filter(lambda n:n>0,lst))
#Filter -Ve values
neglist=list(filter(lambda n:n<0,lst))
print("Given Possitive List={}".format(poslist))
print("Given Negative List={}".format(neglist))
print("--------------------------------")
#Find sum of Possitive Elements List
pslistsum=functools.reduce(lambda x,y: x+y,poslist)
nglistsum=functools.reduce(lambda x,y: x+y,neglist)
print("PossitiveSum({})={}".format(poslist,pslistsum))
print("NegativeSum({})={}".format(neglist,nglistsum))
print("--------------------------------")

write a python program which will except list of employees who salery range from 0 to 1000 give
10% hike to those employees who salery ranges from 0 to 5000

give 20 % hike those employees who salery ranges from 5pi 1 to 1000

find the total salery of those emplyees whose salery ranges from 0 to 5000 hun --- redu

find the total salery of those employes who salery ranges from pi not 1 to thousand

find the total salery of all the employee

#FilterMapReduceEx.py
import functools,time
print("Enter List of Employee Salaries Ranges from 0 to 1000:")
sallist=[int(sal) for sal in input().split() if 0<=int(sal)<=1000 ]
print("----------------------------------------------------------")
print("Original Sal List:{}".format(sallist))
print("----------------------------------------------------------")
time.sleep(5)
sal0_500=list(filter(lambda sal:0<=sal<=500, sallist))
sal501_1000=list(filter(lambda sal:501<=sal<=1000, sallist))
print("Sal List between 0 to 500:{}".format(sal0_500))
print("Sal List between 501 to 1000:{}".format(sal501_1000))
print("----------------------------------------------------------")
hikesal0_500=list(map(lambda sal: sal+sal*(10/100),sal0_500))
hikesal501_1000=list(map(lambda sal: sal+sal*(20/100),sal501_1000))
#Find sum of Sals for 0--500
totsal0_500=functools.reduce(lambda sal1,sal2:sal1+sal2,hikesal0_500)
#Find sum of Sals for 501--1000
totsal501_1000=functools.reduce(lambda sal1,sal2:sal1+sal2,hikesal501_1000)
time.sleep(5)
print("----------------------------------------------------------")
print("Old Sal 0-500\tHike 0-500")
print("----------------------------------------------------------")
for osl,nsl in zip(sal0_500,hikesal0_500):
print("\t{}\t{}".format(osl,nsl))
print("----------------------------------------------------------")
print("TOTAL SALARY FOR 0-500 HIKE:{}".format(totsal0_500))
time.sleep(5)
print("Old Sal 501-1000\tHike 501-1000")
print("----------------------------------------------------------")
for osl,nsl in zip(sal501_1000,hikesal501_1000):
print("\t{}\t{}".format(osl,nsl))
print("----------------------------------------------------------")
print("TOTAL SALARY FOR 501-1000 HIKE:{}".format(totsal501_1000))
print("="*60)
time.sleep(5)
print("TOTAL SALARY PAID THE COMPANY TO ALL
EMPLOYEES={}".format(totsal0_500+totsal501_1000))
print("="*60).

Day --- 50

=================================================
Modules in Python--2 days
=================================================
Index
----------
=>Purpose of Modules
=>Definition of Module
=>Types of Modules
a) Pre-Defined Modules
b) Programer/ User / Custome Defined Modules
=>Steps for Developing Programer Defined Modules
=>Number of Approaches to Re-Use Modules
a) By Using Import Statement
b) By using from..import statement
=>Programming Examples
------------------------------------------------------------------------------------------------------------
=>Re-Loading modules
=>imp / importlib module
=>Programming Example
=>Use Cases

#MathsInfo.py---File Name and acts as Module name


PI=3.14
E=2.71 # here PI and E are called Global variables

print(pi,E)
#SE1.py
import MathsInfo
#Here SE1 is trying to Re-use the global Variables of one program in another program
print("val of PI=",MathsInfo.PI)
print("val of E=",MathsInfo.E)

#SE2.py
import aop
aop.sumop(10,20)
aop.subop(10,20)
aop.mulop(10,20)

#icici.py--File Name and Module name


bname="ICICI"
addr="HYD" # here bname and addr are called Global Variables
def simpleint(): # Function definition
p=float(input("Enter Principle Amount:"))
t=float(input('Enter Time:'))
r=float(input("Enter rate of interest:"))
#cal si and totamt to pay
si=(p*t*r)/100
totamt=p+si
print("*"*50)
print("Simple Interest Calculations")
print("*"*50)
print("\tPrinciple Amount:{}".format(p))
print("\tTime:{}".format(t))
print("\tRate of Interest:{}".format(r))
print("\tSimple Interest:{}".format(si))
print("\tTOTAL AMOUNT TO PAY:%0.2f" %totamt)
print("*"*50)

#SE3.py
import icici
print("Bank Name:{}".format(icici.bname))
print("Bank Addresss:{}".format(icici.addr))
icici.simpleint()

====================================================
Modules in Python
====================================================
=>We know that Functions are used for "Performing Certain Operations and Provides Code Re-
Usability
within the same Program but not able to provide Code Re-Usability across the programs.".
=>The Purpose of Modules Concept is that "To Re-use the functions, global variables and Class
Names"
from One Program to another Program provided Both The Programs present in Same Folder.
------------------------------------------
=>Definition of Module
------------------------------------------
A Module is a collection of Functions, Global Variable Names and Class Names.
------------------------------------------------------
Types of Modules
-------------------------------------------------------
=>In Python Programming, we have Two Types of Modules. They are
1. Pre-Defined Modules
2. Programmer OR User OR Custom Defined Module
-------------------------------------------------------------
1. Pre-Defined Modules
-------------------------------------------------------------
=>These Moudles are already defined by Python Lang Developers and Available in Python Software
and
Used all Python Lang Programmers and for dealing with Universal Requirements.
Examples: functools,sys,calendar,re,pickle,threading,csv..etc
=>Out-of Many Pre-defined Modules, By default One of the pre-defined module called "builtins"
imported to all python programs and It is called Default imported python Module.
--------------------------------------------------------------------------------------------------------------------------
-----------------------
2. Programmer OR User OR Custom Defined Module
-------------------------------------------------------------
=>These Moudles are developed by Python Programmers and avilable in Python Project and Used by
Other Members of Same Project for dealing with Common Requirements.
Examples: aop,MathsInfo,icici

=================================================
Development of Programmer-Defined Module
=================================================
=>To develop Programmer-Defined Modules, we must use the following steps

Step-1 : Define Variables (Global variables)


Step-2: Define Functions
Step-3: Define Classes

=>After developing step-1, step-2 and step-3 , we must save on some file name with an extension .py
(FileName.py) and it is treated as module name.
=>Hence Every Python File is treated as Module Name.
=>When a file name treated as a module name , internally Python execution environment creates a
folder automatically on the name of __pycache__ and it contains module name on the name of
"filename.cpython-311.pyc ".
-------------------
Examples:
-------------------
__pycache__ <-----Folder Name
-------------------------------------------
aop.cpathon-311.pyc <-------------------Module Name
mathsinfo.cpython-311.pyc<--------------Module Name
icici.cpython-311.pyc<----------------------Module Name
----------------------------------------------

#ImportSyntax-1.py
import icici
import MathsInfo
import aop
print("Bank Name:{}".format(icici.bname))
print("Bank Addresss:{}".format(icici.addr))
icici.simpleint()
print("-------------------------------------------")
print("val of PI=",MathsInfo.PI)
print("val of E=",MathsInfo.E)
print("-------------------------------------------")
aop.sumop(100,200)
print("-------------------------------------------")

#ImportSyntax-2.py
import icici,MathsInfo,aop
print("Bank Name:{}".format(icici.bname))
print("Bank Addresss:{}".format(icici.addr))
icici.simpleint()
print("-------------------------------------------")
print("val of PI=",MathsInfo.PI)
print("val of E=",MathsInfo.E)
print("-------------------------------------------")
aop.sumop(100,200)
print("--------------------------------------

#ImportSyntax-3.py
import icici as i
import MathsInfo as m
import aop as a
print("Bank Name:{}".format(i.bname))
print("Bank Addresss:{}".format(i.addr))
i.simpleint()
print("-------------------------------------------")
print("val of PI=",m.PI)
print("val of E=",m.E)
print("-------------------------------------------")
a.sumop(100,200)
print("------------------------------

#ImportSyntax-4.py
import icici as i,MathsInfo as m,aop as a
print("Bank Name:{}".format(i.bname))
print("Bank Addresss:{}".format(i.addr))
i.simpleint()
print("-------------------------------------------")
print("val of PI=",m.PI)
print("val of E=",m.E)
print("-------------------------------------------")
a.mulop(100,200)
print("-------------------------------------------")
===============================================
Number of approaches to re-use Modules
===============================================
=>We know that A Module is a collection of variables, Functions and Classes.
=>To re-use the features(Variable Names, Function Names and Class Names ) of module, we have 2
approaches.They are
1) By using import statement
2) By using from.... import statement.
---------------------------------------------------------------------------------------
1) By using import statement:
---------------------------------------------------------------------------------------
=>'import' is a keyword
=>The purpose of import statement is that "To refer or access the variable names, function names and
class names in current program"
=>we can use import statement in 4 ways.
-------------------
=>Syntax-1: import module name
-------------------
=>This syntax imports single module
----------------
Example: import icici
import aop
import mathsinfo
--------------------------------------------------------------------
=>Syntax-2: import module name1, module name2....Module name-n
-------------------
=>This syntax imports multiple modules
----------------
Example: import icici , aop, mathsinfo
--------------------------------------------------------------------------------------------------------------------------
--
=>Syntax-3: import module name as alias name
-------------------
=>This syntax imports single module and aliased with another unique names
----------------
Example: import icici as i
import aop as a
import mathsinfo as m
--------------------------------------------------------------------------------------------------------------------------
--
=>Syntax-4: import module name1 as alias name, module name2 as alias
name......module name-n as alias name
-------------------
=>This syntax imports multiple modules and aliased with another unique names
----------------
Example: import icici as i, aop as a , mathsinfo as m

=>Hence after importing module name(s) by using "import statement", all the variable names,
Function names and class names must access variable names, Function names and class names w.r.t
Module Names or alias names.
Module Name.Variable Name
Module Name.Function Name
Module Name.Class Name
(OR)
Alias Name.Variable Name
Alias Name.Function Name
Alias Name.Class Name

========================================================================
====
2) By using from.... import statement.
=======================================
=>Here "from" "import" are the key words
=>The purpose of from.... import statement is that " To refer or access the variable names, function
names and class names in current program directly without writing module name as alias name of
Module name."
=> we can use from.... import statement in 3 ways.
-------------------
Syntax-1: from module name import Variable Names,Function Names, Class Names
------------------
=>This syntax imports the Variable Names,Function Names, Class Names of a module.

Example: from calendar import month


from aop import addop,subop
from mathinfo import pi,e
from icici import bname,addr, simpleint

-----------------------------------------------------------------------------------------------------------
Syntax-2: from module name import Variable Names as alias name,Function Names as
alias name , Class Names as alias names.
-----------------------------------------------------------------------------------
=>This syntax imports the Variable Names,Function Names, Class Names of a module with Unique
alias Names

Example: from calendar import month as m


from aop import addop as a,subop as s, mulop as m
from mathinfo import pi as p ,e as k
from icici import bname as b,addr as n , simpleint as si
---------------------------------------------------------------------------------------------------------------------
Syntax-3: from module name import *
---------------
=>This syntax imports ALL Variable Names,Function Names, Class Names of a module.
=>This syntax is not recommmended to use bcoz it imports required Features of Module and also
import un-interrested features also imported and leads more main memory space.

Example: from calendar import *


from aop import *
from mathsinfo import *

=>Hence after importing all the variable names, Function names and class names by using
"from ....import statement" , we must access variable names, Function names and class names
Directly without using Module Names or alias names.

Variable Name
Function Name
Class Name

=>Hence with "import statement" we can give alias name for module names only but not for
Variables Names, Function Names and Class Names. Where as with "from ... import statement " we
can give alias names for Variables Names, Function Names and Class Names but not for Module
Name.

#FromImportSyntax-1.py
from icici import bname,addr,simpleint
from MathsInfo import PI,E
from aop import sumop,subop
print("Bank Name:{}".format(bname))
print("Bank Addresss:{}".format(addr))
simpleint()
print("-------------------------------------------")
print("val of PI=",PI)
print("val of E=",E)
print("-------------------------------------------")
sumop(100,200)
subop(10,20)
print("-------------------------------------------")

#FromImportSyntax-2.py
from icici import bname as b ,addr as a ,simpleint as si
from MathsInfo import PI as p,E
from aop import sumop as ap,subop as sp
print("Bank Name:{}".format(b))
print("Bank Addresss:{}".format(a))
si()
print("-------------------------------------------")
print("val of PI=",p)
print("val of E=",E)
print("-------------------------------------------")
ap(100,200)
sp(10,20)
print("-------------------------------------------")

#FromImportSyntax-3.py
from icici import *
from MathsInfo import *
from aop import *
print("Bank Name:{}".format(bname))
print("Bank Addresss:{}".format(addr))
simpleint()
print("-------------------------------------------")
print("val of PI=",PI)
print("val of E=",E)
print("-------------------------------------------")
sumop(100,200)
mulop(10,20)
print("-------------------------------------------")

which will gernate multiplaction table by using table

#MulTable.py--File Name and Module name


def table(n):
if(n<=0):
print("{} is invalid input".format(n))
else:
print("Mul Table for :{}".format(n))
for i in range(1,11):
print("\t{} x {}={}".format(n,i,n*i))

#MulTableDemo.py
from MulTable import table
table(int(input("Enter a number for generating mul table:")))

day – 51

write a python program which will except a numerical integer value and decide whether is prime or
not by using modules

#Prime.py----File Name and Module Name


def decideprime(n):
if(n<=1):
print("{} is invalid".format(n))
else:
res="PRIME"
for i in range(2,n):
if(n%i==0):
res="NOT PRIME"
break
if(res=="PRIME"):
print("{} is {}".format(n,res))
else:
print("{} is {}".format(n,res))

#PrimeDemo.py
from Prime import decideprime
decideprime(int(input("Enter any number to decide prime or not:")))

==========================================
realoding a modules in Python
==========================================
=>To reaload a module in python , we use a pre-defined function called reload(), which is present in
imp module and it was deprecated in favour of importlib module.
=>Syntax:- imp.reload(module name)
(OR)
importlib.reload(module name) ----->recommended
----------------------------------
=>Purpose / Situation:
-----------------------------------
=>reaload() reloads a previously imported module.
=>if we have edited the module source file by using an external editor and we want to use the
changed values/ updated values / new version of previously loaded module then we use reload().
===================================X====================================
==
#shares.py---file and treated as module name
def sharesinfo():
d={"Tech":19,"Pharma":11,"Auto":1,"Finance":00}
return d

#main program
#sharesdemo.py
import shares
import time
import importlib
def disp(d):
print("-"*50)
print("\tShare Name\tValue")
print("-"*50)
for sn,sv in d.items():
print("\t{}\t\t:{}".format(sn,sv))
else:
print("-"*50)
#main program
d=shares.sharesinfo()
disp(d)
time.sleep(15)
importlib.reload(shares) # relodaing previously imported module
d=shares.sharesinfo() # obtaining changed / new values of previously imported module
disp(d)

#SharesDemo.py
import Shares,time,importlib
def dispshares(d):
print("-------------------------------------------")
print("\tShareName\tShareValue")
print("-------------------------------------------")
for sn,sv in d.items():
print("\t{}\t\t{}".format(sn,sv))
print("-------------------------------------------")

#main program
d=Shares.sharesinfo()
dispshares(d)
print("I am going to Sleep for 20 seconds")
time.sleep(20)
print("I am coming out of Sleep ")
#reload the module
importlib.reload(Shares)
d=Shares.sharesinfo()
dispshares(d)
print("I am going to Sleep for 20 seconds")
time.sleep(20)
print("I am coming out of Sleep ")
#reload the module
importlib.reload(Shares)
d=Shares.sharesinfo()
dispshares(d)

#Shares.py---File Name and Module Name


def sharesinfo():
d={"IT":5,"Fin":4,"Auto":3,"Pharma":2}
return d

#SharesDemo.py
import Shares,time,importlib
def dispshares(d):
print("-------------------------------------------")
print("\tShareName\tShareValue")
print("-------------------------------------------")
for sn,sv in d.items():
print("\t{}\t\t{}".format(sn,sv))
print("-------------------------------------------")

#main program
d=Shares.sharesinfo()
dispshares(d)
print("I am going to Sleep for 20 seconds")
time.sleep(20)
print("I am coming out of Sleep ")
#reload the module
importlib.reload(Shares)
d=Shares.sharesinfo()
dispshares(d)
print("I am going to Sleep for 20 seconds")
time.sleep(20)
print("I am coming out of Sleep ")
#reload the module
importlib.reload(Shares)
d=Shares.sharesinfo()
dispshares(d)

write a python program which will implement the following by using module ..

Case-1
=================================================
Arithemtic Operations
=================================================
1. Addition
2. Substraction
3. Multiplications
4. Normal Division
5. Floor Division
6. Modulo Division
7. Expoentiation
8. Exit
================================================
File System
------------------
1. AopMenu.py------File Name and Module Name
2. AopImplementations.py---File Name and Module Name
3. AopDemo.py-------Main Program
------------------------------------------------------------------------------------------------------
#aop.py--File Name and acts as Module name
def sumop(a,b):
print("sum({},{})={}".format(a,b,a+b))

def subop(a,b):
print("sub({},{})={}".format(a,b,a-b))

def mulop(a,b):
print("mul({},{})={}".format(a,b,a*b))

#AopDemo.py
from AopMenu import menu
from AopImplementations import *
while(True):
menu()
ch=int(input("Enter Ur Choice:"))
match(ch):
case 1:addop()
case 2:subop()
case 3:mulop()
case 4:divop()
case 5:fdivop()
case 6:modop()
case 7:expop()
case 8:
print("Thx for using
this program ")
break
case _:
print("Ur Selection of Operations is wrong!!")

#AopMenu.py
def menu():
s="""\t\t=================================================
Arithemtic Operations
=================================================
1. Addition
2. Substraction
3. Multiplications
4. Normal Division
5. Floor Division
6. Modulo Division
7. Expoentiation
8. Exit
================================================"""
print(s)

#aoppro.py----File Name and Module name


from AopMenu import menu
from AopImplementations import *
def runaopproj():
while(True):
menu()
ch=int(input("Enter Ur Choice:"))
match(ch):
case 1:addop()
case 2:subop()
case 3:mulop()
case 4:divop()
case 5:fdivop()
case 6:modop()
case 7:expop()
case 8:
print("Thx for using this program ")
break
case _:
print("Ur Selection of Operations is wrong!!")

#AopImplementations.py--file name and module name


def addop():
print("Enter Two values for Addition")
a,b=int(input()),int(input())
print("sum({},{})={}".format(a,b,a+b))
def subop():
print("Enter Two values for Sub")
a, b = int(input()), int(input())
print("sub({},{})={}".format(a, b, a - b))
def mulop():
print("Enter Two values for Mul")
a, b = int(input()), int(input())
print("mul({},{})={}".format(a, b, a * b))
def divop():
print("Enter Two values for Div")
a, b = int(input()), int(input())
print("Div({},{})={}".format(a, b, a / b))
def fdivop():
print("Enter Two values for Floor Div")
a, b = int(input()), int(input())
print("Floor Div({},{})={}".format(a, b, a // b))
def modop():
print("Enter Two values for Modulo Div")
a, b = int(input()), int(input())
print("mod({},{})={}".format(a, b, a % b))
def expop():
a,b=int(input("Enter Base:")),int(input("Enter Power:"))
print("pow({},{})={}".format(a,b,a**b))

which will implement the following


Case-2
==================================================
Different Figures
==================================================
1. Circle Area
2. Circle Perimter
3. Square Area
4. Square Perimeter
5. Rectangle Area
6. Rectange Perimter
7. Triangle Area
8. Triangle Perimeter(p=a+b+c)
9. Exit
==================================================

File System
------------------
Circle.py----File Name and Module Name
area()
peri()
Square.py---File Name and Module Name
area()
peri()
Recangle.py---File Name and Module Name
area()
peri()
Triangle.py---File Name and Module Name
area()
peri()
FigureMenu.py----File Name and module Name
menu()
CSRT.py---Main program

#FigureMenu.py----File Name and module Name


def menu():
s="""\t==================================================
Different Figures
==================================================
1. Circle Area
2. Circle Perimter
3. Square Area
4. Square Perimeter
5. Rectangle Area
6. Rectange Perimter
7. Triangle Area
8. Triangle Perimeter(p=a+b+c)
9. Exit
=================================================="""
print(s)

#Circle.py----File Name and Module Name


def area():
r=float(input("Enter Radius for Area:"))
ac=3.14*r**2
print("Area of Circle={}".format(ac))

def peri():
r=float(input("Enter Radius for Peri:"))
pc=2*3.14*r
print("Perimeter of Circle={}".format(pc))

#Square.py----File Name and Module Name


def area():
s=float(input("Enter Side for Area:"))
sa=s**2
print("Area of Square={}".format(sa))

def peri():
s=float(input("Enter Side for Peri:"))
sp=4*s
print("Perimeter of Square={}".format(sp))

#Rect.py----File Name and Module Name


def area():
l,b=float(input("Enter Length for Area:")),float(input("Enter Breadth for Area:"))
ra=l*b
print("Area of rectangle={}".format(ra))

def peri():
l,b=float(input("Enter Length for Peri:")),float(input("Enter Breadth for Peri:"))
pr=2*(l+b)
print("Peri of rectangle={}".format(pr))

#CSRT.py---main program
from FigureMenu import menu
from Circle import area as ca,peri as cp
from Square import area as sa,peri as sp
from Rect import area as ra, peri as rp
while(True):
menu()
ch=int(input("\tEnter Ur Choice:"))
if(ch==1):
ca()
elif(ch==2):
cp()
elif(ch==3):
sa()
elif(ch==4):
sp()
elif(ch==5):
ra()
elif(ch==6):
rp()
elif(ch==7):
print("Student must do")
elif(ch==8):
print("Student must do")
elif(ch==9):
break
else:
print("Ur Selection of Operation is Wrrong")

-------------------

Case-3
-------------------
==================================================
Temparature Conversions
==================================================
1. Celcious to Fahrenheit (ft=1.8*ct+32)
2. Fahrenheit to Celcious (ct=(ft-32)/1.8 )
3. Celcious to Kelvin (Kelvin = Celsius + 273.15)
4. Kelvin to Celcious (Celsius=Kelvin-273.15)
5. Fahrenheit to Kelvin(K = (F - 32) 5 / 9 + 273.15 )
6. Kelvin to Fahrenheit ( F = (K 273.15) 9 / 5 + 32 )
7. Exit
==================================================
File System
-------------------
=>TempMenu.py----File Name and Module Name
=>CelciousTOFahrenheit.py---File Name and Module Name
=>FahrenheitToCelcious.py---File Name and Module Name
=>CelciousToKelvin .py-----File Name and Module Name
=>KelvinToCelcious.py----File Name and Module Name
=>FahrenheitToKelvin.py----File Name and Module Name
=>KelvinToFahrenheit.py----File Name and Module Name
=>TempCalculator.py----Main Program
--------------------------------------------------------------------------------------------------------------------------
------------

=========================================
Conversion Menu
=========================================
1. Years to Months
2. Years to Days
3. Months to Years
4. Months to days
5. Days to Years
6. Days to Months
7. Exit
===========================================

Day – 52

=============================================
Package in Python
=============================================
=>The Function concept is used for Performing some operation and provides code re-usability within
the same program and unable to provide code re-usability across programs.

=>The Modules concept is a collection of Variables, Functions and classes and we can re-use the
code across the Programs provided Module name and main program present in same folder but
unable to provide code re-usability across the folders / drives / enviroments.

=>The Package Concept is a collection of Modules.


=>The purpose of Packages is that to provide code re-usability across the folders / drives /
enviroments.

=>To deal with the package, we need to the learn the following.
a) create a package
b) re-use the package
--------------------------------------------------------------------------------------------------
a) create a package:
----------------------------
=>To create a package, we use the following steps.
i) create a Folder
ii) place / write an empty python file called __init__.py (Optional)
iii) place / write the module(s) in the folder where it is considered as Package Name
--------------
Example:
--------------
bank <-----Package Name
-----------
__init__.py <----Empty Python File
simpleint.py <--- Module Name
aop.py-----Module Name
icici1.py---Module Name
welcome.py <--- Module Name
greet.py<---Module names
========================================================
b) re-use the package
---------------------------------
=>To the re-use the modules of the packages across the folders / drives / enviroments, we have to
two approaches. They are
i) By using sys module
ii) by using PYTHONPATH Environmental Variable Name
------------------------------------------------------------------------------------------
i) By using sys module:
-------------------------------------
Syntax:
----------- sys.path.append("Absolute Path of Package")

=>sys is pre-defined module


=>path is a pre-defined object of list / variable present in sys module
=>append() is pre-defined function present in path and is used for locating the package name of
python
( specify the absolute path)

Example:
-----------------
sys.path.append("D:\\KVR-PYTHON-6pm\\PACKAGES\\BANK")
(or)
sys.path.append("D:\KVR-PYTHON-6PM\ACKAGES\BANK")
(or)
sys.path.append("D:\KVR-PYTHON-6PM/PACKAGES/BANK")
-----------------------------------------------------------------------------------------------
ii) by using PYTHONPATH Enviromental Variables:
------------------------------------------------------------------------
=>PYTHONPATH is one of the Enviromental Variable
=>Search for Enviromental Variable
Steps for setting :
------------------------------
Var name : PYTHONPATH
Var Value : D:\\KVR-PYTHON-11am\\PACKAGES\\BANK

The overall path


PYTHONPATH= D:\\KVR-PYTHON-11am\\PACKAGES\\BANK

FAQ: What is Diff between Functions , Modules and Packages?

--------------
Function : To Perform Operation and Provides Code Re-Usability within the same Program
-------------- But not Possibile Re-Use across the Programs
Module: We Know that a Module is a collection of FUNCTIONS, GLOBAL VAR and
CLASSES
------------ Advantage of Modules is that "To Provide Re-usability of FUNCTIONS, GLOBAL VAR
and
CLASSES one Program into another program / Program to program access provided
Modules and Main program must present in Same Folder. But not Possible to Re-Use ACROSS the
FOLDERS, EVIRONMENTS, DRIVES, NETWORKS.

Package : A Package is a Collection of MODULES.


------------ The Advtange of Packages is that To Provide Re-usability of FUNCTIONS, GLOBAL
VAR and
CLASSES of One Module of One Evironment into another EVIRONMENTS, DRIVES,
NETWORKS.
=>Developing a package is nothing but Making Our Project as API
--------
API(Application Programming Interface)
------- An API is a collection of Packages.
Package is a Collection of Modules
A Module is a Collection of FUNCTIONS, GLOBAL VAR and CLASSES

#icici.py--File Name and Module name


bname="ICICI"
addr="HYD" # here bname and addr are called Global Variables
def simpleint(): # Function definition
p=float(input("Enter Principle Amount:"))
t=float(input('Enter Time:'))
r=float(input("Enter rate of interest:"))
#cal si and totamt to pay
si=(p*t*r)/100
totamt=p+si
print("*"*50)
print("Simple Interest Calculations")
print("*"*50)
print("\tPrinciple Amount:{}".format(p))
print("\tTime:{}".format(t))
print("\tRate of Interest:{}".format(r))
print("\tSimple Interest:{}".format(si))
print("\tTOTAL AMOUNT TO PAY:%0.2f" %totamt)
print("*"*50)

FROM ICIC import bname,addr,simpleint

day – 53
-====

===================================================
Exception Handling in Python
===================================================
Index
------------
=>Purpose of Exception Handling
=>Definition of Exception
=>Definition of Exception Handling
=>Types of Errors
a) Compile Time Errors
b) Logical Errors
c) Runtime Errors
=>Building Points in Learning Exception Handling
=>Types of Exceptions
a) Pre-Defined OR Built-In Exceptions
b) Programmer OR User OR Custom-Defined Exceptions
=>Keywords Used Exception Handling
1. try
2. except
3. else
4. finally
5. raise
=>Syntax for Handling Exceptions
=>Programming Examples
----------------------------------------------------------------------------------------
=>Steps for developing Programmer-Defined Exceptions (Most Imp)
=>Programming Examples
-----------------------------------------------------------------------------------------
=>Implementation of ATM Operations
=>Case Study--with Exceptions (ATM)
=================================================
Types of Errors
=================================================
=>The purpose of Exception Handling is that " To Build Robust (Strong) Applications ".
=>In real time, to develop any type of application, we need to choose a language.
=>By using the language, we can develop, compile and execute various Programs. During this
Process,
we get Various types of Errors. They are classified into 3 types. They are
1. Compile Time Errors.
2. Logical Errors.
3. Runtime Errors.
--------------------------------------------------------------------------------------------------------------------------
----------------------
1. Compile Time Errors
--------------------------------------------------------------------------------------------------------------------------
----------------------
=>Compile Time Errors are those which are occuring during Compilation Process (.py---->.pyc).
=>Compile Time Errors occurs due to Programmer not following Syntaxes of the Lang.
=>Compile Time Errors Solved by Programmers during development time.
--------------------------------------------------------------------------------------------------------------------------
----------------------
2. Logical Time Errors
--------------------------------------------------------------------------------------------------------------------------
----------------------
=>Logical Errors are those which are occuring during Execution Time (.pyc---->PVM).
=>Logical Errors occurs due to Wrong Representation / Invalid Logics of Problem
=>Logical Errors always Wrong Results
=>Logical Errors Solved by Programmers during development time.
--------------------------------------------------------------------------------------------------------------------------
----------------------
3. Runtime Errors ( Implementation Errors)
--------------------------------------------------------------------------------------------------------------------------
----------------------
=>Runtime Errors are those which are occuring during Execution / Runtime Time.
=>Runtime Errors occurs due to Wrong OR Invalid Inputs Entered by End-User OR Application
User.
=>By default Runtime Errors always generates Technical Error Messages, which are understandable
by
Programmers but not by end-users. So Industry Recommeded to Convert Technical Error
Messages into User-Freindly Error Messages by using Exception Handling.

====================================================
Building Points for Learning Exception Handling
====================================================
1. When th Application User Enters Invalid / Wrong Input then we get Runtime Errors
(Invalid Input------->Runtime Error)
2. All Runtime Errors by Default generates Technical Error Messages.
( Runtime Errors---->Technical Error Messages )
-------------------------------------
3. Definition of Exception: Every Runtime Error is called Exception
-------------------------------------
(Invalid Input---->Runtime Error---->Exception)
Hence Every Invalid Input gives Exception
-------------------------------------------------
4. Definiton of Exception Handling:
-------------------------------------------------
=>The Process of Converting Technical Error Messages into User-Freindly Error Message is Called
Exception Handling.
5. When an exception occurs, Internally 3 Steps takes Place. They are
a) Program Execution Abnormally terminated by PVM
b) PVM Comes Out-of Program Execution
c) By Default PVM generates Technical Error Message

6. To Perform Step-(a),Step-(b) and Step-(c), Internally "PVM Creates an Object of Appropriate


Exception
Class".
7. When an exception occurs in Python then PVM creates an object appropriate exception Classs.

8. Hence Every Exception in Python is Considered as Object and It is created w.r.t appropriate
exception
Classs.
========================================================================
==========

NOTE:
When th Application User Enters Valid Input then we get result / Output. When the application
user enters Invalid Input then we get Exception.

#Ex1.py
print("Program Execution Started:")
a=10
b=0
print("a={} b={}".format(a,b))
c=a/b
print("Div={}".format(c))
print("Program Execution Ended:")

=======================================
Types of Exceptions in Python
=======================================
=>In Python Programming, we have two types of exceptions. They are

1. Pre-Defined OR Built-in Exceptions


2. Programmer OR User OR Custom Defined Exceptions
--------------------------------------------------------------------------------------------------------------------------
-----------------------
1. Pre-Defined OR Built-in Exceptions
--------------------------------------------------------------------------------------------------------------------------
-----------------------
=>These exceptions are developed by Python Lang Developers and Available in Python Software and
Used by Python Lang Programmers for Dealing with Universal Problem.
=>Some of the Universal Probelms are.

a) Invalid number format ( ValueError)


b) Invalid Attribute Names (AttributeError)
c) Invalid Key (KeyError)
d) module does not exist ( ModuleNotFoundError)
e) wrong index (IndexError)..etc
--------------------------------------------------------------------------------------------------------------------------
-----------------------
2. Programmer OR User OR Custom Defined Excetpions
--------------------------------------------------------------------------------------------------------------------------
-----------------------
=>These exceptions developed by Python Lang Programmers and Available in Python Project and
Used by Other team Members of same project for dealing with Common Problems in Project

=>Some of the Common Problems are


a) Attempting to enter Invalid PIN in ATM Application
b) Attempting to withdraw more amount than existing Balance.
c) Attempting to Enter Invalid User Name and Password ..etc
================================x=======================================
===========/.
day --- 54

=========================================================
Handling the Exceptions in Python
=========================================================
=>Handling the Exceptions in Python is nothing Converting Techincal Error Messages into into
User-Freindly Error Messages.
=>To handle the exceptions in Python, we have 5 Keywords. They are
1. try
2. except
3. else
4. finally
5. raise
--------------------------------------------------------------------------------------------------------------------------
----------------
Syntax for Handling the exception in Python
--------------------------------------------------------------------------------------------------------------------------
----------------
try:
Block of statements
Generating Exceptions
except exception-class-name-1:
Block of Statements
Generates User-Friendly Error Messages
except exception-class-name-2:
Block of Statements
Generates User-Friendly Error Messages
----------------------------------------
----------------------------------------
except exception-class-name-n:
Block of Statements
Generates User-Friendly Error Messages
else:
Block of Statements
generates Results
finally:
Block of statements executes
Compulsorily

#Program for accepting Two Numerical Values from KBD and Find their Div
#DivEx1.py
s1=input("Enter First Value:")
s2=input("Enter Second Value:")
a=int(s1) # exception generated statement--problemtaic statement
b=int(s2) # exception generated statement--problemtaic statement
c=a/b # exception generated statement--problemtaic statement
print("Div={}".format(c))

#Program for accepting Two Numerical Values from KBD and Find their Div
#DivEx2.py
try:
print("I am in try block")
s1=input("Enter First Value:")
s2=input("Enter Second Value:")
a=int(s1) # exception generated statement--problemtaic statement
b=int(s2) # exception generated statement--problemtaic statement
c=a/b # exception generated statement--problemtaic statement
except ZeroDivisionError:
print("Don't enter Zero for Den...")
except ValueError:
print("Don't Enter Alnums,Strs and symbols")
else:
print("-------------------------------")
print("Div={}".format(c))
print("-------------------------------")
finally:
print("I am from finally block")

#Program for accepting Two Numerical Values from KBD and Find their Div
#DivEx3.py
try:
print("I am in try block")
s1=input("Enter First Value:")
s2=input("Enter Second Value:")
a=int(s1) # exception generated statement--problemtaic statement
b=int(s2) # exception generated statement--problemtaic statement
c=a/b # exception generated statement--problemtaic statement
except (ZeroDivisionError,ValueError): # Multi Exceptions handling Block
print("Don't enter Zero for Den...")
print("Don't Enter Alnums,Strs and symbols")
else:
print("-------------------------------")
print("Div={}".format(c))
print("-------------------------------")
finally:
print("I am from finally block")

day --- 55

================================================
Explanation for the keywords used in Syntax of Handling Exception
================================================
--------------------------------------------------------------------------------------------
1.try
--------------------------------------------------------------------------------------------
=>It is the block in which we write block of statements generating exceptions. In otherwords what
are all the statements generating exceptions, those statements must be written within try block and
hence try block is called Exception monitering block.
=>When an exception occurs in try block then PVM comes out of try block and executes
appropriate except block.
=>After executing appropriate except block, PVM never goes to try block for executing rest of
the statements in try block.
=>Every try block must be immediately followed by except block ( Otherwise we get
SyntaxError)
=>Every try block must contain atleast one except block . It is recommended to write multiple
except blocks for generating User-Friendly error messages.
-------------------------------------------------------------------------------------------
2.except
--------------------------------------------------------------------------------------------
=>It is the block in which we write block of statements generates User-Friendly Error
Messages. In Otherwords except block suppreses Technical error messages and generates
User-Freindly Error Messages and hence except block is called Exception Processing Block.
Note: Handling exception= try block + except block

=>except block will execute when there is an exception occurs in try block.
=>Even we write multiple except blocks , PVM executes Appropriate except block(Single
Block) depends on type of exception occurs in try block.
=>The place for writing except block is that after try block and before else block.
--------------------------------------------------------------------------------------------------------------------------
----------------
3.else
--------------------------------------------------------------------------------------------
=>It is the block in which we write block of statements will display results of the program and
hence else block is called Result Generated Block.
=>else block will execute when there is no exception occurs in try block.
=>Writing else block is optional
=>The place of writing else block is that after except block and before finally block (if it
present).
--------------------------------------------------------------------------------------------
4.finally
--------------------------------------------------------------------------------------------
=>It is the block, in which we write block of statements will relinquish (release / close /
give-up/clean-up) the resources ( Files, Database softwares) which are obtained in try block and
finally block is called Resouces relinquishing Block.
=>finally block will execute compulsorily.
=>finally block is optional to write
=>The place of writing finally block is that after else block ( if else block present)
=======================x================================================
=============

Various forms of except blocks


=======================================
=>we can use except block in Various Forms.
----------------------------------------------------------------------------------------------------------
Form-1: With this form, we can handle one exception at a time.
----------------------------------------------------------------------------------------------------------
try:
---------------------------
---------------------------
except exception-class-name-1:
------------------------------------
------------------------------------
except exception-class-name-2:
------------------------------------
------------------------------------
------------------------------------------------
except exception-class-name-n:
------------------------------------
------------------------------------
-----------------------------------------------------------------------------------------------------------
Form-2: With this form we can handle multiple specific exceptions with a single except block
This type of facility is called Multi Exception handling block.
----------------------------------------------------------------------------------------------------------
try:
------------------------------------
------------------------------------
except ( exception-class-1,exception-class-2...exception-class-n ):
---------------------------------------------------
Block of statments provides
User-Friendly error messages
for Multiple Specific Exceptions
---------------------------------------------------

---------------------------------------------------------------------------------------------------------------------
Form-3: With this form, we can handle one exception at a time with ALIAS NAME for capuring
Technical
error messages occuring due exception occurence.
---------------------------------------------------------------------------------------------------------------------
try:
---------------------------
---------------------------
except exception-class-name-1 as alias name:
------------------------------------
print(alias name)
------------------------------------
except exception-class-name-2 as alias name:
------------------------------------
print(alias name)
------------------------------------
------------------------------------------------
except exception-class-name-n as alias name:
------------------------------------
print(alias name)
------------------------------------
-------------------------------------------------------------------------------------------------------------------
Form-4: default except block--matches with all types of exceptions
---------------------------------------------------------------------------------------------------------------------
try:
---------------------------
---------------------------
except :
------------------------------------
print("OOOPs Some thing went wrong")
------------------------------------
=>Industry is not recommended to write single default except block bcoz it is giving common
messages for all types of exceptions.
=>Hence Industry is highly recommended to write default except block at end of all types of specific
except blocks.

Final Syntax:
--------------------------
try:
---------------------------
---------------------------
except exception-class-name-1:
------------------------------------
------------------------------------
except exception-class-name-2:
------------------------------------
------------------------------------
------------------------------------------------
except exception-class-name-n:
------------------------------------
------------------------------------
except: # default except block
------------------------------
------------------------------
else:
-----------------
-----------------
finally:
---------------
---------------

(OR)

try:
---------------------------
---------------------------
except ( exception-class-1,exception-class-2...exception-class-n ):
---------------------------------------------------
Block of statments provides
User-Friendly error messages
for Multiple Specific Exceptions
---------------------------------------------------
except: # default except block
------------------------------
------------------------------
else:
-----------------
-----------------
finally:
---------------
---------------

==================================x===================================

#Program for accepting Two Numerical Values from KBD and Find their Div
#DivEx3.py
try:
print("I am in try block")
s1=input("Enter First Value:")
s2=input("Enter Second Value:")
a=int(s1) # exception generated statement--problemtaic statement
b=int(s2) # exception generated statement--problemtaic statement
c=a/b # exception generated statement--problemtaic statement
except (ZeroDivisionError,ValueError): # Multi Exceptions handling Block
print("Don't enter Zero for Den...")
print("Don't Enter Alnums,Strs and symbols")
else:
print("-------------------------------")
print("Div={}".format(c))
print("-------------------------------")
finally:
print("I am from finally block")

#Program for accepting Two Numerical Values from KBD and Find their Div
#DivEx4.py
try:
print("I am in try block")
s1=input("Enter First Value:")
s2=input("Enter Second Value:")
a=int(s1) # exception generated statement--problemtaic statement
b=int(s2) # exception generated statement--problemtaic statement
c=a/b # exception generated statement--problemtaic statement
except ZeroDivisionError as z:
print(z)
except ValueError as v:
print(v)
else:
print("-------------------------------")
print("Div={}".format(c))
print("-------------------------------")
finally:
print("I am from finally block")
#Program for accepting Two Numerical Values from KBD and Find their Div
#DivEx5.py
try:
print("I am in try block")
s1=input("Enter First Value:")
s2=input("Enter Second Value:")
a=int(s1) # exception generated statement--problemtaic statement
b=int(s2) # exception generated statement--problemtaic statement
c=a/b # exception generated statement--problemtaic statement
except :
print("ooops....Some Thing went Wrong")
else:
print("-------------------------------")
print("Div={}".format(c))
print("-------------------------------")
finally:
print("I am from finally block")

#Program for accepting Two Numerical Values from KBD and Find their Div
#DivEx6.py---2023-May--KVR Developed This program with 2 Exceptions
#2025---there is chance of Modifying the code by adding some new statements by NEW
PROGRAMMER
try:
print("I am in try block")
s1=input("Enter First Value:")
s2=input("Enter Second Value:")
a=int(s1) # exception generated statement--problemtaic statement
b=int(s2) # exception generated statement--problemtaic statement
c=a/b # exception generated statement--problemtaic statement
#s="PYTHON" # 2025 adding
#print(s[11])
except ZeroDivisionError:
print("Don't enter Zero for Den...")
except ValueError:
print("Don't Enter Alnums,Strs and symbols")
except : # default except block--last
print("OOOPS..Some Thing went Wrong")
else:
print("-------------------------------")
print("Div={}".format(c))
print("-------------------------------")
finally:
print("I am from finally block")

==================================================
Development of Programmer-Defined Exceptions
==================================================
=>These exceptions developed by Python Lang Programmers and Available in Python Project and
Used
by Other team Members of same project for dealing with Common Problems in Project.
=>Some of the Common Problems are
a) Attempting to enter Invalid PIN in ATM Application (Ex: PinError)
b) Attempting to withdraw more amount than existing Balance(Ex: InSufficientBal)
c) Attempting to Enter Invalid User Name and Password ..etc (Ex: LoginError)

=>To develop Programmer-Defined Exception classes, we use the following Steps

Step-1: Choose the Programmer Class Name


Step-2: Every Programmer-Defined Class Name Must Inherit From Either Exception or
BaseException
and Hence Programmer-Defined Class is called Programmer-Defined exception sub Class.
Step-3: The Step-1 and Step-2 on some file name with an extension .py and It acts as Module Name.
--------------------------------------------------------------------------------------------------------------------------
---------------------
Examples: class PinError(Exception):pass
class InSufficientFundError(BaseException):pass
class LoginError(Exception):pass

=>Here PinError,InSufficientFundError and LoginError are called Programmer-Defined Exception


Classes.

#Generating Exception when division by zero by using raise kwd


#Division.py--File Name and Module Name
from Hyd import HydDivisionError
def divop(a,b):
if(b==0):
raise HydDivisionError # raise kwd is used for Hitting / generating the exception
else:
return (a/b)

#Handling the exception by zero is denominater--main program


#DivDemo.py
from Division import divop
from Hyd import HydDivisionError
a=int(input("Enter First Value:"))
b=int(input("Enter Second Value:"))
try:
res=divop(a,b) # Function call with result or exception
except HydDivisionError:
print("DON'T ENTER ZERO FOR DEN...")
else:
print("Div:{}".format(res))

#Development of Exception
#Hyd.py--File name and module name
# (1) (2)
class HydDivisionError(Exception):pass

write a python program which will geneartee a multiplaction table

where n must be positive integer

it n =0 then raised 0 error

if n>0 raised neg number error

#development of exception for generating multable


#MulExceptions.py--File Name and Module Name
class ZeroError(Exception):pass
class NegNumError(BaseException):pass

#Program for MulTable by hitting exceptions


#MulTable.py---File Name and Module Name
from MulExceptions import ZeroError,NegNumError
def multable(n):
if(n==0):
raise ZeroError # Hitting the exception
elif(n<0):
raise NegNumError # Hitting the exception
elif(n>0):
print("-----------------------------------------------------")
print("Mul Table for :{}".format(n))
print("-----------------------------------------------------")
for i in range(1,11):
print("\t{} x {} = {}".format(n,i,n*i))
print("-----------------------------------------------------")

#Program for obtaining MulTable and Handling the exception


#MulTableDemo.py
from MulTable import multable
from MulExceptions import ZeroError,NegNumError
try:
n=int(input("Enter a Number for Generating Mul table:"))
multable(n) # Funcrtion call with Result and Exceptions
except ZeroError:
print("Don't enter Zero for Mul Table:")
except NegNumError:
print("Don't Enter -ve Number for Mul table:")
except ValueError:
print("Don't enter alnums,strs and special symbols")

================================================
raise key word
=================================================
=>raise keyword is used for hitting / raising / generating the exception provided some
condition must be satisfied.
=>raise keyword always used inside of Function Definition only.
=>PVM uses raise keyword implicitly for hitting pre-defined Exceptions where as Programmer
makes the PVM to use raise keyword explicitly for Hitting or Generating Programmer-defined
Exceptions.

=>Syntax-1:- if (Test Cond):


raise <exception-class-name>

=>Syntax-2:- def functionname(list of formal parms if any):


-----------------------------------------------------
-----------------------------------------------------
if (Test Cond):
raise <exception-class-name>
--------------------------------------------------------
-------------------
Examples:
-------------------
from hyd import HydDivisionError
def division(a,b):
if(b==0):
raise HydDivisionError
else:
return (a/b)

day == 56
write a python program which will implement sum of atm and devlop,hit ,devlop,hit handeled the
exceptions if requjireds

#ATMMenu.py
def menu():
s="""\t\t=========================================
ATM Operations
=========================================
1. Deposit
2. WithDraw
3. BalEnq
4. Exit
========================================="""
print(s)

menu()

#ATMMainProg.py
from ATMMenu import menu
from ATMExceptions import DepositError,WithDrawError,InSuffFundError
from ATMOperations import deposit,withdraw,balenq
while(True):
menu()
ch=int(input("\t\tEnter Ur Choice:"))
match(ch):
case 1:
try:
deposit()
except ValueError:
print("Don't try deposit Alnums,strs and Special Symbols")
except DepositError:
print("Don't try deposit Zero / -Ve Values")
case 2:
try:
withdraw()
except ValueError:
print("Don't try Withdraw Alnums,strs and Special Symbols")
except WithDrawError:
print("Don't try withdraw Zero / -Ve Values")
except InSuffFundError:
print("Ur Account does not have suff funds--read python notes")
case 3:
balenq()
case 4:
print("Thx for this program")
break
case _:
print("Ur Selection of Operation is Wrong--Try again")

#ATMOperations.py
from ATMExceptions import DepositError,WithDrawError,InSuffFundError
bal=500.00 # Global Varaible
def deposit():
damt=float(input("Enter Ur Deposit Amount:")) # PVM Implicitly Raises ValueError
if(damt<=0):
raise DepositError
else:
global bal
bal=bal+damt
print("Ur Account xxxxxxxx123 Credited with INR:{}".format(damt))
print("After Deposit Ur Account xxxxxxxx123 Bal INR:{}".format(bal))

def withdraw():
global bal
wamt=float(input("Enter Ur WithDraw Amount:")) # PVM Implicitly Raises ValueError
if(wamt<=0):
raise WithDrawError
elif((wamt+500)>bal):
raise InSuffFundError
else:
bal=bal-wamt
print("Ur Account xxxxxxxx123 Debited with INR:{}".format(wamt))
print("After With Ur Account xxxxxxxx123 Bal INR:{}".format(bal))

def balenq():
print("\t Ur Account xxxxxxxx123 Bal INR:{}".format(bal))

#ATMExceptions.py
class DepositError(Exception):pass
class WithDrawError(BaseException):pass
class InSuffFundError(Exception):pass

#ATMMainProg1.py
from ATMMenu import menu
from ATMExceptions import DepositError,WithDrawError,InSuffFundError
from ATMOperations import deposit,withdraw,balenq
def runatm():
while(True):
menu()
ch=int(input("\t\tEnter Ur Choice:"))
match(ch):
case 1:
try:
deposit()
except ValueError:
print("Don't try deposit Alnums,strs and Special Symbols")
except DepositError:
print("Don't try deposit Zero / -Ve Values")
case 2:
try:
withdraw()
except ValueError:
print("Don't try Withdraw Alnums,strs and Special Symbols")
except WithDrawError:
print("Don't try withdraw Zero / -Ve Values")
except InSuffFundError:
print("Ur Account does not have suff funds--read python notes")
case 3:
balenq()
case 4:
print("Thx for this program")
break
case _:
print("Ur Selection of Operation is Wrong--Try again")

import sys
sys.path.append(“”)
from

======================================
Decorators in Python
======================================
=>Decorator is one of the Function which will provides Additional Processing capability to the
normal Function value and returns the modified value.
=>A Decorator Function is always takes Normal Function as parameter
--------------
Syntax:-
-------------
def functionname1( functionname ): # Decorator
def innerfunctionname(): # Inner Function name
val=functionname()
--------------------------
#do the operation on ' val '
-------------------------
return resut # Inner Funtion must return modified value
return innerfunctionname # Decorator returns inner function name

=>here functionname1 is called Decorator function


=>here Functionname as a formal parameter . Every decorator function must take normal function as
parameter.

#Program for demoinstrating non-decorator example


#Non-DecEx1.py
def getval(): # This Function Defined by KVR
return int(input("Enter Any Value:"))
def square():
n=getval()
res=n**2
return res

def squareroot():
n=getval()
res=n**0.5
return res

def cube():
n=getval()
res=n**3
return res

#Main program
res=square()
print("Square ={}".format(res))
print("------------------------------------------")
res=squareroot()
print("Square Root ={}".format(res))
print("------------------------------------------")
res=cube()
print("Cube ={}".format(res))

#Program for demoinstrating non-decorator example


#DecEx1.py
def getval(): # This Function Defined by KVR
return int(input("Enter Any Value:"))

def square( kvr ): # Here Square is called Decorator


def operation(): # Inner Function will the operations for kvr function (alias name of getval())
n=kvr()
res=n**2
return res
return operation

#main program
result=square(getval)
res=result()
print("Square={}".format(res))

#Program for demoinstrating non-decorator example


#DecEx2.py
def square(kvr):
def operation():
n=kvr()
res=n**2
return res
return operation

@square
def getval(): # This Function Defined by KVR
return int(input("Enter Any Value:"))

#main program
res=getval() # Calling Normal Function
print("Square={}".format(res))

#DecEx3.py
def getline():
line=input("Enter a Line of Text:")
return line

def converttoupper(hyd): # here converttoupper() is called Decorator


def caseconvert():
text=hyd()
res=text.upper()
return res
return caseconvert

#Main Program
resstr=converttoupper(getline)
res=resstr()
print("Upper Case Data=",res)

#DecEx4.py

def converter(kvr):
def caseconvert():
text=kvr()
res=text.upper()
return res
return caseconvert

@converter
def getline():
line=input("Enter a Line of Text:")
return line

#main program
res=getline()
print("Upper Case Data:",res)

day – 57

========================================
random module
========================================
=>random one of pre-defined module present in python
=>The purpose of random is that "To generate random values in various contexts".
=>random module contains the follwoing essential functions.
a) randrange()
b) randint()
----------------------------------
c) random()
d) uniform()
----------------------------------
e) choice()
f) shuffle()
g) sample()
--------------------------------------
===============================================================
a) randrange()
-------------------------
=>This function is used for generating random integer values between specified limits.
Syntax1:- random.randrang(Value)
This syntax generates any random value between 0 to Value-1

Syntax-2: random.rangerange(start,stop,step)
This syntax generates any random value between start to stop-1

Examples:
---------------
>>> import random
>>> print(random.randrange(100,150))----133
>>> print(random.randrange(100,150))----121
>>> print(random.randrange(100,150))----139
>>> print(random.randrange(100,150))----143
>>> print(random.randrange(100,150))---106
>>> print(random.randrange(100,150))---133
>>> print(random.randrange(10))----5
>>> print(random.randrange(10))----9
-----------------------------------------------------
#randrangeex.py
import random
for i in range(1,6):
print(random.randrange(10))
print("---------------------------------------")
for i in range(1,6):
print(random.randrange(1000,1100))
print("---------------------------------------")
================================X============================
b) randint():
--------------------
=>Syntax:- random.radint(start,stop)
=>This syntax generates any random value between start to stop. Here start and stop are inclusive.
Examples:
----------------
>>> print(random.randint(10,15))------10
>>> print(random.randint(10,15))-----13
>>> print(random.randint(10,15))----14
>>> print(random.randint(10,15))----11
>>> print(random.randint(10,15))----15
----------------------------------------------------------
#randintex.py
import random
for i in range(1,6):
print(random.randint(10,20))
print("---------------------------------------")
==============================X================================
c) random()
-----------------------
=>Syntax:- random.random()
=>This syntax generates floating point random values between 0.0 and 1.0 (Execlusive))
Examples:
----------------
>>> import random
>>> print(random.random())----------0.1623906138450063
>>> print(random.random())--------0.15382209709271966
>>> print(random.random())-------0.09542283007844476
>>> print(random.random())-----0.6134301633766425
-------------------------
#randomex.py
import random
lst=[]
for i in range(1,6):
lst.append("%0.2f" %random.random())
print("---------------------------------------")
print("Content of lst={}".format(lst))
============================X=============================
d) uniform()
----------------------
Syntax:- random.uniform(start,stop)
=>This generates random floting point values from start to stop-1 values
=>The values of start and stop can both Integer or floating point values.
Examples:
----------------
>>> import random
>>> print(random.uniform(10,15))----------14.416746067678286
>>> print(random.uniform(10,15))----13.2420406264978
>>> print(random.uniform(10,15))-----11.716110933506432
>>> print(random.uniform(10,15))--------10.703499588966528
>>> print(random.uniform(10,15))-----11.306226559323017
>>> print(random.uniform(10.75,15.75))--------13.939787347170148
>>> print(random.uniform(10.75,15.75))----10.760428232717597
-------------------------------------------------------------------------------------------
#uniformex.py
import random
lst=[]
for i in range(1,6):
lst.append(float("%0.2f" %random.uniform(10,15.5)))
print("---------------------------------------")
print("Content of lst={}".format(lst))
===========================X================================
e) choice():
-------------------
Syntax:- random.choice(Iterable_object)
=>This function obtains random values from Iterable_object.
---------------------
EXAMPLES:
---------------------
>>>
print(random.choice([10,20,30,40,50]),random.choice("PYTHON"),random.choice(range(10,15)))---
40 T 11
>>>
print(random.choice([10,20,30,40,50]),random.choice("PYTHON"),random.choice(range(10,15)))---
-------30 P 12
>>>
print(random.choice([10,20,30,40,50]),random.choice("PYTHON"),random.choice(range(10,15)))---
--------40 N 12
-------------------------------------
#choiceex.py
import random
s="AaBRe#^%@8YuQLPau*&"
for i in range(1,6):
print(random.choice(s),random.choice(s),random.choice(s),random.choice(s))
===========================X================================
f) shuffle():
--------------------
=>This Function is used for re-organizing the elements of any mutable object but not on immutable
object.

Syntax:- random.shuffle(list)
=>We can shuffle the data of list but not other objects of Data Types
Examples:
-------------------
>>> d={10:"cadburry",20:"kitkat",30:"malkybar", 40:"dairymilk"}
>>> print(d)---{10: 'cadburry', 20: 'kitkat', 30: 'malkybar', 40: 'dairymilk'}
>>> for k,v in d.items():
... print(k,"--",v)
...
10 -- cadburry
20 -- kitkat
30 -- malkybar
40 -- dairymilk
>>> import random
>>> print(random.shuffle(d))----Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\nareshit\AppData\Local\
Programs\Python\Python310\lib\random.py", line 394, in shuffle
x[i], x[j] = x[j], x[i]
KeyError: 3
>>> s={10,20,30,40,50}
>>> print(random.shuffle(s))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\nareshit\AppData\Local\Programs\
Python\Python310\lib\random.py", line 394, in shuffle
x[i], x[j] = x[j], x[i]
TypeError: 'set' object is not subscriptable

>>> t=(10,20,30,40,50)
>>> print(random.shuffle(t))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\nareshit\AppData\Local\Programs\
Python\Python310\lib\random.py", line 394, in shuffle
x[i], x[j] = x[j], x[i]
TypeError: 'tuple' object does not support item
assignment
>>> l=[10,20,30,40,50]
>>> print(random.shuffle(l))-----None
>>> print(l)-------------[30, 40, 50, 10, 20]
>>> random.shuffle(l)
>>> print(l)------------[40, 30, 10, 20, 50]
>>> random.shuffle(l)
>>> print(l)---------[40, 10, 50, 20, 30]
>>> random.shuffle(l)
>>> print(l)------------[30, 50, 20, 40, 10]

#shuffleex.py
import random as r
l=[10,"Python","Rossum",34.56,True]
for i in range(1,6):
r.shuffle(l)
print("content of l=",l)
===================================X============================
g) sample()
------------------
=>This Function is used for selecting random samples from any Iterable object based on number of
samples(+ve)
Syntax:- random.sample(iterable_object, k)
=>Here 'k' can be number of samples.

Examples:
------------------
>>> import random
>>> s="ABCabcERTYUertyu$%^&*#@!%^&ghjkiyl"
>>> print(random.sample(s,5))----------['A', '*', '^', 'j', 't']
>>> print(random.sample(s,5))---------['%', 'l', 'b', 'C', 'y']
>>> print(random.sample(s,5))----------['%', 'e', 'Y', 'j', 'u']
>>> print(random.sample(s,5))------['y', 'E', '&', '$', '#']
>>> print(random.sample(s,5))----------['j', '*', 't', '$', 'u']
-----------------------------------------------------------------
#sampleex.py
import random
lst=[10,"Rossum","Python",34.56,True]
for i in range(1,6):
print(random.sample(lst,2))
================================X===========================

#program for generating random Integer Values between 10 and 20 --randrange()


#randrangeex1.py
import random as r
for i in range(1,6):
print(r.randrange(10,20))

"""
D:\KVR-PYTHON-6PM\RANDOM>py randrangeex1.py
17
11
11
12
18
"""

#program for generating random Integer Values between 10 and 20 --randint()


#randintex1.py
import random as r
for i in range(1,6):
print(r.randint(10,20))

"""
D:\KVR-PYTHON-6PM\RANDOM>py randintex1.py
20
11
10
18
10
"""

#program for generating random floating point values between 0.0 to 1.0--random()
#randomex1.py
from random import random
for i in range(1,6):
print(random())
print("---------------OR-----------------------")
for i in range(1,6):
print("%0.3f" %random())
print("---------------OR-----------------------")
for i in range(1,6):
print(round(random(),2))

"""
D:\KVR-PYTHON-6PM\RANDOM>py randomex1.py
0.9793648027983883
0.08749143415787031
0.8938371308045829
0.6104902612716221
0.6244688112926148
---------------OR-----------------------
0.633
0.582
0.013
0.398
0.176
---------------OR-----------------------
0.81
0.77
0.64
0.92
0.72
"""

#program for generating random floating point values between 10 to 12--uniform()


#uniformex.py
from random import uniform
for i in range(1,6):
print(uniform(10.5,12))
print("---------------OR-----------------------")
for i in range(1,6):
print("%0.3f" %uniform(10.5,12))
print("---------------OR-----------------------")
for i in range(1,6):
print(round(uniform(10.5,12),2))

""""
D:\KVR-PYTHON-6PM\RANDOM>py uniformex.py
10.69204330380328
11.039112959695647
10.875764502472572
11.49883288815713
11.679105477134472
---------------OR-----------------------
10.648
11.194
11.928
11.404
10.664
---------------OR-----------------------
10.53
11.61
11.9
10.64
11.35
"""

rogram for demnonstrating random Choce Value from any Iterable object
#choiceex1.py
import random as r
s="HYDERABAD"
for i in range(1,6):
print(r.choice(s))
print("--------------------------------------------------")
lst=[10,"Rossum",34.56,True,2+6j,False,"Python"]
for i in range(1,6):
print(r.choice(lst))
print("--------------------------------------------------")

"""
--------------------------------------------------

D:\KVR-PYTHON-6PM\RANDOM>py choiceex1.py
Y
D
H
A
D
--------------------------------------------------
10
(2+6j)
Python
34.56
(2+6j)
--------------------------------------------------
"""
#program for demnonstrating random Choce Value from any Iterable object--captcha Code
#choiceex2.py
import random as r
Upperalphs="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Loweralphs="abcdefghijklmnopqrstuvwxyz"
digits="0123456789"
sps="!@#$%^&*()_+="
for i in range(1,10):
print(r.choice(Upperalphs),r.choice(Loweralphs),r.choice(digits),r.choice(sps))

"""
Nt9@
Rw2%
Ni5^
Gd5&
Ux4(
Vx6=
Vc1#
Vt2=
Dk3(
"""

#program for demnonstrating random Choce Value from any Iterable object--captcha Code
#choiceex3.py
import random as r
cap="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz!@#$
%^&*()_+="
for i in range(1,10):
print(r.choice(cap),r.choice(cap),r.choice(cap),r.choice(cap),r.choice(cap))

"""
D:\KVR-PYTHON-6PM\RANDOM>py choiceex3.py
CM!2F
uWs0*
XJ=Ms
YPb5P
T8Xvq
RxjD1
Pi(wh
SL_AB
Ml#4@
"""
#Program re-shuffling Or Re-oraganizng the elements of mutable objects--by using shuffle()
#ShuffleEx1.py
import random as r
lst=[10,"HYD",45.67,True,"Rajesh","Python",2+3j]
for i in range(1,6):
r.shuffle(lst)
print(lst)

#Program re-shuffling Or Re-oraganizng the elements of str object--by using shuffle()


#ShuffleEx2.py
import random as r
s="HYDERABAD"
lst=list(s)
for i in range(1,len(s)):
r.shuffle(lst)
k=""
k=k.join(lst)
print(k)

"""
D:\KVR-PYTHON-6PM\RANDOM>py ShuffleEx2.py
DBDAEAYHR
EDRYHBDAA
AYHDBARDE
DEAAHBDRY
EYABHDRDA
DAYHRBEAD
AHDABEYRD
ERDAYAHDB
"""

#program for demnonstrating random sampling values from any Iterable object
#SampleEx1.py
from random import sample
s="PYTHON"
for i in range(1,6):
k=""
lst=sample(s,k=3)
k=k.join(lst)
print(k)

#program for demnonstrating random sampling values from any Iterable object
#SampleEx2.py
import random as r
cap="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz!@#$
%^&*()_+="
for i in range(1,10):
lst=r.sample(cap,k=5)
k=""
k=k.join(lst)
print(k)

"""
D:\KVR-PYTHON-6PM\RANDOM>py SampleEx2.py
liNQb
q6(_E
9!2Uj
ieBTO
aibL@
&!lu@
Fp9hw
hAW_V
6@QR5
"""

#program for demnonstrating random sampling values from any Iterable object
#SampleEx3.py
import random as r
state=["TS","AP"]
rtcode=["09","08","07","06","39"]
nums="0123456789"
alphs="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
#numberplate: TS08 HF 8558 TS08HL3600
for i in range(1,10):
st1=r.sample(state,1)
rc=r.sample(rtcode,1)
lets=r.sample(alphs,2)
no=r.sample(nums,4)
sst1=""
sst1=sst1.join(st1)
src=""
src=src.join(rc)
slets=""
slets=slets.join(lets)
sno=""
sno=sno.join(no)
numberplate=sst1+src+" "+slets+" "+sno
print(numberplate)

"""
D:\KVR-PYTHON-6PM\RANDOM>py SampleEx3.py
AP39 AX 5498
TS06 MK 1072
AP08 QE 2360
AP07 MC 6304
TS08 FU 4396
TS09 MQ 1309
TS07 BY 6783
TS06 UF 3016
AP39 LR 5138
"""

Day --- 58

==========================================
Files Or Streams in Python--5 Days
==========================================
Index
-----------------------
=>Purpose of Files
=>Types of Applications
a) Non-Persistant Appliactions
b) Persistant Appliactions
=>Defition of File
=>Definition of Streams
=>Operations on Files
a) Write Operation
b) Read Operation
=>Types of Files
a) Text Files
b) Binary Files
=>File Opening Opening Modes
1) r 2) w 3) a
4) r+ 5) w+ 6) a+
7) x 8) x+
=>Number of approaches to Open the File
a) By using open()
b) By using " with open() as "
=>Programming Examples
---------------------------------------------------------------------------------------------------------------
=>Pickling (Object Serialization) and Un-Pickling(Object De-Serialization) Concept
=>Implementation of Pickling and Un-Pickling Operations.
=>pickle module
=>Programming Examples
-----------------------------------------------------------------------------------------------------------------
=>Working with CSV Files and Operations
=>csv module
=>Implementation of csv operations with csv module
a) csv.reader
b) csv.writer
c) csv.DictReader
d) csv.DictWriter
=>Programming Examples
-----------------------------------------------------------------------------------------------------------------
=>Working OS Based Operations
=>os module
=>Implemenattion OS Based Operations with os Module
=>Programming Examples
=================================x======================================
===
=================================================
Types of Application in Files
=================================================
=>The purpose of Files in any programming language is that " To maintain Data Persistency".
=>The Process of storing the data permanently is called Data Persistency.
=>In this context, we can develop two types of applications. They are
1) Non-Persistant Applications
2) Persistant Applications
=>In Non-Persistant Applications development, we read the data from Keyboard , stored in main
memory(RAM) in the form of objects, processed and whose results displayed on Moniter.
Examples: ALL our previous examples comes under Non-Persistant Applications.

=>We know that Data stored in Main Memory(RAM) is temporary.

=>In Persistant Applications development, we read the data from Keyboard , stored in main
memory(RAM) in the form of objects, processed and whose results stored Permanently.
=>In Industry, we have two ways two store the Data Permanently. They are
1) By using Files
2) By Using RDBMS DataBase Softwares ( Oracle, MySQL, MongoDB, DB2,
PostgreySQL, SQL Server,SQLITE3..etc)
=================================x=====================================

============================================
Data Persistenecy by Using Files of Python
============================================
-------------------
Def. of File:
-----------------------------------------------------
=>A File is a collection of Records.
=>Files Resides in Secondary Memory(HDD).
=>Technically, File Name is a named location in Secondary Memory.
=>The purpose of Files is that "To get Data Persistency".
-----------------------------------------------------
=>All the objects data of main memory becomes records in File of Secondary memory and records of
file of secondary memory becomes the objects in main memory.
----------------------------------------------------
Def. of Stream:
----------------------------------------------------
=>The Flow of Data between object(s) of Main Memory and Files of Seconday memory is called
Stream.

==============================================
Operations on Files
==============================================
=>On the files, we can perform Two Types of Operations. They are
1) Write Operation
2) Read Operation.

1) Write Operation:
-----------------------------
=>The purpose of write operation is that " To transfer or save the object data of main memory as
record in the file of secondary memory".
=>Steps:
1) Choose the File Name
2) Open the File Name in Write Mode
3) Perform cycle of Write Operations.
=>While we are performing write operations, we get the following exceptions.
a) IOError
b) OSError
c) FileExistError
------------------------------
2) Read Operation:
------------------------------
=>The purpose of read operation is that " To transfer or read the record from file of secondary
memory into the object of main memory".
=>Steps
a) Choose the file name
b) Open the file name in Read Mode
c) Perform cycle of read operations.
=>While we performing read operations, we get the following exceptions.
a) FileNotFoundError
b) EOFError
================================x======================================

======================================================
Types of Files in Python
======================================================
=>In Python Programming, we have Two Types of Files. They are

1. Text Files
2. Binary Files
--------------------------------------------------------------------------------------------------------------------------
---------------
1. Text Files
--------------------------------------------------------------------------------------------------------------------------
---------------
=>Text Files are those which are containing Alphabets, Digits and Symbols.
=>Text Files are denoted by a Letter 't'
=>By Default Every File treated as Text File
=>Examples: .c, .cpp, .txt , .docx, .xlsx, .py...etc
--------------------------------------------------------------------------------------------------------------------------
---------------
2. Binary Files
--------------------------------------------------------------------------------------------------------------------------
---------------
=>Binary Files are those which are containing the data in the form of Binary
=>Binary Files are denoted by a Letter 'b'
=>Examples: All types of Image Files (.jpeg, .gif , .jpg , .png)
all types of audio , video files
--------------------------------------------------------------------------------------------------------------------------
---------------
========================================================
File Opening Modes in Python
========================================================
=>The purpose of File Opening Modes in Python is that "In which Mode we are opening the file.".
=>In Python programming, we have 8 File Opening Modes. They are
--------------------------------------------------------------------------------------------------------------------------
------------------
1. r
--------------------------------------------------------------------------------------------------------------------------
------------------
=>This Mode is Used for Opening the File in READ Mode and Performs read Operation only.
=>If we open the file name in "r" mode and if that file does not exist then we get FileNotFoundError.
=>The default file mode is "r".
--------------------------------------------------------------------------------------------------------------------------
------------------
2. w
--------------------------------------------------------------------------------------------------------------------------
------------------
=>This Mode is used for Creating a New File and opening that file in Write Mode and we can
perform
Write Operations.
=>If we Choose NEW File then that File Created and Opened In WRITE Mode and we can perform
Write Operations.
=>If we Choose EXISTING File then That File Opened In WRITE Mode and Existing Data
OVERLAPPED
with NEW Data.
--------------------------------------------------------------------------------------------------------------------------
------------------
3. a
--------------------------------------------------------------------------------------------------------------------------
------------------
=>This Mode is used for Creating a New File and opening that file in Write Mode and we can
perform
Write Operations.
=>If we Choose NEW File then that File Created and Opened In WRITE Mode and we can perform
Write Operations.
=>If we Choose EXISTING File then That File Opened In WRITE Mode and Existing Data
APPENDED with
NEW Data.
--------------------------------------------------------------------------------------------------------------------------
------------------
4. r+
--------------------------------------------------------------------------------------------------------------------------
------------------
=>This Mode is Used for Opening the File in READ Mode .
=>If we open the file name in "r+" mode and if that file does not exist then we get
FileNotFoundError
=>If we open the file name in "r+" mode then The file Opened in read Mode, First Performs Read
Operation and Later Performs Write Operation also.
--------------------------------------------------------------------------------------------------------------------------
------------------
5. w+
--------------------------------------------------------------------------------------------------------------------------
------------------
=>This Mode is used for Creating a New File and opening that file in Write Mode .
=>If we Choose NEW File then that File Created and Opened In WRITE Mode and we can perform
Write Operations.
=>If we Choose EXISTING File then That File Opened In WRITE Mode and Existing Data
OVERLAPPED
with NEW Data.
=>If we open File Name(New File OR Exitsing File) in "w+" then First We can perform Write
Operation and Later we can also Perform Read Operation.
--------------------------------------------------------------------------------------------------------------------------
------------------
6. a+
--------------------------------------------------------------------------------------------------------------------------
------------------
=>This Mode is used for Creating a New File and opening that file in Write Mode
=>If we Choose NEW File then that File Created and Opened In WRITE Mode
=>If we Choose EXISTING File then That File Opened In WRITE Mode and Existing Data
APPENDED with
NEW Data.
=>If we open File Name(New File OR Exitsing File) in "a+" then First We can perform Write
Operation
and Later we can also Perform Read Operation.
--------------------------------------------------------------------------------------------------------------------------
------------------
7. x
--------------------------------------------------------------------------------------------------------------------------
------------------
=>This Mode is used for Creating a New File and Opening the File Name eXclusively in Write
Mode and
we can perform Write Operations.
=>If we open the existing file name in "x" mode then we get FileExistError.
--------------------------------------------------------------------------------------------------------------------------
------------------
8. x+
--------------------------------------------------------------------------------------------------------------------------
------------------
=>This Mode is used for Creating a New File and Opening the File Name eXclusively in Write
Mode and
First we can perform Write Operations and Later we can also Perform Read Operation.
=>If we open the existing file name in "x+" mode then we get FileExistError.
=========================================x==============================
==============.

day --- 59

========================================================
Number of approaches to Open the files in Python
========================================================
=>To perform any type of Operation on Files, we must Open the File by using TWO Approaches.
They are

1. By using open().
2. By using "with open() as ".
--------------------------------------------------------------------------------------------------------------------------
-----------------
1. By using open().
--------------------------------------------------------------------------------------------------------------------------
-----------------
Syntax: varname=open("File Name","File Mode")
-------------
Explanation
-------------------
=>Varname represents an object pointing the file and it is called File Pointer and whose type is
<class, _io.TextIOWrapper>
=>open() is a pre-defined fucntion present in builtins module and It is used for Opening the Filename
in
Specified File Mode.
=>"FileName" represents Name of the file
=>"FileMode" represents r,w,a,r+,w+,a+,x,x+
=>Once we the file name with open() then It is Highly Recommended to Close the file by using
close() for
maintaining Consistency of File data (Manual Closing of the file).
=>hence open() does not provide auto-closeability of File.
--------------------------------------------------------------------------------------------------------------------------
-----------------
2. By using "with open() as ".
--------------------------------------------------------------------------------------------------------------------------
-----------------
=>Syntax: with open("File Name","File Mode") as Varname:
--------------------------------------------------------------
Block of Statements-Performs File Operations
-------------------------------------------------------------
-------------------------------------------------------------

------------------------------------------------------------------
Other Statements in program
------------------------------------------------------------------

Explanation:
------------------
=>"with" and "as" are the keywords
=>open() is a pre-defined fucntion present in builtins module and It is used for Opening the Filename
in
Specified File Mode.
=>"FileName" represents Name of the file
=>"FileMode" represents r,w,a,r+,w+,a+,x,x+
=>Varname represents an object pointing the file and it is called File Pointer and whose type is
<class, _io.TextIOWrapper>
=>The execution Process of "with open(---) as " is that "As Long as PVM present in side of " with
open(---) as " Indentation then File Name is actively Available and once PVM comes of " with
open(---) as" Indentation then File name closed Automatically and This Facility is Called Auto-
Closeability of File". No Need to close the file by using close() manually.

#Program demonstarting opening the files


#FileOpenEx1.py
try:
kvr=open("stud.data")
except FileNotFoundError:
print("File does not exist")
else:
print("\nType of kvr=",type(kvr))
print("File Opened in Read Mode Sucessfully")

#Program demonstarting opening the files


#FileOpenEx2.py
fp=open("stud.data","w")
print("\nType of fp=",type(fp))
print("File Opened in Write Mode Sucessfully")

#Program demonstarting opening the files


#FileOpenEx3.py
try:
with open("stud1.data") as fp:
print("File Opened in Read Mode")
print("Type of fp=",type(fp))
except FileNotFoundError:
print("File Does not Exist")

#Program demonstarting opening the files


#FileOpenEx4.py
with open("stud1.data","w") as fp:
print("File Opened in Write Mode")
print("Type of fp=",type(fp))

#Program demonstarting opening the files


#FileOpenEx5.py
with open("stud2.data","w") as fp:
print("-------------------------------------------------")
print("File Opened in Write Mode")
print("-------------------------------------------------")
print("File Name : ",fp.name)
print("File Opening Mode:",fp.mode)
print("Is this File Readable:",fp.readable())
print("Is this File Writable:",fp.writable())
print("Is this File closed:",fp.closed)
print("-------------------------------------------------")
print("---------------Out of with open() as --------")
print("Is this File closed:",fp.closed)

writwe program which will obtain internail information about the file such as filename ,filemode
readability rightability and closea bility

#Program demonstarting opening the files


#FileOpenEx6.py
try:
with open("stud2.data") as fp:
print("-------------------------------------------------")
print("File Opened in Write Mode")
print("-------------------------------------------------")
print("File Name : ",fp.name)
print("File Opening Mode:",fp.mode)
print("Is this File Readable:",fp.readable())
print("Is this File Writable:",fp.writable())
print("Is this File closed:",fp.closed)
print("-------------------------------------------------")
print("---------------Out of with open() as --------")
print("Is this File closed:",fp.closed)
except FilenotFoundError:
print("File does not exist")

#Program demonstarting opening the files


#FileOpenEx7.py
with open("stud2.data","a+") as fp:
print("-------------------------------------------------")
print("File Opened in Write Mode")
print("-------------------------------------------------")
print("File Name : ",fp.name)
print("File Opening Mode:",fp.mode)
print("Is this File Readable:",fp.readable())
print("Is this File Writable:",fp.writable())
print("Is this File closed:",fp.closed)
print("-------------------------------------------------")
print("---------------Out of with open() as --------")
print("Is this File closed:",fp.closed)

#Program demonstarting opening the files


#FileOpenEx8.py
try:
with open("stud3.data","x") as fp:
print("-------------------------------------------------")
print("File Opened in Write Mode")
print("-------------------------------------------------")
print("File Name : ",fp.name)
print("File Opening Mode:",fp.mode)
print("Is this File Readable:",fp.readable())
print("Is this File Writable:",fp.writable())
print("Is this File closed:",fp.closed)
print("-------------------------------------------------")
print("---------------Out of with open() as --------")
print("Is this File closed:",fp.closed)

except FileExistsError:
print("File already exist")

#Program demonstarting opening the files


#FileOpenEx9.py
try:
with open("kvr.data","x+") as fp:
print("-------------------------------------------------")
print("File Opened in Write Mode")
print("-------------------------------------------------")
print("File Name : ",fp.name)
print("File Opening Mode:",fp.mode)
print("Is this File Readable:",fp.readable())
print("Is this File Writable:",fp.writable())
print("Is this File closed:",fp.closed)
print("-------------------------------------------------")
print("---------------Out of with open() as --------")
print("Is this File closed:",fp.closed)

except FileExistsError:
print("File already exist")

which will demonstarte how to write data tio the file

==============================================
Writing the data to the Files
==============================================
=>To write the data to the file, we have Two Pre-defined functions Present in File pointer object.
They are
1) write()
2) writelines()
--------------------------------------------------------------------------------------------------------------------------
----------------------
1) write()
--------------------------------------------------------------------------------------------------------------------------
----------------------
=>Syntax: filepointerobj.write(str data)
=>This Function is used for Writing any type of data to the file in the form of str .
--------------------------------------------------------------------------------------------------------------------------
----------------------
2) writelines()
--------------------------------------------------------------------------------------------------------------------------
----------------------
=>Syntax: filepointerobj.writelines(Iterable object data)
=>This Function is used for Writing any type of Iterable object data to the file in the form of str .
--------------------------------------------------------------------------------------------------------------------------
----------------------
NOTE: write() and writelines() writes the data to file in the form of str by Value by Value But not all
at
Once. It is one of the time consuming Process.

#Program writing the data to the file


with open("vs.data","w") as fp:
fp.write(str(1000))
fp.write("Vivek")
fp.write(str(34.11))
print("Data Written to the file")

"""
fp.write("Guido van Rossum\n")
fp.write("FNO:3-4, Hill Side\n")
fp.write("Python Software Foundation\n")
fp.write("NL-56\n")
print("Data Written to the File")
"""

#Program writing the data to the file


#FileWriteEx2.py
with open("C:\\HYD\\addr1.data","a") as fp:
fp.write("Guido van Rossum\n")
fp.write("FNO:3-4, Hill Side\n")
fp.write("Python Software Foundation\n")
fp.write("Nether landas-56\n")
print("Data Written to the File")

#Program writing the data to the file


#FileWriteEx3.py
x={10:"Python",20:"Java",30:"C",40:"DS"}
with open("authors.data","a") as fp:
fp.writelines(str(x)+"\n")
print("Data Written to the file")

day – 60

==============================================
Reading the data from the Files
==============================================
=>To Read the data from the file, we have Two Pre-Defined Functions present in File Pointer object.
They are
1) read()
2) readlines()
--------------------------------------------------------------------------------------------------------------------------
------------------------
1) read()
--------------------------------------------------------------------------------------------------------------------------
------------------------
Syntax: varname=filepointer.read()
=>This Function is used for reading Entire Data of the file and Placed in LHS Varname and Its type is
<class,'str'>
--------------------------------------------------------------------------------------------------------------------------
------------------------
2) readlines()
--------------------------------------------------------------------------------------------------------------------------
------------------------
Syntax: varname=filepointer.readlines()
=>This Function is used for reading Entire Data of the file and Placed in LHS Varname and Its type
is <class,'list'>.

with open("addr1.data","r")as fp:


filedata=fp.readlines()
for fd in filedata:
print(fd,end="")

write a python program which will read the data dynamically from the keyboard and write to the file

#DynamicWriteEx1.py
with open("Hyd.info","a") as fp:
print("Enter Ur data from Key Board press @ to stop: ")
while(True):
kbddata=input()
if(kbddata!="@"):
fp.write(kbddata+"\n")
else:
break
print("Data written to the file")

write a python priogram which will copy the content one file into another file

#FileCopy.py
srcfile=input("Enter Source File:")
try:
with open(srcfile,"r") as rp:
dstfile=input("Enter Destination File:")
with open(dstfile,"a") as wp:
srcdata=rp.read() # Reading the data from SRC File
wp.write(srcdata)# Wrtinh the SRC File Data to dest File
print("File Copied--Verify")
except FileNotFoundError:
print("Source File Does not Exist:")

=================================================
Pickling and Un-Pickling
(OR)
Object Serialization or Object De-Serialization
=================================================
--------------
Pickling ( Object Serialization)
--------------
=>Let us assume there exist an object which contains multiple values. To save or write an object data
of
main memory into the file of secondary memory by using write() and writelines() , they transfers
the values in the form of value by value and it is one of the time consuming process( bcoz of multiple
write operations).
=>To Overcome this time consuming process, we must use the concept of Pickling.
=>The advantage of pickling concept is that with single write operation , we can
save or write entire object data of main memory into the file of secondary memory.
----------------------------------
=>Definition of Pickling:
---------------------------------
=>The Process of saving or transfering entire object content of main memory into the file of
secondary memory by performing single write operation is called Pickling.
=>Pickling concept participates in Write Operations.
-----------------------------------------------------------
Steps for implementing Pickling Concept:
-----------------------------------------------------------
=>import pickle module, here pickle is one of the pre-defined module
=>Choose the file name and open it into write mode.
=>Create an object with collection of values (Iterable object)
=>use the dump() of pickle module. dump() save the content of any object into the
file with single write operation.
Syntax: pickle.dump(object , filepointer)
=>NOTE That pickling concept always takes the file in Binary Format.
--------------------------------------------------------------------------------------------------------------------------
----------------------
Un-Pickling (Object De-Serialization)
--------------------------------------------------------
=>Let us assume there exists a record with multiple values in a file of secondary memory. To read or
transfer the entire record content from file of secondary memory, if we use read(), readlines() then
they read record values in the form of value by value and it is one of the time consuming
process( bcoz of multiple read operations).
=>To overcome this time consuming process, we must use the concept of Un-pickling.
=>The advantange of Un-pickling is that with single read operation, we can read entire record content
from the file of secondary memory into the object of main memory.
--------------------------------------------
=>Definition of Un-Pickling:
--------------------------------------------
=>The process of reading or transfering the entire record content from file of secondary memory into
the object of main memory by performing single read operation is called Un-pickling.
=>Un-Pickling concept participates in Read Operations.
--------------------------------------------------------------------------------------------------------------
Steps for implementing Un-Pickling Concept:
----------------------------------------------------------------------------------------------------------------
=>import pickle module
=>Choose the file name and open it into read mode.
=>Use the load() of pickle module. load() is used for transfering or loading the
entire record content from file of secondary memory into object of main memory.
Syntax: objname=pickle.load(filepointer)
=>NOTE That Un-pickling concept always takes the file in Binary Format.
--------------------------------------------------------------------------------------------------------------------------
---------------------.

write a python program which will read the student data from the keyboard and save as a record in
your file

write a python program which will read the student record from the file

#StudPickEx1.py-----Program-A
import pickle
def saverecord():
with open("stud.pick","ab") as fp:
while(True):
#read student values from KBD
print("----------------------------------")
sno=int(input("Enter Student Number:"))
sname=input("Enter Student Name:")
marks=float(input("Enter Student marks:"))
#create an empty list and add student values
l=list()
l.append(sno)
l.append(sname)
l.append(marks)
#save list object content as a record to the file
pickle.dump(l,fp)
print("----------------------------------")
print("Student Data Saved as Record:")
print("----------------------------------")
ch=input("Do u want to insert another Record(yes/no):")
if(ch.lower()=="no"):
break
#main program
saverecord()

#StudUnPickEx1.py---Program-B
import pickle
try:
with open("C:\\Users\Kvr\\PycharmProjects\\6pmfiles1\\stud.pick","rb") as fp:
print("--------------------------")
while(True):
try:
obj=pickle.load(fp)
for val in obj:
print("{}".format(val),end="\t")
print()
except EOFError:
print("--------------------------")
break
#Lots of code
except FileNotFoundError:
print("File does not exist")

write a python program which will copy and image

#ImageCopy.py
try:
with open("C:\HYD\human.png","rb") as rp:
with open("programmer.png","wb") as wp:
srcdata=rp.read() # Reading the data from SRC File
wp.write(srcdata)# Wrtinh the SRC File Data to dest File
print("Image File Copied--Verify")
except FileNotFoundError:
print("Source File Does not Exist:")

write a python program which will read employee details from the keyboard and save the name as a
record by using pickling

write a python program which will read the employee file by using unpickiling operation

write a python program which demonstrate random access file

#RandomAccessFile.py
with open("addr1.data","r") as fp:
print("----------------------------")
print("Initial Pos of fp=",fp.tell()) # 0
filedata=fp.read(5)
print("File Data=",filedata)
print("Now Pos of fp=", fp.tell()) # 5
filedata = fp.read(8)
print("File Data=", filedata)
print("Now Pos of fp=", fp.tell()) # 13
print("----------------------------")
filedata=fp.read()
print("File Data=", filedata)
print("Now Pos of fp=", fp.tell())
print("----------------------------")
fp.seek(6) # we reset fp to 6th index
filedata = fp.read(7)
print("File Data=", filedata)
print("Now Pos of fp=", fp.tell()) # 13
print("----------------------------")
filedata = fp.read()
print("File Data=", filedata)

day - 61
================================================
Working with CSV Files in Python
================================================
=>CSV stannds for Comma Separated Values.
=>A CSV File is one of the is a simple file format used to store tabular data, such as a
spreadsheet or database.
=>A CSV file stores tabular data (numbers and text) in plain text.
=>Each line of the CSV file is a data record. Each record consists of one or more fields,
separated by commas.
=>Python provides an in-built module called csv to work with CSV files.
=>There are 2 classes provided by this module for writing the data to CSV File. They are
1) By using Using csv.writer class object
2) By Using csv.DictWriter class object
=>There are 2 classes provided by this module for Reading the data from CSV File. They are
1) By using Using csv.reader class object
2) By Using csv.DictReader class object
-----------------------------------------------------------------------
1) By using Using csv.writer class object
------------------------------------------------------------------------
=>The csv.writer class object is used to insert data to the CSV file.
=>To create an object of "csv.writer" class object, we use writer() and present in csv module.
=>"csv.writer" class object provides two Functions for writing to CSV file.
=>They are
1) writerow()
2) writerows()

1) writerow(): This method writes a single row at a time.


Field row can be written using this method.
Syntax:- csvwriterobj.writerow(fields Row / Data Row)
2) writerows(): This method is used to write multiple rows at a time.
This can be used to write rows list.
Syntax: Writing CSV files in Python
csvwriterobj.writerows(data rows)
here data rows can be list tuple set,frozenset only
--------------------------------------------------------------------------------------------------------------
2) By Using csv.DictWriter class object
---------------------------------------------------------------
=>The "csv.DictWriter" class object is used to insert dict data to the CSV file.
=>To create an object of "csv.DictWriter" class object, we use DictWriter() and present in csv
module.
=>"csv.DictWriter" class object provides two Functions for writing to CSV.
1) writeheader()
2) writerows()
------------------------
1) writeheader():
------------------------
=>writeheader() method simply writes the first row of your csv file using the pre-specified
fieldnames.
Syntax: DictWriterObj.writeheader()
----------------------------------------------------------
2) writerows():
------------------------
=>writerows() method simply writes all the values of (Key,Value) from dict object in the form of
separate rows[ Note: it writes only the values(not keys) ]
Syntax:- DictWriterObj.writerows(dictobject)
--------------------------------------------------------------------------------------------------------------------------
-----
Reading the data from CSV File
--------------------------------------------------------------------------------------------------------------------------
----
=>There are various ways to read a CSV file that uses either the CSV module or the pandas
library.
=>The csv Module provides classes for reading information from CSV file .
1) csv.reader
2) csv.DictReader
--------------------------
1) csv.reader():
--------------------------
=>This Function is used for creating an object of "csv.reader" class and It helps us to read the data
records from csv file.
=>Syntax:- csvreaderobj=csv.reader(filepointer)

-------------------------------------------------------------------------------------
2) csv.DictReader():
-----------------------------------
=>This Function is used for creating an object of "csv.DictReader" class and It helps us to read the
data from csv file where it contains dict data(Key,Value).
=>Syntax:- csvdictreaderobj=csv.DictReader(filepointer)
------------------------------------------------------------------------------------------------------------------

#Program for Reading the data from CSV File by using File Pointer (Normal
Files)
#Non-CsvEx1.py
try:
with open("stud.csv","r") as fp:
print("----------------------------------------------")
filedata=fp.read()
print(filedata)
print("----------------------------------------------")
except FileNotFoundError:
print("File does not exist")

#Program for Reading the data from CSV File by using CSV Module
#CsvReaderEx1.py----csv.reader()---Gives an object csv.reader class object
import csv
try:
with open("stud.csv","r") as fp:
print("----------------------------------------------")
csvr=csv.reader(fp) # here csvr is an object of <class, _csv.reader>
for record in csvr:
for val in record:
print("{}".format(val),end="\t")
print()
print("----------------------------------------------")
except FileNotFoundError:
print("File does not exist")

#Program for Reading the data from CSV File by using CSV Module
#CsvReaderEx2.py----csv.reader()---Gives an object csv.reader class object
import csv
try:
with open("emp.csv","r") as fp:
print("----------------------------------------------")
csvr=csv.reader(fp) # here csvr is an object of <class, _csv.reader>
for record in csvr:
for val in record:
print("{}".format(val),end="\t")
print()
print("----------------------------------------------")
except FileNotFoundError:
print("File does not exist")

#Program for creating CSV File by Python Program with csv module
#CsvWriteEx1.py-----csv.writer() gives an object of <class, _csv.Writer>
import csv # Step-1
hnames=["empno","ename","sal","dsg"] # Step-2
records=[ [10,"RS",3.4,"Author"],
[20,"TR",4.4,"Scientist"],
[30,"DR",1.4,"SE"],
[40,"ST",2.4,"TL"],
[50,"GS",1.4,"HR"] ] # Step-3
with open("emp.csv","a") as fp: # Step-4
csvwr=csv.writer(fp) # Step-5--here csvwr is an object of <class, _csv.writer>
#Here write Header names to the csv file---writerow() present in object of <class,
_csv.writer>
csvwr.writerow(hnames) # Step-6
#Write the rercords which are in the form nested list--writerows()
csvwr.writerows(records) # Step-7
print("CSV File Created and Verify")

#Program for adding Record to CSV File by Python Program with csv module
#CsvWriteEx2.py-----csv.writer() gives an object of <class, _csv.Writer>
import csv # Step-1
record=[60,"KVR",0.0,"Trainer"]
with open("emp.csv","a") as fp:
csvwr=csv.writer(fp)
csvwr.writerow(record)
print("Recod Saved in a File:")

#Program for adding Record to CSV File by Python Program with csv module
#CsvWriteEx3.py-----csv.writer() gives an object of <class, _csv.Writer>
import csv # Step-1
with open("emp.csv","a") as fp:
while(True):
print("----------------------------------------------------")
#accept the employee values from KBD
eno=int(input("Enter Employee Number:"))
ename=input("Enter Employee Name:")
sal=float(input("Enter Employee Salary:"))
dsg=input("Enter Employee Desgination:")
#create an empty list
lst=list()
#append employee Data to list object
lst.append(eno)
lst.append(ename)
lst.append(sal)
lst.append(dsg)
#create an object ccsv.Writer object
csvwr=csv.writer(fp)
#write record data to csv file---writerow()
csvwr.writerow(lst)
print("Recod Saved in a File:")
print("----------------------------------------------------")
ch=input("Do u want to insert another Record(yes/no):")
if(ch.lower()=="no"):
break

#Program for Reading the data from CSV File by using CSV Module in the form Dict
#CsvDictReaderEx1.py
import csv
with open("emp.csv","r") as fp:
csvdr=csv.DictReader(fp) # here csvdr is an object of type <class, csv.DictReader>
for drdata in csvdr:
for k,v in drdata.items():
print("\t{}--->{}".format(k,v))
print("------------------------------------------")

#Program for Reading the data from CSV File by using CSV Module in the form Dict
#CsvDictReaderEx2.py
import csv
with open("stud.csv","r") as fp:
csvdr=csv.DictReader(fp) # here csvdr is an object of type <class, csv.DictReader>
for drdata in csvdr:
for k,v in drdata.items():
print("\t{}--->{}".format(k,v))
print("------------------------------------------")

jupyter

import pandas as pd
df=pd.read_csv(“d:\\KVR-python-6pm\\csvemp.csv”)

#Program for creating CSV File by Python Program with csv module where the data is available in
the form of dict
#CsvDictWriteEx1.py
import csv # Step-1
hname=["HTNO","NAME","BRANCH","CGPA"] # step-2
records=[ {"HTNO":100,"NAME":"VIVEK","BRANCH":"CSE","CGPA":8.0},
{"HTNO":200,"NAME":"NARESH","BRANCH":"ECE","CGPA":7.8},
{"HTNO":300,"NAME":"DINESH","BRANCH":"EEE","CGPA":8.1},
{"HTNO":400,"NAME":"AMOL","BRANCH":"IT","CGPA":7.7},
{"HTNO":500,"NAME":"SUJITH","BRANCH":"MECH","CGPA":8.3}] #
Step-3
with open ("univstud.csv","a") as fp: # Step-4
csvwdr=csv.DictWriter(fp,fieldnames=hname) # Step-5
csvwdr.writeheader() # # Step-6
csvwdr.writerows(records) # # Step-7
print("Dict Data Saved as records in CSV File:")

day --- 62

===========================================
os module
===========================================
=>In Python, "os" is one pre-defined module.
=>The purpose of os module is that "To perform some os related oprations"
=>The Os based operations are
1) Creating Folder / Directory. (mkdir() )
2) Creating Folders Hierarchy. (makedirs() )
3) Removing Folder / Directory. (rmdir() )
4) Removing Folders Hierarchy. (removedirs() )
5) Removing File Name from Folder( remove() )
6) Renaming a Folder/File Name. (rename())
7) List the file names in folder ( listdir() )

--------------------------------------------------------------------------------------------
1) Creating Folder / Directory
--------------------------------------------------------------------------------------------
=>For Creating a Folder / Directory, we use mkdir().
=>Syntax: os.mkdir("Folder Name")
=>if the folder name already exist then we get FileExistsError
=>mkdir() can create only one folder at a time and if we try to create folderS hierarchy then
we get FileNotFoundError.
=>in mkdir(), if we specify any folder name with escape sequence ( \n \u \digits,\t..etc) then
we get OSError.

Examples:
----------------
#Program for Creating Folder / Directory
#mkdirex.py
import os
try:
os.mkdir("D:\suraj\python\7am")
print("Folder Created Successfully-verify")
except FileNotFoundError:
print("mkdir() can create only one folder at a time")
except FileExistsError:
print("The specified folder already exist")
except OSError:
print("Check ur path of folder names")
------------------------------------------------------------------------------------------------------------
2) Creating Folders Hierarchy.
-----------------------------------------------------------------------------------------------------------
=>For Creating Folders Hierarchy, we use makedirs().
=>Syntax: os.makedirs("Folders Hierarchy")
=>Here Folders Hierarchy represent Root Folder\sub folder\sub-sub folder so on...
=>if the folder name already exist then we get FileExistsError
=> if we specify any folder name with escape sequence ( \n \u \digits,\t..etc) then
we get OSError.

Examples:
---------------
#Program for Creating Folders Hierarchy
#makedirsex.py
import os
try:
os.makedirs("D:\\India\\Hyd\\ampt\\python\\python")
print("Folder Created Successfully-verify")
except FileExistsError:
print("The specified folder already exist")
except OSError:
print("Check ur path of folder names")
----------------------------------------------------------------------------------------------------------
3) Removing Folder / Directory.
----------------------------------------------------------------------------------------------------------
=>For Removing Folder / Directory, we use rmdir()
=>syntax: os.rmdir("folder name")
=>rmdir() can remove folder name provided folder name is empty.
=>if we specify any folder name with escape sequence ( \n \u \digits,\t..etc) then
we get OSError.
-------------------------------------------------------------------------------
#Program for Removing Folder / Directory
#rmdirex.py
import os
try:
os.rmdir("D:\KVR")
print("Folder removed Successfully-verify")
except FileNotFoundError:
print("folder name does not exist")
except OSError:
print("rmdir() can remove those foilder which are empty--check ur path")
----------------------------------------------------------------------------------------------------------
4) Removing Folders Hierarchy. (removedirs() )
----------------------------------------------------------------------------------------------------------
=>For Removing Removing Folders Hierarchy, we use removedirs()
=>Syntax: os.removedirs("Folders Hierarchy")
=>Here Folders Hierarchy represent Root Folder\sub folder\sub-sub folder so on...
=>if the folder name not exist then we get FileNotFoundError
=> if we specify any folder name with escape sequence ( \n \u \digits,\t..etc) then
we get OSError.
--------------------------
Examples
-------------------------
#Program for Removing Folders Hierarchy
#removedirsex.py
import os
try:
os.removedirs("D:\\India\\Hyd\\ampt\\python\\python")
print("Folders Hierarchy Removed Successfully-verify")
except FileNotFoundError:
print("The specified folders hierachy does exist")
except OSError:
print("remove those folder which are empty-Check ur path of folder names")
---------------------------------------------------------------------------------------------------
5) Removing File Name from Folder.
---------------------------------------------------------------------------------------------------
=>To remove the file name from folder, we use remove()
=>Syntax: os.remove("Absolute Path of File Name")
=>If the file name does not exist then we get FileNotFoundError
-----------------
Examples
-----------------
#Program for removing the file name from folder
#RemoveFileEx.py
import os
try:
os.remove("E:\KVR-PYTHON-7AM\MODULES\SE3.py")
print("File Name removed Sucessfully")
except FileNotFoundError:
print("File does not exist")

---------------------------------------------------------------------------------------------------
6) Renaming a Folder/File Name.
---------------------------------------------------------------------------------------------------
=>To rename a folder, we rename()
=>Syntax: os.rename("Old Folder Name","New Folde Name")
=>Syntax: os.rename("Old Folder Name","New Folde Name")
=>If the Old Folder Name does not exist then we get FileNotFoundError.
----------------
Examples
------------------
#Program for renaming a folder anme
#RenameFolderEx.py
import os
try:
os.rename("D:\KVR","D:\PYTHON")
print("Folder Name renamed")
except FileNotFoundError:
print("File does not exist")
---------------------------------------------------------------------------------------------------
7) List the file names in folder.
---------------------------------------------------------------------------------------------------
=>To list the file names in folder, we use listdir()
=>Syntax: os.listdir("Absolute Path of Folder Name")
=>If the Folder Name does not exist then we get FileNotFoundError.
------------------
Examples:
------------------
#Program for Listing files ijn folder
#ListFileFolderEx.py
import os
try:
FolderName=input("Enter Folder name to list files:")
fileslist=os.listdir(FolderName)
print("-"*50)
print("List of Files:")
print("-"*50)
for filename in fileslist:
print("\t{}".format(filename))
print("-"*50)
except FileNotFoundError:
print("Folder does not exist")

import os
try:
os.mkdir(“kvr”)
print(“folder create sucessfully”)
except fileexistserror:
print(“folder allready access)

#Program for creating a Folder---mkdir()


#CreateFolderEx1.py
import os
try:
os.mkdir("C:\\BANG\\PYTHON")
print("Folder Created Sucessfully ")
except FileNotFoundError:
print("Root Folder Does not Exist")
except FileExistsError:
print("Folder already Exist")

#Program for creating a Folders Hierarchy---makedirs()


#CreateFoldersHierarchyEx1.py
import os
try:
os.makedirs("C:\\BANG")
print("Folders hierarchy Created--verify")
except FileExistsError:
print("Folders hierarchy already Exist")

#program for removing a Folder--rmdir()


#RemoveFolderEx1.py
import os
try:
os.rmdir("C:\INDIA\HYD\AMPT\PYTHON\KVR")
print("Folder Removed Successfully --veriry")
except FileNotFoundError:
print("Folder Does not Exist")
except OSError:
print("Folder is not empty--plz Check")

#program for removing a Folders Hierarchy--removedirs()


#RemoveFoldersHierarchyEx1.py
import os
try:
os.removedirs("C:\INDIA\HYD\AMPT\python")
print("Folder Removed Successfully --veriry")
except FileNotFoundError:
print("Folder(s) hierarchy Does not Exist")
except OSError:
print("Folder is not empty--plz Check")

#Program for removing a File Name


#FileRemoveEx1.py
import os
try:
os.remove("D:\KVR-PYTHON-6PM\FILES\stud1.data")
print("File Removed Sucessfully--Verify")
except FileNotFoundError:
print("File does not exist")
#Program renaming a File--rename()
#RenameFileEx1.py
import os
try:
os.rename("D:\KVR-PYTHON-6PM\FILES\student2.data","D:\KVR-PYTHON-6PM\FILES\
stud2.data")
print("File Name re-named--verify")
except FileNotFoundError:
print("File does not exist")

#Program for Listing the files in the folder---listdir()


#ListFilesEx1.py
import os
try:
fileslist=os.listdir("D:\KVR-PYTHON-6PM\FILES")
print("------------------------------------------")
print("List of Files :")
print("Number of Files={}".format(len(fileslist)))
print("------------------------------------------")
for filename in fileslist:
print("\t{}".format(filename))
print("------------------------------------------")
except FileNotFoundError:
print("Folder does not exist")

#Program for Listing the Python files(.py) in the folder---listdir()


#ListFilesEx2.py
import os
try:
fileslist=os.listdir("D:\KVR-PYTHON-6PM\FILES")
print("------------------------------------------")
print("List of Files :")
nop=0
print("Number of Files={}".format(len(fileslist)))
print("------------------------------------------")
for filename in fileslist:
if(filename[-3:]==".py"):
print("\t{}".format(filename))
nop=nop+1
print("------------------------------------------")
print("Number of Python File={}".format(nop))
print("------------------------------------------")
except FileNotFoundError:
print("Folder does not exist")

#Program for Listing the Python files(.py) in the folder---listdir()


#ListFilesEx3.py
import os
try:
foldername=input("Enter the Folder Name:")
fileslist=os.listdir(foldername)
print("------------------------------------------")
print("List of Files :")
nop=0
print("Number of Files={}".format(len(fileslist)))
print("------------------------------------------")
for filename in fileslist:
print("\t{}".format(filename))
print("------------------------------------------")
except FileNotFoundError:
print("Folder does not exist")

Day=63

=================================
generator in python
=================================
=>generator is one of the function
=>The generator function always contains yield keyword
=>If the function contains return statement then it is called Normal Function. Here return
statement of function can return More Number of Values if required
=>If the function contains yield keyword then it is called generator. Here yield statement
returns the value only on demand and reduces the memory space.
=>Syntax:
def function_name(start,stop,step):
----------------------------------------
----------------------------------------
yield value
----------------
=>The 'yield' key word is used for giving the value back to function call from function defintion and
continue the function execution until condition becomes false.
=>The advantage of generators over functions concept is that it save lot of memory space in the case
large sampling of data. In otherwords Functions gives all the result at once and it take more memory
space where as generators gives one value at a time when programmer requested and takes minimized
memory space.
========================X===================================.

#Non-GenEx1.py
r=range(10,100,5)
for val in r:
print(val)

#GenEx1.py
def kvrrange(Val):
i=0
while(i<Val):
yield i
i=i+1

#main program
g=kvrrange(5) # here 'g' is an object of <class,'generator'>
print("Content of g=",g)
print("------------------------------------------------")
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
#print(next(g))----This statement generates StopIteration bcoz generates yielded all the demanded
values

#GenEx2.py
def kvrrange(Val):
i=0
while(i<=Val):
yield i
i=i+1

#main program
g=kvrrange(10) # here 'g' is an object of <class,'generator'>
print("Content of g=",g)
print("------------------------------------------------")
while(True):
try:
print(next(g))
except StopIteration:
print("------------------------------------------------")
break
#GenEx3.py
def kvrrange(Begin,End):
while(Begin<=End):
yield Begin
Begin+=1 # here += is called Short Hand Operator

#main program
g=kvrrange(10,20) # here 'g' is an object of <class,'generator'>
print("Content of g=",g)
print("------------------------------------------------")
while(True):
try:
print(next(g))
except StopIteration:
print("------------------------------------------------")
break
print("=====================================")
g1=kvrrange(100,120) # here 'g1' is an object of <class,'generator'>
print("------------------------------------------------")
while(True):
try:
print(next(g1))
except StopIteration:
print("------------------------------------------------")
break

#GenEx4.py
def kvrrange(Begin,End,Step):
while(Begin<=End):
yield Begin
Begin+=Step # here += is called Short Hand Operator

#main program
g=kvrrange(10,20,2) # here 'g' is an object of <class,'generator'>
print("Content of g=",g)
print("------------------------------------------------")
while(True):
try:
print(next(g))
except StopIteration:
print("------------------------------------------------")
break
print("=====================================")
g1=kvrrange(1000,1050,10) # here 'g1' is an object of <class,'generator'>
print("------------------------------------------------")
while(True):
try:
print(next(g1))
except StopIteration:
print("------------------------------------------------")
break

#GenEx5.py
def getcourses():
yield "PYTHON"
yield "JAVA"
yield "DSA"
yield "DSc"

#main program
crs=getcourses() # here crs is of type <class,'generator'>
print(next(crs))
print(next(crs))
print(next(crs))
print(next(crs))

========================
Iterators in Python
========================
------------------------------------------------------
Why should WE use Iterators:
------------------------------------------------------
=>In modern days, we have a lot of data in our hands, and handling this huge amount of data creates
problems for everyone who wants to do some sort of analysis with that data.So, If you’ve ever
struggled with handling huge amounts of data, and your machine running out of memory, then WE
use the concept of Iterators in Python.
=>Therefore, Rather than putting all the data in the memory in one step, it would be better if we
could work with it in bits or some small chunks, dealing with only that data that is required at that
moment. As a result, this would reduce the load on our computer memory tremendously. And this is
what exactly the iterators do.
=>Therefore, you can use Iterators to save a ton of memory, as Iterators don’t compute their items
when they are generated, but only when they are called upon.
----------------------------------------------------------------------------------------------------------
=>Iterator in python is an object that is used to iterate over iterable objects like lists, tuples, dicts, str,
and sets.
=>The iterator object is initialized using the iter() Function. It uses the next() Function for iteration.
=>Here iter() is used for converting Iterable object into Iterator object.
=>next() is used for obtaining next element of iterator object and if no next element then we get an
exception called StopIteration.
=>On the object of Iterator, we can't perform Indexing and Slicing Operations bcoz They supply the
value on demand .
--------------------------
Examples:
--------------------------
s = 'Python'
itobj = iter(s)
while True:
try:
item = next(s) # Iterate by calling next
print(item)
except StopIteration: # exception will happen when iteration will over
break
======================================================
mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)
print(next(myit))
print(next(myit))
print(next(myit))

lsst=[10,20,30,40,50,60,70,80,90]

lstir =itr(lst)
print(lst)
print(lsitr)

#IterEx1.py
lst=[10,20,30,40,50,60,70,80,90] # here lst is one of the Iterable object
#Convert Iterable object into Iterator object by using iter(Iterable object)
lstiter=iter(lst)
print("-----------------------------------------------------------")
print("Type of lst=",type(lst)) # <class,list>
print("Type of lstiter=",type(lstiter)) #<class, list_iterator>
print("-----------------------------------------------------------")
print(next(lstiter))
print(next(lstiter))
print(next(lstiter))
while(True):
try:
print(next(lstiter))
except StopIteration:
print("-----------------------------------------------------------")
break

#IterEx2.py
tpl=(10,"Rossum",45.67,True,2+3j) # here tpl is one of the Iterable object
#Convert Iterable object into Iterator object by using iter(Iterable object)
tpliter=iter(tpl)
print("-----------------------------------------------------------")
print("Type of tpl=",type(tpl)) # <class,tuple>
print("Type of tpliter=",type(tpliter)) #<class, tuple_iterator>
print("-----------------------------------------------------------")
while(True):
try:
print(next(tpliter))
except StopIteration:
print("-----------------------------------------------------------")
break

#IterEx3.py
sets={10,"Rossum",45.67,True,2+3j} # here tpl is one of the Iterable object
#Convert Iterable object into Iterator object by using iter(Iterable object)
setsiter=iter(sets)
print("-----------------------------------------------------------")
print("Type of sets=",type(sets)) # <class,set>
print("Type of setsiter=",type(setsiter)) #<class, set_iterator>
print("-----------------------------------------------------------")
while(True):
try:
print(next(setsiter))
except StopIteration:
print("-----------------------------------------------------------")
break

#IterEx4.py
d={10:"Python",20:"Dsc",30:"Java",40:"DSA",50:"C++"} # here tpl is one of the Iterable object
#Convert Iterable object into Iterator object by using iter(Iterable object)
diter=iter(d)
print("-----------------------------------------------------------")
print("Type of d=",type(d)) # <class,dict>
print("Type of diter=",type(diter)) #<class, dict_keyiterator>
print("-----------------------------------------------------------")
while(True):
try:
k=next(diter)
v=d[k] # OR v=d.get(k)
print("\t{}--->{}".format(k,v))
except StopIteration:
print("-----------------------------------------------------------")
break

#IterEx5.py
d={10:"Python",20:"Dsc",30:"Java",40:"DSA",50:"C++",60:"C"} # here tpl is one of the Iterable
object
#Convert Iterable object into Iterator object by using iter(Iterable object)
diter=iter(d)
print("-----------------------------------------------------------")
print("Type of d=",type(d)) # <class,dict>
print("Type of diter=",type(diter)) #<class, dict_keyiterator>
print("-----------------------------------------------------------")
for k in diter:
print("\t{}===>{}".format(k,d.get(k)))
print("-----------------------------------------------------------")
print("---------------------OR--------------------------------------")
diter=iter(d) # Re-building Dictdict_keyiterator
for k in diter:
print("\t{}===>{}".format(k,d[k] ))
print("-----------------------------------------------------------")

#IterEx6.py
s="PYTHON"
#Convert Iterable object into Iterator object by using iter(Iterable object)
siter=iter(s)
print("-----------------------------------------------------------")
print("Type of s=",type(s)) # <class,str>
print("Type of siter=",type(siter)) #<class, str_iterator>
print("-----------------------------------------------------------")
for val in siter:
print("\t{}".format(val))
print("-----------------------------------------------------------")

#IterEx7.py
r=range(10,100,10)
#Convert Iterable object into Iterator object by using iter(Iterable object)
riter=iter(r)
print("-----------------------------------------------------------")
print("Type of r=",type(r)) # <class,range>
print("Type of riter=",type(riter)) #<class,range_iterator>
print("-----------------------------------------------------------")
for val in riter:
print("\t{}".format(val))
print("-----------------------------------------------------------")

#IterEx2.py
tpl=(10,"Rossum",45.67,True,2+3j) # here tpl is one of the Iterable object
#Convert Iterable object into Iterator object by using iter(Iterable object)
tpliter=iter(tpl)
print("-----------------------------------------------------------")
print("Type of tpl=",type(tpl)) # <class,tuple>
print("Type of tpliter=",type(tpliter)) #<class, tuple_iterator>
print("-----------------------------------------------------------")
while(True):
try:
print(next(tpliter))
except StopIteration:
print("-----------------------------------------------------------")
break

day -64

python database

index:

= limitation of file or streams


= advantages of database softwares
= purpose of python database communication (pdbc)
setup of database module in python
– steps for deeloping python database communicaton (PDBC) applications
– type of queries
1. ddl queries
2. dml queries
3. drl queries

executing ddl queries through python programmer

– programming examples
meta data programming in python
– programming examples

case studies
--------------.

=======================================================
Python Database Communication (PDBC)-4 days(Oracle)+1 MySQL
=======================================================
Index
--------------
=>Limtation of File OR Streams
=>Advantages of Database Softwares
=>Purpose of Python Database Communication (PDBC)
=>Setup of Database Modules in Python
=>Steps for developing Python Database Communication (PDBC) Applications
=>Types of Queries
a) DDL Queries
b) DML Queries
c) DRL Queries
=>Executing DDL Queries through Python Program
=>Programming Examples
=>Executing DML Queries through Python Program
=>Programming Examples
=>Executing DRL Queries through Python Program
=>Programming Examples
=>Meta-Data Programming in Python
=>Programming Examples
-----------------------------------------------------------------
Case Studies

limitations of file s or streams – data presistancy

1. files does not contain security --- not providing user name and password
2. files does not contains col names and processing becomes difficiuilt
3. to locate the data in the file we must use indexing operations
4. files are unable to store large col of data
5. file arch differs from one os to another os – file and os development

to overcome these problems to files – we use any rdbms datbase


softwares – oracle ,mysql –etc

database – to store the data perminantely

example --- oracle ,mysql etc


import pydoc
print(pydoc.__file__)

=============================================
Python DataBase Communication ( PDBC )
=============================================
=>Even we acheived the Data Persistency by using Files, Files has the following Limitations.

1. Files of any language does not contain security bcoz Files are unable to provide
security in the form of User Name and Password.
2. Files are unable to store large amount of data
3. File are differing from One OS to another OS (Files are OS depenedent)
4. Querying and Processing the data from Files is Very Complex bcoz file data is
organized w.r.t Indices and idenfying the indices is very complex.
5. Files does not contain Column Names (Except CSV Files) and complex to Process the data

=>To Overcome the limitation of files and to acheive the Data Persistency, we must use the concept
of any RDBMS DataBase Softwares ( Oracle, MYSQL, Mongo DB, DB2, SQL Server, Postgey SQL,
SQLITE3...........etc).

1. All RDBMS DataBase Softwares Provides Security bcoz RDBMS DataBase


Softwares considers User names and Password.
2. All RDBMS DataBase Softwares stores large amount of data
3. All RDBMS DataBase Softwares Arch Remains Same on all types of OSes ( OS
Independent)
4. Querying and Processing the data from All RDBMS DataBase Softwares is Very
Simple
bcoz data of All RDBMS DataBase Softwares oranganized records in the form of
Tables with Column Names.
5. The Data Present in any RDBMS DataBase Softwares oranganized in the of Tables
with
Column Names makes the processing Easy.

=>If Python Program want to communicate with any RDBMS DataBase Softwares then we must use
a PRE-DEFINED MODULE and such PRE-DEFINED MODULE does not exist in Python
Software.
=>Some Third Party Software Vendors( Ex: "Anthony Tuininga") developed a Module for Python
Programmers to communicate with RDBMS DataBase Softwares and placed in github and Third
Party Software Modules must be installed.
=>To install any Third Party Software Modules in python , we use a tool called pip and it is present
in C:\Users\KVR\AppData\Local\Programs\Python\Python310\Scripts folder.

=>Syntax : pip install Module Name (at any Windows command prompt)

=>If Python Program want to communicate with Oracle Database, then we must install
cx_Oracle Module.
=>Examples : pip install cx_Oracle

=>If Python Program want to communicate with MySQL Database, then we must install
mysql-connector or mysql-connector-python Module.

=>Examples : pip install mysql-connector


=>Examples : pip install mysql-connector-python
====================================x====================.

pip install pyodbc

Steps for developing Python Database Communication Application With Oracle

====================================================================
=>If Python Program want to Communicate with any RDBMS Softwares Like Oracle then we follow
Certain Steps. They are
1. Import cx_Oracle module
2. Every Python Program must get CONNECTION from Database Software
3. Every Python Program Must Create an object of CURSOR .
4. Every Python Program Must Design the Query , place the Query in Cursor object
and
Execute
5. Every Python Program must Process the Result of Query which is coming from
Database
Software though the Cursor
6. Python Program Closes the Connection.
===================================x====================================
============
1. Import cx_Oracle module
--------------------------------------------------------------------------------------------------------------------------
-----------------------
=>If any Python Program want to communicate with Oracle Data base Then we must import
cx_Oracle
module.
=>Examples: import cx_Oracle
--------------------------------------------------------------------------------------------------------------------------
-----------------------
2. Every Python Program must get CONNECTION from Database Software
--------------------------------------------------------------------------------------------------------------------------
-----------------------
=>After importing cx_Oracle Module, Python Program must get the connection from Oracle
Database.
=>If a Python program want to get the connection from Oracle database then we must use connect()
of
cx_Oracle module.
=>Syntax: varname=cx_Oracle.connect("Connection URL")
Here Connection URL Represents "username/password@DNS/serviceid"
(OR)
Here Connection URL Represents "username/password@IPAddress/serviceid"
-----------------
Explanation
------------------
=>here varname is an object of Connection object
=>Here usename and password represents user name and password of Oracle Database
=>DNS is nothing but name of the Physical Machine where Database Software Installed / resides
The Default DNS of Every Computer is "localhost"
=>IP Address is is nothing but Address of the Physical Machine where Database Software Installed /
resides. The Default IP ADDress of Every Computer is "127.0.0.1" (loop back address)
=>ServiceID represents on which name Oracle database software is available in current machine.
To Find Service-ID of Oracle Database, use the following Command at SQL Environment.

SQL> select * from global_name;


GLOBAL_NAME
------------------------------
XE
--------------------------------
Exmaple: con=cx_Oracle.connect("system/manager@localhost/XE")
here con is an object of <class, cx_Oracle.Connection>
--------------------------------------------------------------------------------------------------------------------------
-----------------------
3. Every Python Program Must Create an object of CURSOR .
--------------------------------------------------------------------------------------------------------------------------
-----------------------
=>after getting the connection from Oracle DB, the programmer must create an object of cursor.
=>The purpose of creating the cursor object is that "To carry the Query from Python Program,
Handover to Database Software and Brings the result from database software and gives to Python
Program".
=>To create an object of cursor, we have curosr() in connection object.
=>Syntax: varname=conobj.cursor()
=>Here var name is an object of <class, cx_Oracle.Cursor>
--------------------------------------------------------------------------------------------------------------------------
-----------------------
4. Every Python Program Must Design the Query , place the Query in Cursor object and Execute
--------------------------------------------------------------------------------------------------------------------------
-----------------------
=>A Query a request / Question to the database from Program.
=>To execute a Query, we have to use execute() and it is present in cursor object
=>Syntax: curobj.execute("Query")
=>In SQL, We have Different Types of Queries. They are DDL , DML and DRL
--------------------------------------------------------------------------------------------------------------------------
-----------------------.

5. every python program must process the result coming frome oracle db
6. every python program must close the connection

day – 65

Here is the exact and simple way to create your own database in SQL Server.
You can do it in two ways:

✅ Method 1: Create database using SQL Server Management Studio


(SSMS)
1. Open SSMS
2. Right-click Databases
3. Select New Database…
4. Enter database name (example: mydb)
5. Click OK
✅ Database created!

✅ Method 2: Create database using Python


Use this code:
import pyodbc

conn = pyodbc.connect(
"Driver={ODBC Driver 17 for SQL Server};"
"Server=localhost;"
"Database=master;"
"Trusted_Connection=yes;"
)

cursor = conn.cursor()

# Create new database


cursor.execute("CREATE DATABASE mydb")
conn.commit()

print("Database created successfully!")

conn.close()
✅ Replace mydb with your desired name.

✅ Confirm database is created


Run:
cursor.execute("SELECT name FROM sys.databases")
for row in cursor:
print(row)

You should see mydb in the list.

✅ Next Step (Optional)


After database creation, you can connect to it:
conn = pyodbc.connect(
"Driver={ODBC Driver 17 for SQL Server};"
"Server=localhost;"
"Database=mydb;"
"Trusted_Connection=yes;"
)

Then create tables, insert data, etc.

If you want, I can also show you:


✅ How to create tables
✅ How to insert data
✅ How to view data
Tell me your database name and table structure (columns).

#Program for demonstrating how to get the connection Oracle Database


#OracleTestConEx1.py
import cx_Oracle # Step-1
kvr=cx_Oracle.connect("system/manager@localhost/xe") # Step-2
print("\nType of kvr=",type(kvr))
print("Python Program program obtains Connection from Oracle DB")

#Program for demonstrating how to get the connection Oracle Database


#OracleTestConEx2.py
import cx_Oracle # Step-1
try:
kvr=cx_Oracle.connect("system/[email protected]/xe") # Step-2
print("\nType of kvr=",type(kvr))
print("Python Program program obtains Connection from Oracle DB")
except cx_Oracle.DatabaseError as db:
print("Ur Username OR Password is Wrong-Check Once")
#Program for creating an object of cursor
#OracleCursorEx1.py
import pyodbc # Step-1
try:
con=pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};'
'SERVER=localhost;'
'DATABASE=master;'
'Trusted_Connection=yes;') #Step-2
print("\nPython Program Obtains Connection from Oracle DB")
cur=con.cursor() #Step-3
print("\nType of cur=",type(cur))
print("Python Program creates Cursor object")
except pyodbc.DatabaseError as db:
print("Problem in Oracle DB:",db)

================================================
1. DDL (Data Definiton Language) Queries
================================================
=>The purpose of DDL (Data Definiton Language) Queries is that "To deal with Physical Level of
Tables such as Table creation with column names, droping tables and re-structuring columns of
table".
=>DDL Queries are classified into 3 types. They are
1. create
2. alter
3. drop
---------------------------------------------------------------------------------------------------
1) create
---------------------------------------------------------------------------------------------------
=>It is used for creating Table in Database Software.
=>Syntax:
SQL>create table table-name(col1 DB Data Type, Col2 DB DataType,....Col-n DB Data Type)
Examples:
---------------
SQL> create table student (sno number(2) primary key ,sname varchar2(10) not null ,marks
number(5,2) not null);
---------------------------------------------------------------------------------------------------
2) alter------ add option modify option
---------------------------------------------------------------------------------------------------
=>This Query is used for altering table structure.
=>In Otherwords, alter is used for modifying the Column Sizes ( modify) and adding new column
names ( add )
=>Syntax1:
-----------------
SQL> alter table table-name modify(existing col-name1 DB Data Type,.... existing col-name-n DB
Data Type)
-----------------
=>Syntax2:
-----------------
SQL> alter table table-name add(new col-name1 DB Data Type,... new col-name-n DB Data Type)
Example1:
--------------
SQL> alter table teacher modify(tno number(3),tsal number(6,2));
------------------
Example2:
------------------
SQL> alter table teacher add(cname varchar2(10) not null);
---------------------------------------------------------------------------------------------------
3) drop
---------------------------------------------------------------------------------------------------
=>This query is used for removing or droping the table from Database Software:
=>Syntax: SQL> drop table tablename
=>Examples: SQL > drop table employee
---------------------------------------------------------------------------------------------------.

✅ This error means the database already exists, so no need to create it again.
Database 'DataEngineer' already exists.

Great! ✅ You can now connect to it and start creating tables.

✅ Step 1: Connect to DataEngineer database


import pyodbc

con = pyodbc.connect(
"Driver={ODBC Driver 17 for SQL Server};"
"Server=localhost;"
"Database=DataEngineer;"
"Trusted_Connection=yes;"
)
cur = con.cursor()
print("Connected Successfully")

✅ Step 2: Create a table


Example: student table
cur.execute("""
CREATE TABLE student (
id INT PRIMARY KEY,
name VARCHAR(50),
age INT
)
""")
con.commit()

✅ Table created.
✅ Step 3: Insert data
cur.execute("INSERT INTO student VALUES (1, 'Yash', 20)")
con.commit()

✅ Step 4: Show data


cur.execute("SELECT * FROM student")
for row in cur:
print(row)

Output:
(1, 'Yash', 20)

✅ Step 5: Show all tables in your database


cur.execute("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES")
for row in cur:
print(row)

✅ If you want to delete (drop) table


cur.execute("DROP TABLE student")
con.commit()

✅ Now your database is created and ready.


Tell me next:
• Create another table?
• Add foreign key?
• Insert multiple rows?
• Create employee table?
I can generate full code.

✅ Great! You have completed:


✔ Connection
✔ Database creation
✔ Table creation
✔ Insert
✔ Select
Now you’re ready for next SQL Server + Python tasks.
Here are recommended next steps (you can choose):

✅ 1. Insert multiple rows


data = [
(2, 'Rahul', 22),
(3, 'Aman', 21),
(4, 'Priya', 23)
]

cur.executemany("INSERT INTO student VALUES (?, ?, ?)", data)


con.commit()

✅ 2. Update record
cur.execute("UPDATE student SET age = 25 WHERE id = 1")
con.commit()

✅ 3. Delete record
cur.execute("DELETE FROM student WHERE id = 3")
con.commit()

✅ 4. Show only names


cur.execute("SELECT name FROM student")
print(cur.fetchall())

✅ 5. Add a new column


cur.execute("ALTER TABLE student ADD city VARCHAR(50)")
con.commit()

✅ 6. Drop table
cur.execute("DROP TABLE student")
con.commit()

✅ 7. Create another table (employee)


cur.execute("""
CREATE TABLE employee (
emp_id INT PRIMARY KEY,
emp_name VARCHAR(50),
salary INT,
department VARCHAR(50)
)
""")
con.commit()

✅ 8. Join two tables


If student and employee tables exist:
cur.execute("""
SELECT s.name, e.emp_name
FROM student s
JOIN employee e ON s.id = e.emp_id
""")
print(cur.fetchall())

✅ You can tell me what you want to learn next, and I’ll guide step-by-step:
• CRUD operations
• Primary key / foreign key
• Multiple tables
• Stored Procedure
• SQL functions
• Python + SQL server project
• Data Engineer queries
• Pandas + SQL server
• ETL process (Extract–Transform–Load)
• Bulk load CSV into SQL Server
• Insert hundreds of rows
Just say “Next step” or tell your goal.
Great ✅
Next important step for Data Engineers using Python + SQL Server:

✅ Step: Load CSV Data into SQL Server (Most Needed Skill)
This is a core ETL skill.

✅ 1. Create a table first


Example table:
cur.execute("""
CREATE TABLE sales (
id INT,
product VARCHAR(50),
quantity INT,
price FLOAT
)
""")
con.commit()

✅ 2. Load CSV using Python


Suppose your CSV file is sales.csv:
id,product,quantity,price
1,Apple,10,50
2,Banana,5,20
3,Orange,8,30

Now load it:


import csv

with open("sales.csv", "r") as file:


reader = csv.reader(file)
next(reader) # skip header

for row in reader:


cur.execute(
"INSERT INTO sales VALUES (?, ?, ?, ?)",
row
)
con.commit()

✅ CSV loaded successfully


✅ This is real Data Engineering work

✅ 3. Verify CSV data


cur.execute("SELECT * FROM sales")
for r in cur:
print(r)

✅ 4. SUM / COUNT / GROUP BY (Basic Analytics)


cur.execute("SELECT product, SUM(quantity) FROM sales GROUP BY product")
print(cur.fetchall())

✅ 5. Delete the table (if needed)


cur.execute("DROP TABLE sales")
con.commit()
✅ What next?
Choose your next learning goal:

✅ Option A:
Bulk Insert — super fast loading
(Important for Data Engineers)

✅ Option B:
Create stored procedures using Python

✅ Option C:
Read SQL data into pandas DataFrame

✅ Option D:
Build a small ETL pipeline (extract → transform → load)

✅ Option E:
Automate job with Python schedule

? Reply with one option:


A, B, C, D, or E
I will guide step-by-step.

Write a python program which will created with eno enmae ans sell

#SqlServerTableCreateEx1.py
import pyodbc # Step-1

def tablecreate():
try:
# Step-2: Connect to SQL Server
con = pyodbc.connect(
"Driver={ODBC Driver 17 for SQL Server};"
"Server=localhost;"
"Database=master;"
"Trusted_Connection=yes;"
)

cur = con.cursor() # Step-3

# Step-4: SQL Server Table Creation


ct = """
CREATE TABLE employee1 (
eno INT PRIMARY KEY,
ename VARCHAR(10) NOT NULL,
sal DECIMAL(5,2) NOT NULL
)
"""

cur.execute(ct)
con.commit()

print("Employee table created successfully in SQL Server—verify!")

except pyodbc.DatabaseError as db:


print("Problem in SQL Server DB:", db)

# main program
tablecreate()

con = pyodbc.connect(
"Driver={ODBC Driver 17 for SQL Server};"
"Server=localhost;"
"Database=DataEngineer;"
"Trusted_Connection=yes;"
)

#OracleAlterTableColSizes.py
import cx_Oracle #Step-1
def tableColSize():
try:
con=cx_Oracle.connect("system/manager@localhost/xe") #Step-2
cur=con.cursor() #Step-3
#step-4
aq="alter table employee modify(eno number(3),ename varchar2(15))"
cur.execute(aq)
#Step-5
print("Employee Table altered sucessfully in Oracle Database--verify ")
except cx_Oracle.DatabaseError as db:
print("Problem in Oarcle DB",db)

#main program
tableColSize()

#OracleAlterTableColadding.py
import cx_Oracle #Step-1
def tableColadd():
try:
con=cx_Oracle.connect("system/manager@localhost/xe") #Step-2
cur=con.cursor() #Step-3
#step-4
aq="alter table employee add(cname varchar2(10) not null)"
cur.execute(aq)
#Step-5
print("Employee Table altered sucessfully in Oracle Database--verify ")
except cx_Oracle.DatabaseError as db:
print("Problem in Oarcle DB",db)

#main program
tableColadd()

Python 3.14.0 (tags/v3.14.0:ebf955d, Oct 7 2025, 10:15:03) [MSC v.1944 64 bit (AMD64)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pyodbc
...
... con = pyodbc.connect(
... "Driver={ODBC Driver 17 for SQL Server};"
... "Server=localhost;"
... "Database=DataEngineer;"
... "Trusted_Connection=yes;"
... )
... cur = con.cursor()
... print("Connected Successfully")
...
Connected Successfully
>>> cur.execute("""
... CREATE TABLE student2 (
... id INT PRIMARY KEY,
... name VARCHAR(50),
... age INT
... )
... """)
... con.commit()
...
>>> cur.execute("INSERT INTO student2 VALUES (1, 'Yash', 20)")
... con.commit()
...
>>> cur.execute("SELECT * FROM student2")
... for row in cur:
... print(row)
...
(1, 'Yash', 20)
>>> cur.execute("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES")
... for row in cur:
... print(row)
...
('student',)
('DATAENGINEER_SYLLABUS',)
('student2',)
>>> cur.execute("DROP TABLE student")
... con.commit()
...
>>> cur.execute("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES")
... ... for row in cur:
... ... print(row)
...
File "<python-input-6>", line 2
... for row in cur:
^^^
SyntaxError: invalid syntax
>>> data = [
... (2, 'Rahul', 22),
... (3, 'Aman', 21),
... (4, 'Priya', 23)
... ]
... data = [
... (2, 'Rahul', 22),
... (3, 'Aman', 21),
... (4, 'Priya', 23)
... ]
...
>>>
>>>
KeyboardInterrupt
>>> data = [
... (2, 'Rahul', 22),
... (3, 'Aman', 21),
... (4, 'Priya', 23)
... ]
...
... cur.executemany("INSERT INTO student2 VALUES (?, ?, ?)", data)
... con.commit()
...
...
>>> cur.execute("SELECT * FROM student2")
... for row in cur:
... print(row)
...
(1, 'Yash', 20)
(2, 'Rahul', 22)
(3, 'Aman', 21)
(4, 'Priya', 23)
>>> cur.execute("UPDATE student2 SET age = 25 WHERE id = 1")
... con.commit()
...
>>> cur.execute("SELECT * FROM student2")
... for row in cur:
... print(row)
...
(1, 'Yash', 25)
(2, 'Rahul', 22)
(3, 'Aman', 21)
(4, 'Priya', 23)
>>>
SELECT name, physical_name
FROM sys.master_files
WHERE database_id = DB_ID('student2');
day --- 66

import pyodbc

# Step 1: Connect to SQL Server


conn = pyodbc.connect(
'DRIVER={ODBC Driver 17 for SQL Server};'
'SERVER=localhost;'
'DATABASE=DataEngineer;'
'Trusted_Connection=yes;'
)

# Step 2: Create a cursor


cursor = conn.cursor()

# Step 3: Create a table (only run once)


cursor.execute("""
IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='Employees' AND xtype='U')
CREATE TABLE Employees (
ID INT PRIMARY KEY,
Name NVARCHAR(50),
Age INT,
Salary FLOAT
)
""")

# Step 4: Insert single row


cursor.execute("""
INSERT INTO Employees (ID, Name, Age, Salary)
VALUES (1, 'John Doe', 30, 50000)
""")

# Step 5: Insert multiple rows


data = [
(2, 'Alice', 28, 55000),
(3, 'Bob', 35, 60000),
(4, 'Charlie', 25, 48000)
]

cursor.executemany("INSERT INTO Employees (ID, Name, Age, Salary) VALUES


(?, ?, ?, ?)", data)

# Step 6: Commit changes


conn.commit()

print("✅ Data inserted successfully!")

# Step 7: Fetch and verify inserted rows


cursor.execute("SELECT * FROM Employees")
rows = cursor.fetchall()

print("\nInserted Records:")
for row in rows:
print(row)

# Step 8: Close connection


cursor.close()
conn.close()

import pyodbc

# Step 1: Connect to SQL Server


conn = pyodbc.connect(
'DRIVER={ODBC Driver 17 for SQL Server};'
'SERVER=localhost;'
'DATABASE=DataEngineer;'
'Trusted_Connection=yes;'
)

# Step 2: Create cursor


cursor = conn.cursor()

# Step 3: Select all data from table


cursor.execute("SELECT * FROM Employees")

# Step 4: Fetch all rows


rows = cursor.fetchall()

# Step 5: Display table data


print("?¬タヘ? Employees Table Data:\n")
print("ID\tName\t\tAge\tSalary")
print("-"*40)
for row in rows:
print(f"{row.ID}\t{row.Name}\t{row.Age}\t{row.Salary}")

# Step 6: Close connection


cursor.close()
conn.close()

#OracleRecordInsertEx1.py
import cx_Oracle
def recordinsert():
try:
con=cx_Oracle.connect("system/manager@localhost/xe")
cur=con.cursor()
iq="insert into employee values(400,'Sagatika',2.4,'SE')"
cur.execute(iq)
con.commit()
print("Employee Inserted Sucessfully in Employee Table")

except cx_Oracle.DatabaseError as db:


print("Problem in Oarcle DB",db)

#main program
recordinsert()

#OracleRecordInsertEx2.py
import cx_Oracle
def recordinsert():
try:
con=cx_Oracle.connect("system/manager@localhost/xe")
cur=con.cursor()
#accept the emp details from KBD
empno=int(input("Enter Employee Number:"))
empname=input("Enter Employee Name:")
empsal=float(input("Enter Employee Salary:"))
empdsg = input("Enter Employee Designation:")
#Prepare the Query with dynamic values
iq="insert into employee values(%d,'%s',%f,'%s')"
cur.execute(iq %(empno,empname,empsal,empdsg))
#OR cur.execute("insert into employee values(%d,%s',%f,'%s')" %
(empno,empname,empsal,empdsg))
con.commit()
print("Employee Inserted Sucessfully in Employee Table")
except cx_Oracle.DatabaseError as db:
print("Problem in Oarcle DB",db)

#main program
recordinsert()

#OracleRecordInsertEx3.py
import cx_Oracle
def recordinsert():
while(True):
try:
con=cx_Oracle.connect("system/manager@localhost/xe")
cur=con.cursor()
print("-"*50)
#accept the emp details from KBD
empno=int(input("Enter Employee Number:"))
empname=input("Enter Employee Name:")
empsal=float(input("Enter Employee Salary:"))
empdsg = input("Enter Employee Designation:")
#Prepare the Query with dynamic values
iq="insert into employee values(%d,'%s',%f,'%s')"
cur.execute(iq %(empno,empname,empsal,empdsg))
#OR cur.execute("insert into employee values(%d,%s',%f,'%s')" %
(empno,empname,empsal,empdsg))
con.commit()
print("-" * 50)
print("{} Employee Record Inserted Sucessfully in Employee Table".format(cur.rowcount))
print("-" * 50)
ch=input("Do u want Insert another record(yes/no):")
if(ch.lower()=="no"):
break
except cx_Oracle.DatabaseError as db:
print("Problem in Oarcle DB",db)
except ValueError:
print("Don't enter alnums,strs and symbols for empnos,sals")

#main program
recordinsert()

#OracleRecordUpdateEx1.py
import cx_Oracle
def updaterecord():
try:
con=cx_Oracle.connect("system/[email protected]/xe")
cur=con.cursor()
empno=int(input("Enter Employee Number for Updating a Record:"))
cname=input("Enter New Company Name of Employee: ")
cur.execute("update employee set sal=sal+sal*(20/100),cname='%s' where eno=%d" %
(cname,empno))
con.commit()
if(cur.rowcount>0):
print("{} Employee Record Updated--Verify".format(cur.rowcount))
else:
print("Employee Number Does not Exist")
except cx_Oracle.DatabaseError as db:
print("Problem in Oarcle DB", db)

#main program
updaterecord()

#OracleRecordUpdateEx2.py
import cx_Oracle
def updaterecord():
while(True):
try:
con=cx_Oracle.connect("system/[email protected]/xe")
cur=con.cursor()
empno = int(input("Enter Employee Number for Updating a Record:"))
cname = input("Enter New Company Name of Employee: ")
empsal=float(input("Enter New Sal of Employee "))
cur.execute("update employee set sal=%f,cname='%s' where eno=%d" %(empsal,cname,
empno))
con.commit()
if(cur.rowcount>0):
print("{} Employee Record Updated".format(cur.rowcount))
else:
print("{} Emp Number Does not Exist".format(empno))
print("--------------------------------------")
ch = input("Do u want Update another record(yes/no):")
if (ch.lower() == "no"):
break
except cx_Oracle.DatabaseError as db:
print("Problem in Oarcle DB", db)
except ValueError:
print("Don't enter alnums,strs and symbols for empnos,sals")

================================================
2. DML(Data Manipulation Language) Queries
================================================
=>The purpose of DML(Data Manipulation Language) Queries is that " To insert records, delete
records and update records of any table".
=>DML(Data Manipulation Language) Queries are classfied into 3 types. They are

1. insert
2. delete
3. update
=>After performing any DML Operation through Python Program, we must commit the database by
using commit() and to undo the operation we do roll back by using rollback().
=>commit() and rollback() are present in connection object.
---------------------------------------------------------------------------------------------------
1. insert
---------------------------------------------------------------------------------------------------
=>This Query is used for inserting Record in a table.
=>Syntax:-
-----------------
SQL> insert into table-name values(val1 for col1,val2 for col2,....val-n for col-n)
Examples:
------------------
SQL> insert into employee values(20,'TR',1.9,'numpy');
---------------------------------------------------------------------------------------------------
2) delete
---------------------------------------------------------------------------------------------------
=>This Query is used for deleting a record from table.
=>Syntax1: SQL>delete from table-name ;
(OR)
=>Syntax2: SQL>delete from table-name where cond list ;
----------------
Examples:
----------------
SQL> delete from employee; #Deletes all records of employee table
SQL> delete from employee where eno=10; #Deletes Perticular record of employee table
---------------------------------------------------------------------------------------------------
3) update
--------------------------------------------------------------------------------------------------------------------------
---------
=>This Query is used for updating a record in a table.
=>Syntax1:- SQL>update table-name set col1=Val1,col2=val2....col-n=val-n;
(OR)
=>Syntax2:-
SQL>update table-name set col1=Val1,col2=val2....col-n=val-n where Cond List

how to create

import pyodbc

def recordinsert():
try:
# ✅ Connection to SQL Server
con = pyodbc.connect(
"DRIVER={ODBC Driver 17 for SQL Server};"
"SERVER=localhost;"
"DATABASE=DataEngineer;" # change if needed
"Trusted_Connection=yes;"
)
cur = con.cursor()

while True:
print("-" * 50)
empno = int(input("Enter Employee Number: "))
empname = input("Enter Employee Name: ")
empsal = float(input("Enter Employee Salary: "))
empdsg = input("Enter Employee Designation: ")

# ✅ Insert record using parameters (safe)


cur.execute(
"INSERT INTO Employee (EmpID, Name, Salary, Designation) VALUES (?, ?, ?, ?)",
(empno, empname, empsal, empdsg)
)
con.commit()

print(f"✅ Employee '{empname}' inserted successfully!")


print("-" * 50)

ch = input("Do you want to insert another record (yes/no)? ").lower()


if ch == "no":
break

except Exception as e:
print("❌ Problem in SQL Server DB:", e)
finally:
con.close()

# main program
recordinsert()
show table

import pyodbc

def show_table():
try:
# ✅ Connect to SQL Server
con = pyodbc.connect(
"DRIVER={ODBC Driver 17 for SQL Server};"
"SERVER=localhost;"
"DATABASE=DataEngineer;" # change if needed
"Trusted_Connection=yes;"
)
cur = con.cursor()

# ✅ Fetch all records


cur.execute("SELECT * FROM Employee")

rows = cur.fetchall()
print("-" * 60)
print("EmpID\tName\t\tSalary\t\tDesignation")
print("-" * 60)

# ✅ Display each row


for row in rows:
print(f"{row.EmpID}\t{row.Name}\t\t{row.Salary}\t\t{row.Designation}")

print("-" * 60)

except Exception as e:
print("❌ Problem in SQL Server DB:", e)
finally:
con.close()

# main program
show_table()

#OracleRecordUpdateEx1.py
import cx_Oracle
def updaterecord():
try:
con=cx_Oracle.connect("system/[email protected]/xe")
cur=con.cursor()
empno=int(input("Enter Employee Number for Updating a Record:"))
cname=input("Enter New Company Name of Employee: ")
cur.execute("update employee set sal=sal+sal*(20/100),cname='%s' where eno=%d" %
(cname,empno))
con.commit()
if(cur.rowcount>0):
print("{} Employee Record Updated--Verify".format(cur.rowcount))
else:
print("Employee Number Does not Exist")
except cx_Oracle.DatabaseError as db:
print("Problem in Oarcle DB", db)

#main program
updaterecord()

===============================================
Types of Queries in Database Softwares
===============================================
=>In RDBMS Softwares, SQL Queries are classified into 3 Types. They are

1. DDL (Data Definiton Language) Queries--create, alter, drop


2. DML(Data Manipulation Language) Queries--insert,update,delete
3. DRL (Data Retrieval Language) Queries------select
--------------------------------------------------------------------------------------------------------------------------
------.

write a program which will read the records from the emplyee table

#Program for Reading the records from employee table--fetchone()


#OracleSelectRecordsEx1.py
import cx_Oracle
def getrecords():
try:
con=cx_Oracle.connect("system/[email protected]/xe")
cur=con.cursor()
cur.execute("select * from employee")
print("------------------------------------")
while(True):
record = cur.fetchone()
if(record!=None):
for val in record:
print("{}".format(val),end="\t")
print()
else:
print("------------------------------------")
break
except cx_Oracle.DatabaseError as db:
print("Problem in Oracle DB:",db)

#main program
getrecords()

#Program for Reading the records from employee table--fetchmany()


#OracleSelectRecordsEx2.py
import cx_Oracle
def getrecords():
try:
con = cx_Oracle.connect("system/[email protected]/xe")
cur = con.cursor()
cur.execute("select * from employee")
records=cur.fetchmany(4)
print("-----------------------------")
for record in records:
for val in record:
print("{}".format(val),end="\t")
print()
print("-----------------------------")
except cx_Oracle.DatabaseError as db:
print("Problem in Oracle DB:", db)

#main program
getrecords()

#Program for Reading the records from employee table--fetchall()


#OracleSelectRecordsEx3.py
import cx_Oracle
def getrecords():
try:
con = cx_Oracle.connect("system/[email protected]/xe")
cur = con.cursor()
cur.execute("select * from employee")
records=cur.fetchall()
print("-----------------------------")
for record in records:
for val in record:
print("{}".format(val),end="\t")
print()
print("-----------------------------")
except cx_Oracle.DatabaseError as db:
print("Problem in Oracle DB:", db)

#main program
getrecords()

============================================
3. DRL (Data Retrieval Language ) Queries
============================================
=>DRL (Data Retrieval Language ) Queries are used for Reading the records from table.
=>To read the records from table, we use "select"
=>In Otherwords "select" comes under DRL (Data Retrieval Language ) Query.
=>Syntax1: SQL>select col1,col2,.....col-n from <table-name>
=>Syntax2: SQL>select col1,col2,.....col-n from <table-name> where cond list
=>Syntax3: SQL>select * from <table-name>
=>Syntax4: SQL>select * from <table-name> where cond list
--------------------------------------------------------------------------------------------------------------------------
------------
=>Once the select query executed, all records are present in the object of cursor in Python.
=>To get the records from cusror object, we have 3 functions present in cursor object. They are
1) fetchone()
2) fetchmany(no. of records)
3) fetchall()
-----------------------------------------------------------------------
1) fetchone():
=>This function is used obtaining One Record at a time, where cursor object pointing and it returns
either tuple (if records exist) or None (if records does not exist)
-----------------------------------------------------------------------------
2) fetchmany(no. of records)
-----------------------------------------------------------------------------
=>fetchmany(no. of records) is used for obtaining specified number of records.
case-1: if specified number of records==0 then this function obtains all records
case-2: if specified number of records>0 and specified number of records<=Total
Number of Records then this function gives specified number of
records
case-3: if specified number of records>Total Number of Records then this function
obtains all records
case-4: if specified number of records<0 then this function never gives any
records.
-----------------------------------------------------------------------------
3) fetchall()
-----------------------------------------------------------------------------
=>fetchall() is used for obtaining all the records from cursor object in the form tuples of list.
-----------------------------------------------------------------------------.

#Program for obtaining Col names along with records


#OracleTableColrecordsEx1.py
import cx_Oracle
def getrecords():
try:
con = cx_Oracle.connect("system/[email protected]/xe")
cur = con.cursor()
cur.execute("select * from employee")
print("-----------------------------")
#Code obtaining Col Names
for col in cur.description:
print(col[0],end="\t")
print()
print("-----------------------------")
# Code obtaining Records
records=cur.fetchall()
for record in records:
for val in record:
print("{}".format(val),end="\t")
print()
print("-----------------------------")
except cx_Oracle.DatabaseError as db:
print("Problem in Oracle DB:", db)

#main program
getrecords()
#Program for accepting any table name and display records along with col names
#OracleTableDisplay.py
import cx_Oracle
def getrecords():
try:
con = cx_Oracle.connect("system/[email protected]/xe")
cur = con.cursor()
#accept the table name from Key Board
print("-----------------------------")
tname=input("Enter table Name:")
cur.execute("select * from %s" %tname)
print("-----------------------------")
#Code obtaining Col Names
for col in cur.description:
print(col[0],end="\t")
print()
print("-----------------------------")
# Code obtaining Records
records=cur.fetchall()
for record in records:
for val in record:
print("{}".format(val),end="\t")
print()
print("-----------------------------")
except cx_Oracle.DatabaseError as db:
print("'%s' Table Does not exist "%tname)

#main program
getrecords()

sql/pl/sql developers guide


by lvon bayrons

====================================================================
Steps for developing Python Database Communication Applications With
MySQL

====================================================================
=>If Python Program want to Communicate with any RDBMS Softwares Like Oracle then we
follow Certain Steps. They are
1. Import mysql.connector module
2. Every Python Program must get CONNECTION from Database Software
3. Every Python Program Must Create an object of CURSOR .
4. Every Python Program Must Design the Query , place the Query in Cursor
object and
Execute
5. Every Python Program must Process the Result of Query which is coming from
Database
Software though the Cursor
6. Python Program Closes the Connection.

===================================x===================================
=============
1. Import mysql.connector module
--------------------------------------------------------------------------------------------------------------------------
-----------------------
=>If any Python Program want to communicate with Oracle Data base Then we must
importmysql.connector module.
=>Examples: import mysql.connector
--------------------------------------------------------------------------------------------------------------------------
-----------------------
2. Every Python Program must get CONNECTION from Database Software
--------------------------------------------------------------------------------------------------------------------------
-----------------------
=>After importing mysql.connector Module, Python Program must get the connection from
MySQL Database.
=>If a Python program want to get the connection from MySQL database then we must use
connect() of
mysql.connector module.
=>Syntax: varname=mysql.connector.connect("Connection URL")
Here Connection URL Represents----> host="DNS",username="user
name",passwd="password"
(OR)
Here Connection URL Represents----> host="IP
Address",username="username",passwd="password"
-----------------
Explanation
------------------
=>here varname is an object of Connection object
=>Here usename and password represents user name and password of MySQL Database
=>DNS is nothing but name of the Physical Machine where Database Software Installed /
resides
The Default DNS of Every Computer is "localhost"
=>IP Address is is nothing but Address of the Physical Machine where Database Software
Installed /
resides. The Default IP ADDress of Every Computer is "127.0.0.1" (loop back address)
=>ServiceID represents on which name MySQL database software is available in current
machine.

Exmaple: con=mysql.connector.connect(host="localhost",
user="root",
passwd="root")
here con is an object of <class, mysql.connector.MySQLConnection>
--------------------------------------------------------------------------------------------------------------------------
-----------------------
3. Every Python Program Must Create an object of CURSOR .
--------------------------------------------------------------------------------------------------------------------------
-----------------------
=>after getting the connection from Oracle DB, the programmer must create an object of
cursor.
=>The purpose of creating the cursor object is that "To carry the Query from Python Program,
Handover to Database Software and Brings the result from database software and gives to
Python Program".
=>To create an object of cursor, we have curosr() in connection object.
=>Syntax: varname=conobj.cursor()
=>Here var name is an object of <class, mysql.connector.Cursor>
--------------------------------------------------------------------------------------------------------------------------
-----------------------
4. Every Python Program Must Design the Query , place the Query in Cursor object and
Execute
--------------------------------------------------------------------------------------------------------------------------
-----------------------
=>A Query a request / Question to the database from Program.
=>To execute a Query, we have execute() in cursor object
=>Syntax: curobj.execute("Query")
=>In SQL, We have Different Types of Queries. They are DDL , DML and DRL

#Program for demonstrating Connection from MYSQL


#MySQLConnTestEx1.py
import mysql.connector
con=mysql.connector.connect(host="localhost",
user="root",
passwd="root")
print("\nPython Program obtains Connection from MySQL")
print("Type of con=",type(con))

#Program for demonstrating Connection from MYSQL


#MySQLConnTestEx2.py
import mysql.connector
con=mysql.connector.connect(host="127.0.0.1",
user="root",
passwd="root")
print("\nPython Program obtains Connection from MySQL")
print("Type of con=",type(con))
#Program for demonstrating creating cursor in MYSQL
#MySQLCursorTestEx1.py
import mysql.connector
con=mysql.connector.connect(host="127.0.0.1",
user="root",
passwd="root")
print("\nPython Program obtains Connection from MySQL")
print("Type of con=",type(con))
cur=con.cursor()
print("\nPython Program created a cursor object")
print("Type of cur=",type(cur))

day – 68

my_sql

write a python program which will create database on the name of batch 6 pm in mysql

#Program for Creating a Database--batch6pm


#MySQLDatabaseCreateEx1.py
import mysql.connector
def databasecreate():
try:
con=mysql.connector.connect(host="127.0.0.1",
user="root",
passwd="root")
cur=con.cursor()
dc="create database batch6pm"
cur.execute(dc)
print("Database Created Sucessfully-Verify")
except mysql.connector.DatabaseError as db:
print("Problem in MySQL DB:",db)

#main program
databasecreate()

#MySQLTableCreateEx.py
import mysql.connector
def tablecreate():
try:
con=mysql.connector.connect(host="127.0.0.1",
user="root",
passwd="root",
database="batch6pm")
cur=con.cursor()
tc="create table student(sno int primary key,name varchar(10) not null,marks float not
null)"
cur.execute(tc)
print("Student Table Created Sucessfully-Verify")
except mysql.connector.DatabaseError as db:
print("Problem in MySQL DB:",db)

#main program
tablecreate()

#MySQLTableAddColNameEx.py
import mysql.connector
def tablecreate():
try:
con=mysql.connector.connect(host="127.0.0.1",
user="root",
passwd="root",
database="batch6pm")
cur=con.cursor()
aq="alter table student add(colname varchar(10))"
cur.execute(aq)
print("Student Table altred Sucessfully-Verify")
except mysql.connector.DatabaseError as db:
print("Problem in MySQL DB:",db)

#main program
tablecreate()

#MySQLDroptableEx.py
import mysql.connector
def tablecreate():
try:
con=mysql.connector.connect(host="127.0.0.1",
user="root",
passwd="root",
database="batch6pm")
cur=con.cursor()
dq="drop table student"
cur.execute(dq)
print("Student Table Droped Sucessfully-Verify")
except mysql.connector.DatabaseError as db:
print("Problem in MySQL DB:",db)

#main program
tablecreate()

#MySQLRecordDeleteEx.py
import mysql.connector
def recorddelete():
try:
con = mysql.connector.connect(host="127.0.0.1",
user="root",
passwd="root",
database="batch6pm")
while(True):
try:
cur=con.cursor()
print("-"*50)
#accept the emp number from KBD
empno=int(input("Enter Employee Number:"))
#Prepare the Query with dynamic values
dq="delete from employee where eno=%d"
cur.execute(dq %empno)
con.commit()
print("-" * 50)
if(cur.rowcount>0):
print("{} Employee Record Deleted Sucessfully in Employee
Table".format(cur.rowcount))
else:
print("Employee Record does not exist")
print("-" * 50)
ch=input("Do u want delete another record(yes/no):")
if(ch.lower()=="no"):
break
except ValueError:
print("Don't enter alnums,strs and symbols for empnos")
except mysql.connector.DatabaseError as db:
print("Problem in Oarcle DB",db)
#main program
recorddelete()

#MySQLRecordInsertEx.py
import mysql.connector
def recordinsert():
try:
con = mysql.connector.connect(host="127.0.0.1",
user="root",
passwd="root",
database="batch6pm")
while(True):
try:
cur=con.cursor()
print("-"*50)
#accept the emp details from KBD
empno=int(input("Enter Employee Number:"))
empname=input("Enter Employee Name:")
empsal=float(input("Enter Employee Salary:"))
empdsg = input("Enter Employee Designation:")
#Prepare the Query with dynamic values
iq="insert into employee values(%d,'%s',%f,'%s')"
cur.execute(iq %(empno,empname,empsal,empdsg))
#OR cur.execute("insert into employee values(%d,%s',%f,'%s')" %
(empno,empname,empsal,empdsg))
con.commit()
print("-" * 50)
print("{} Employee Record Inserted Sucessfully in Employee
Table".format(cur.rowcount))
print("-" * 50)
ch=input("Do u want Insert another record(yes/no):")
if(ch.lower()=="no"):
break
except ValueError:
print("Don't enter alnums,strs and symbols for empnos,sals")
except mysql.connector.DatabaseError as db:
print("Problem in Oarcle DB",db)
#main program
recordinsert()

#MySQLRecordUpdateEx.py
import mysql.connector
def recordupdate():
try:
con = mysql.connector.connect(host="127.0.0.1",
user="root",
passwd="root",
database="batch6pm")
while(True):
try:
cur=con.cursor()
print("-"*50)
#accept the emp number from KBD
empno=int(input("Enter Employee Number for updating records:"))
empname=input("Enter Employee Name:")
empsal =float(input("Enter Employee New Salary:"))
empdsg = input("Enter Employee Designation:")
#Prepare the Query with dynamic values
uq="update employee set ename='%s',sal=%f,dsg='%s' where eno=%d"
cur.execute(uq %(empname,empsal,empdsg,empno))
con.commit()
print("-" * 50)
if(cur.rowcount>0):
print("{} Employee Record Updated Sucessfully in Employee
Table".format(cur.rowcount))
else:
print("Employee Record does not exist")
print("-" * 50)
ch=input("Do u want update another record(yes/no):")
if(ch.lower()=="no"):
break
except ValueError:
print("Don't enter alnums,strs and symbols for empnos")
except mysql.connector.DatabaseError as db:
print("Problem in Oarcle DB",db)
#main program
recordupdate()
#MySQLRecordSelectEx.py
import mysql.connector
def recordsselect():
try:
con = mysql.connector.connect(host="127.0.0.1",
user="root",
passwd="root",
database="batch6pm")
cur=con.cursor()
tname=input("Enter any table Name:")
cur.execute("select * from %s" %tname)
#getting Col names
print("-"*40)
for col in cur.description:
print("{}".format(col[0]),end="\t")
print()
print("-" * 40)
#getting the records
records=cur.fetchall()
for record in records:
for val in record:
print("{}".format(val),end="\t")
print()
print("-" * 40)

except mysql.connector.DatabaseError as db:


print("Problem in Oarcle DB",db)
#main program
recordsselect()

day – 69

=======================================================
Object Oriented Principles or Features or Concepts (10 days)
=======================================================
Index:
---------
=>What are the advantages of OOPs
=>List of Object Oriented Principles
1. Classes
2. Objects
3. Data Encapsulation
4. Data Abstraction
5. Inheritance
6. Polymorphism
7. Message Passing(already discussed)
---------------------------------------------------------------------------
1. Classes
=>Importance and purpose of Classes concept
=>Syntax for Defining Class
=>Types of Data Members
a) Instance Data Members
b) Class Level Data Members
=>Types of Methods
a) Instance Method
b) Class Level Method
c) Static Method
=>What is "self" and "cls"
=>Programming Examples
2. Object
=>Importance and purpose of Object Concept
=>Syntax for creating Object
=>Programming Examples
=>PRAMMING Examples related to pickling and Data base communication with Classes and
objects.
--------------------------------------------------------------------------------------------------------------------------
-----------
=>Constructors in OOPs
=>Importance and purpose of Constructors
=>Types of Constructors
a) Default Constructors
b) Parameterized Constructors
=>Rules for Constructors
=>Programming Examples
--------------------------------------------------------------------------
=>Destructrors in OOPs with Garbage Collector
=>Importance and purpose of Detstructrors
=>Syntax for defining Detstructrors
=>Internal flow of Detstructrors
=>Relation between Detstructrors and Garbage Collector
=>gc module
=>Pgramming Examples
----------------------------------------------------------------------------------------
3. Data Encapsulation and Data Abstraction
=>Importance and purpose of Data Encapsulation
=>Importaance and purpose of Data Abstraction
=>Implementation of data encapsulation and Data Abstraction
=>Programming Examples
----------------------------------------------------------------------
5. Inheritance
=>Importaance and purpose of Inheritance
=>Types of Inheritances
a) single
b) multi level
c) hierarchical
d) multiple
e) Hybrid
=>Syntax for Inheritance
=>Programming Examples
--------------------------------------------------
Method Overriding in OOPs
=>Importance and purpose of Method Overriding
=>Memory management in Method Overriding
=>Programming Examples
----------------------------------------------
6.Polymorphism
----------------------------------------------
=>Importance and purpose of Polymorphism
=>Difference between Polymorphism and Inheritance
=>Method Overriding with Polymorphism
=>Constructor Overriding with Polymorphism
=>super() and class name approaches in Polymorphism
=>Programming Examples
----------------------------------------------------------------------------------------------------------------
Introduction to Object Oriented Programming Principles (OOPs)

==========================================================
=>In real Time, To develop any project / Application, we use a Language and It can Satisfy to
either Procedure Oriented Features( Functional Programming ) OR Object Oriented Features.
=>In Other Words, we have Two Types of Programming languages. They are

1. Procedure Orineted(Functional) Programming Langugaes.


Examples: C,8086,upto Oracle7.3,Pascal,Cobol,PYTHON
2. Object Orineted Programming Langugaes.
Examples: c++,java,c#.net,smalltalk,ruby,PYTHON,from Oracle8
onwards

=>Hence PYTHON Programming Lang Belongs to Both Functional and Object Oriented
Programming lang.
=>Even Python Programming Lang Belongs to Functional Programming lang, Internally Every
Thing is Treated as object.
--------------------------------------------------------------------------------------------------------------------------
------------------
"Every Thing in Python is Treated as Object"--Advantages
(OR)
Advantages of Object Oriented Principles
--------------------------------------------------------------------------------------------------------------------------
-------------------
1. The Concept of object allows us to store Large Volume of Data.
2. The Confidential data / Information is Transmitting between the Remote
Machines in the
form of Cipher text / Encrypted Format. So that we can get Security.
3. The large Volume of Data Transfered Between Multiple Remote machines all at
once. So that
we can get Effective Communication.
4. The data is always available in the form of Objects. So that we can get Effective
Memory
Managament.
5. Provides Minimal Memory space for application development bcoz OOPs
Provides Re-usable
Mechanisms.
=====================================x=================================
===========.
===================================================
1. Classes
===================================================
=>The purpose of Classes concept is that "To develop Programmer-Defined Data Type + Real
Time
Applications".
=>The purpose of developing Programmer-Defined Data Type is that "To Store Customized
Data and to
Perform Customized Operations".
=>To develop Programmer-Defined Data Type by using Classes Concept, we use a keyword
called
"class".
=>Programatically Every Class Name is a Data Type.
=>In OOPs, Every Python Program must starts with class concept. Without class concept,
There is no
Python Program.
--------------------------------------------------------------
Definition of a Class
--------------------------------------------------------------
=>A Class is a collection of Data Members and Methods
=>When we define a Class , Memory space is not created for Data Members and Methods. But
whose memory space is created when we create an object W.R.T class name
=>All Data Memebrs and Methods of class are reflected as it is as part of Object with memory
space.
=>Class is Considered as Logical Existence and Object Considered as Physical Existence
=======================================================================
=========.

day --- 70

=================================================
Types of Data Members in Class of Python
=================================================
=>In a Class of Python, we can define Two Types of data members. They are
1. Instance Data Memebers
2. Class Level Data Members
--------------------------------------------------------------------------------------------------------------------------
--------
1. Instance Data Memebers
--------------------------------------------------------------------------------------------------------------------------
--------
=>Instance Data Memebers are those whose memory space created Every Time when an object
is
created.
=>Instance Data Members are Used for storing Specific values in object. Hence Instance data
members
are also called Object Level Data Members.
=>Instance Data Memebers can be specified in 3 ways. They are
a) Through Object name
b) Through Instance Method Name
c) Through Constructors
=>Instance Data Memebers can be accessed by using the following Syntaxes.
Syntax1: objname.Instance Data Members name
Syntax2: self.Instance Data Members name
--------------------------------------------------------------------------------------------------------------------------
--------
2. Class Level Data Members
--------------------------------------------------------------------------------------------------------------------------
--------
=>Class Level Data Memebers are those whose memory space created One Time irrespective of
Number of Objects are created.
=>Class Level Data Members are Used for storing Common values for all objects of same
Class.
=>Class Level DataData Memebers can be specified in 2 ways. They are
a) Inside of Class name
b) Inside of Class Level Method Definition
=>Class Level Data Memebers can be accessed by using the following Syntaxes.
Syntax1: Classname.Class Level Data Member name
Syntax2: cls.Class Level Data Member name
Syntax3: objname.Class Level Data Member name
Syntax4: self.Class Level Data Member name
--------------------------------------------------------------------------------------------------------------------------
--------.

#InstanceDataMemberEx1.py
class Student:pass

#main program
s1=Student() # Here s1 is called Object
s2=Student() # Here s2 is called Object
print("-----------------------------")
print("Content of s1 before adding=",s1.__dict__)
print("Content of s2 before adding=",s2.__dict__)
print("-----------------------------")
#Adding Instance Data memebrs through an object to s1
s1.sno=10
s1.sname="RS"
s1.marks=33.33
#Adding Instance Data memebrs through an object to s2
s2.sno=20
s2.sname="TR"
s2.marks=63.33
print("Content of s1 after adding=",s1.__dict__)
print("Content of s2 after adding=",s2.__dict__)
print("-----------------------------")

==================================================
Syntax for Denining a Class in Python
==================================================

class <clsname>:
Class Level Data Members
def InstanceMethodName(self,list of formal params if any):
------------------------------------------------------------------------
Specify Instance Data Members
Block of Statements--Performs Specific Operations
------------------------------------------------------------------------
@classmethod
def ClasslevelMethodName(cls,list of formal params if any):
------------------------------------------------------------------------
Specify Class Level Data Members
Block of Statements--Performs Common Operations
------------------------------------------------------------------------

@staticmethod
def StaticMethodName(list of formal params if any):
------------------------------------------------------------------------
Block of Statements--Performs Utility Operations
------------------------------------------------------------------------
=====

#InstanceDataMemberEx2.py
class Student:pass

#main program
s1=Student() # Here s1 is called Object
s2=Student() # Here s2 is called Object
print("-----------------------------")
print("Content of s1 before adding=",s1.__dict__)
print("Content of s2 before adding=",s2.__dict__)
print("-----------------------------")
#Adding Instance Data memebrs through an object to s1
s1.sno=10
s1.sname="RS"
s1.marks=33.33
#Adding Instance Data memebrs through an object to s2
s2.sno=20
s2.sname="TR"
s2.marks=63.33
print("First Object data")
print("-----------------------------")
print("Student Number:{}".format(s1.sno))
print("Student Name:{}".format(s1.sname))
print("Student Marks:{}".format(s1.marks))
print("-----------------------------")
print("Second Object data")
print("-----------------------------")
print("Student Number:{}".format(s2.sno))
print("Student Name:{}".format(s2.sname))
print("Student Marks:{}".format(s2.marks))
print("-----------------------------")

lassInstanceDataMemberEx1.py
class Student:
crs="PYTHON" # Here crs is called Class Level Data Member

#main program
s1=Student() # Here s1 is called Object
s2=Student() # Here s2 is called Object
print("-----------------------------")
print("Content of s1 before adding=",s1.__dict__)
print("Content of s2 before adding=",s2.__dict__)
print("-----------------------------")
#Adding Instance Data memebrs through an object to s1
s1.sno=10
s1.sname="RS"
s1.marks=33.33
#Adding Instance Data memebrs through an object to s2
s2.sno=20
s2.sname="TR"
s2.marks=63.33
print("First Object data")
print("-----------------------------")
print("Student Number:{}".format(s1.sno))
print("Student Name:{}".format(s1.sname))
print("Student Marks:{}".format(s1.marks))
print("STUDENT COURSE:{}".format(Student.crs))
print("-----------------------------")
print("Second Object data")
print("-----------------------------")
print("Student Number:{}".format(s2.sno))
print("Student Name:{}".format(s2.sname))
print("Student Marks:{}".format(s2.marks))
print("STUDENT COURSE:{}".format(Student.crs))
print("-----------------------------")

#ClassInstanceDataMemberEx2.py
class Student:
crs="PYTHON" # Here crs is called Class Level Data Member
city="HYD" # Here city is called Class Level Data Member

#main program
s1=Student() # Here s1 is called Object
s2=Student() # Here s2 is called Object
print("-----------------------------")
print("Content of s1 before adding=",s1.__dict__)
print("Content of s2 before adding=",s2.__dict__)
print("-----------------------------")
#Adding Instance Data memebrs through an object to s1
s1.sno=int(input("Enter First Student Number:"))
s1.sname=input("Enter First Student Name:")
s1.marks=float(input("Enter First Student Marks:"))
#Adding Instance Data memebrs through an object to s2
s2.sno=int(input("Enter Second Student Number:"))
s2.sname=input("Enter Second Student Name:")
s2.marks=float(input("Enter Second Student Marks:"))
print("First Object data")
print("-----------------------------")
print("Student Number:{}".format(s1.sno))
print("Student Name:{}".format(s1.sname))
print("Student Marks:{}".format(s1.marks))
print("STUDENT COURSE:{}".format(Student.crs)) # Accessing Class Level Data Members
by using Class Name
print("STUDENT CITY:{}".format(Student.city)) # Accessing Class Level Data Members by
using Class Name
print("-----------------------------")
print("Second Object data")
print("-----------------------------")
print("Student Number:{}".format(s2.sno))
print("Student Name:{}".format(s2.sname))
print("Student Marks:{}".format(s2.marks))
print("STUDENT COURSE:{}".format(Student.crs)) # Accessing Class Level Data Members
by using Class Name
print("STUDENT CITY:{}".format(Student.city)) # Accessing Class Level Data Members by
using Class Name
print("-----------------------------")

#ClassInstanceDataMemberEx2.py
class Student:
crs="PYTHON" # Here crs is called Class Level Data Member
city="HYD" # Here city is called Class Level Data Member

#main program
s1=Student() # Here s1 is called Object
s2=Student() # Here s2 is called Object
print("-----------------------------")
print("Content of s1 before adding=",s1.__dict__)
print("Content of s2 before adding=",s2.__dict__)
print("-----------------------------")
#Adding Instance Data memebrs through an object to s1
s1.sno=int(input("Enter First Student Number:"))
s1.sname=input("Enter First Student Name:")
s1.marks=float(input("Enter First Student Marks:"))
#Adding Instance Data memebrs through an object to s2
s2.sno=int(input("Enter Second Student Number:"))
s2.sname=input("Enter Second Student Name:")
s2.marks=float(input("Enter Second Student Marks:"))
print("First Object data")
print("-----------------------------")
print("Student Number:{}".format(s1.sno))
print("Student Name:{}".format(s1.sname))
print("Student Marks:{}".format(s1.marks))
print("STUDENT COURSE:{}".format(Student.crs)) # Accessing Class Level Data Members
by using Class Name
print("STUDENT CITY:{}".format(Student.city)) # Accessing Class Level Data Members by
using Class Name
print("-----------------------------")
print("Second Object data")
print("-----------------------------")
print("Student Number:{}".format(s2.sno))
print("Student Name:{}".format(s2.sname))
print("Student Marks:{}".format(s2.marks))
print("STUDENT COURSE:{}".format(Student.crs)) # Accessing Class Level Data Members
by using Class Name
print("STUDENT CITY:{}".format(Student.city)) # Accessing Class Level Data Members by
using Class Name
print("-----------------------------")

=================================================
Types of Data Members in Class of Python
=================================================
=>In a Class of Python, we can define Two Types of data members. They are
1. Instance Data Memebers
2. Class Level Data Members
--------------------------------------------------------------------------------------------------------------------------
--------
1. Instance Data Memebers
--------------------------------------------------------------------------------------------------------------------------
--------
=>Instance Data Memebers are those whose memory space created Every Time when an object
is
created.
=>Instance Data Members are Used for storing Specific values in object. Hence Instance data
members
are also called Object Level Data Members.
=>Instance Data Memebers can be specified in 3 ways. They are
a) Through Object name
b) Through Instance Method Name
c) Through Constructors
=>Instance Data Memebers can be accessed by using the following Syntaxes.
Syntax1: objname.Instance Data Members name
Syntax2: self.Instance Data Members name
--------------------------------------------------------------------------------------------------------------------------
--------
2. Class Level Data Members
--------------------------------------------------------------------------------------------------------------------------
--------
=>Class Level Data Memebers are those whose memory space created One Time irrespective of
Number of Objects are created.
=>Class Level Data Members are Used for storing Common values for all objects of same
Class.
=>Class Level DataData Memebers can be specified in 2 ways. They are
a) Inside of Class name
b) Inside of Class Level Method Definition
=>Class Level Data Memebers can be accessed by using the following Syntaxes.
Syntax1: Classname.Class Level Data Member name
Syntax2: cls.Class Level Data Member name
Syntax3: objname.Class Level Data Member name
Syntax4: self.Class Level Data Member name
--------------------------------------------------------------------------------------------------------------------------
--------.

write a python program which wiill calculate addition of two numbers by using classes and
objects

#Program for calculating addition of Two Numbers by using Classes and Objects
#SumEx1.py
class Sum:pass

#main program
s=Sum() # Here s is called object
print("Content of s=",s.__dict__)
print("------------------------------------------------")
s.k=float(input("Enter Value of k:"))
s.v=float(input("Enter Value of v:"))
print("Content of s=",s.__dict__)
print("------------------------------------------------")
#add the values
s.r=s.k+s.v
print("------------------------------------------------")
print("First Value:{}".format(s.k))
print("Second Value:{}".format(s.v))
print("Sum :{}".format(s.r))
print("------------------

day --- 71

==============================================
Types of Methods in Class of Python
==============================================
=>In class of Python, we define 3 Types of Methods. They are
1. Instance Methods
2. Class Level Methods
3. Static Methods
--------------------------------------------------------------------------------------------------------------------------
---------------------------
1. Instance Methods
--------------------------------------------------------------------------------------------------------------------------
---------------------------
=>Instance Methods are used for performing Specific Operations on objects. In Otherwords, to
perform the operations on objects data, we always use Instance Methods. Hence Instance
Methods are called Object Level Methods.
=>Programtically, Instance Methods always takes "self" as First Possitional Formal Parameter.
=>Syntax: def instancemethod(self, list of formal Parameters if any):
------------------------------------
Perform Specific Operations
Specify Instance Data Members
------------------------------------
=>All types of Instance Methods Must accessed w.r.t Object Name or self
objectname.Instance Method
(OR)
self.Instance Method Name
-----------------------------
What is self
-----------------------------
=>"self" is one of the Implicit Object which is always contains Ref /address of current object
=>"self" to be used always as First Possitonal Parameter in Instance Method
=>"self" to be accessed within Corresponding Instance Method body but not in Other Part of
program bcoz It is a First Possitonal Parameter .
--------------------------------------------------------------------------------------------------------------------------
---------------------------
2. Class Level Methods
--------------------------------------------------------------------------------------------------------------------------
---------------------------
=>Class Level Methods are used for Performing Common Operations for the objects of
Correspinding class and specifies Class Level Data Memebers.
=>To define Class Level Method, we must use a pre-defined Decorator called @classmethod
=>The Syntax for defining class level method is
@classmethod
def classlevelmethod(cls,list of formal params if any):
-------------------------------------
Specify Class Level Data Members
Perform Common Operations for all objects of corresponding objects.
--------------------------------------
=>Every Class Level Method must be accssed w.r.t to Class Name OR cls OR Object Name
OR self
ClassName.Class Level Method
(OR)
cls.Class Level Method
(OR)
objectname.Class Level Method
(OR)
self.Class Level Method
What is cls:
------------------------------
=>"cls" is one of the implicit object and it contains Current Class Name
=>"cls" always to be used as First Formal Parameter in Class Level Method
=>Since "cls" is a Formal parameter, so that it can access inside of Corresponding Class Level
Method Definition only but not possible to access in other part of Program.
--------------------------------------------------------------------------------------------------------------------------
---------------------------
3. Static Methods
--------------------------------------------------------------------------------------------------------------------------
---------------------------
=>Static Methods are used for performing Universal Operations or Utility Operations
=>Static Methods definition must be preceded with a predefined decorator called
@staticmethod and it never takes "cls" or "self" but always takes object of other classes.
=>The Syntax for Static Method is
@staticmethod
def staticmethodname(list of Formal Params):
-------------------------------------
Utility Operation / Universal Operations
------------------------------------

=>Static Methods can be accessed w.r.t Class Name OR object name OR cls OR self

ClassName.static method name()


(OR)
ObjectName.static method name()
(OR)
cls.static method name()
(OR)
self.static method name()

--------------------------------------------------------------------------------------------------------------------------
--------------------------.

#program for Demonstrating Instance Methods


#InstanceMethodEx1.py
class Student:
def getstuddata(self): # Instance Method
print("ID of current in getstuddata()=",id(self))
self.sno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.marks=float(input("Enter Student Marks:"))
def dispstuddata(self):
print("Student Number:{}".format(self.sno))
print("Student Name:{}".format(self.sname))
print("Student Marks:{}".format(self.marks))

#main program
s1=Student()
s2=Student()
#read the Instance data to Object s1
print("-------------------------------------------------------")
print("ID of s1 in main program=",id(s1))
s1.getstuddata() # Calling Instance Method w.r.t Object Name
print("-------------------------------------------------------")
print("ID of s2 in main program=",id(s2))
s2.getstuddata() # Calling Instance Method w.r.t Object Name
print("-------------------------------------------------------")
print("First Object data")
print("-----------------------------")
s1.dispstuddata() # Calling Instance Method w.r.t Object Name
print("-------------------------------------------------------")
print("Second Object data")
print("-----------------------------")
s2.dispstuddata() # Calling Instance Method w.r.t Object Name
print("-----------------------------")

#Program for adding of Two Numbers by using Classes and Object with instance Method
#SumOpEx1.py
class Sum:
def readvalues(self):
self.a=float(input("Enter Value of a:"))
self.b=float(input("Enter Value of b:"))

def addvalues(self):
self.c=self.a+self.b

def dispvalues(self):
print("Val of a:{}".format(self.a))
print("Val of b:{}".format(self.b))
print("Sum:{}".format(self.c))

#main program
s1=Sum()
s1.readvalues()
s1.addvalues()
s1.dispvalues()

#program for Demonstrating Instance Methods


#InstanceMethodEx2.py
class Student:
def getstuddata(self): # Instance Method
print("ID of current in getstuddata()=",id(self))
self.sno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.marks=float(input("Enter Student Marks:"))
def dispstuddata(self):
print("Student Number:{}".format(self.sno))
print("Student Name:{}".format(self.sname))
print("Student Marks:{}".format(self.marks))

#main program
s1=Student()
s2=Student()
#read the Instance data to Object s1
print("-------------------------------------------------------")
s1.getstuddata() # Calling Instance Method w.r.t Object Name
s1.dispstuddata()# Calling Instance Method w.r.t Object Name
print("-------------------------------------------------------")
s2.getstuddata() # Calling Instance Method w.r.t Object Name
s2.dispstuddata() # Calling Instance Method w.r.t Object Name
print("-----------------------------")

#Program for Demonstrating Class Level Methods


#ClassLevelMethodEx1.py
class Employee:
@classmethod
def getcompanyname(cls): # Class Level Method
Employee.cname="IBM"
Employee.addr="HYD" # Here cname and addr are called Class Level Data
members

def getempdet(self): # Instance Method


self.eno=int(input("Enter Employee Number:"))
self.ename=input("Enter Employee Name:")
def dispempdet(self): # Instance Method
print("Employee Number:{}".format(self.eno))
print("Employee Name:{}".format(self.ename))
print("EMP Comp NAME:",Employee.cname)
print("EMP Comp ADDR:",Employee.addr)

#main program
Employee.getcompanyname() # calling Class Level method w.r.t Class Name
e1=Employee()
e1.getempdet()
e1.dispempdet()

#Program for Demonstrating Class Level Methods


#ClassLevelMethodEx2.py
class Employee:
@classmethod
def getcompanyname(cls): # Class Level Method
Employee.cname="IBM"
Employee.addr="HYD" # Here cname and addr are called Class Level Data
members

def getempdet(self): # Instance Method


self.eno=int(input("Enter Employee Number:"))
self.ename=input("Enter Employee Name:")
def dispempdet(self): # Instance Method
print("Employee Number:{}".format(self.eno))
print("Employee Name:{}".format(self.ename))
print("EMP Comp NAME:",Employee.cname)
print("EMP Comp ADDR:",Employee.addr)

#main program
e1=Employee()
e1.getcompanyname() # calling Class Level method w.r.t Object Name
e1.getempdet()
e1.dispempdet()
print("-------------------------------------------------------")
e2=Employee()
e2.getempdet()
e2.dispempdet()

#Program for Demonstrating Class Level Methods


#ClassLevelMethodEx3.py
class Employee:
@classmethod
def getcompanyname(cls): # Class Level Method
Employee.cname="IBM"
Employee.addr="HYD" # Here cname and addr are called Class Level Data
members

def getempdet(self): # Instance Method


self.eno=int(input("Enter Employee Number:"))
self.ename=input("Enter Employee Name:")
def dispempdet(self): # Instance Method
Employee.getcompanyname() # calling Class Level method w.r.t Class Name
print("Employee Number:{}".format(self.eno))
print("Employee Name:{}".format(self.ename))
print("EMP Comp NAME:",Employee.cname)
print("EMP Comp ADDR:",Employee.addr)

#main program
e1=Employee()
e1.getempdet()
e1.dispempdet()
print("-------------------------------------------------------")
e2=Employee()
e2.getempdet()
e2.dispempdet()
#Program for Demonstrating Class Level Methods
#ClassLevelMethodEx4.py
class Employee:
@classmethod
def getcompanyname(cls): # Class Level Method
cls.cname="IBM" # Here cname is called Class Level Data members
cls.getaddr()#calling Class Level method w.r.t Cls
@classmethod
def getaddr(cls):
cls.addr="HYD" # Here addr is called Class Level Data members

def getempdet(self): # Instance Method


self.eno=int(input("Enter Employee Number:"))
self.ename=input("Enter Employee Name:")
def dispempdet(self): # Instance Method
self.getcompanyname() # calling Class Level method w.r.t self
print("Employee Number:{}".format(self.eno))
print("Employee Name:{}".format(self.ename))
print("EMP Comp NAME:",Employee.cname)
print("EMP Comp ADDR:",Employee.addr)

#main program
e1=Employee()
e1.getempdet()
e1.dispempdet()
print("-------------------------------------------------------")
e2=Employee()
e2.getempdet()
e2.dispempdet()

#Program for Demonstrating Static Method


#StaticMethodEx1.py
class Student:
def getstuddata(self):
self.sno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.marks=float(input("Enter Student Marks:"))

class Employee:
def getempdata(self):
self.eno=int(input("Enter Employee Number:"))
self.ename=input("Enter Employee Name:")

class Teacher:
def getteacherdet(self):
self.tno=int(input("Enter Teacher ID:"))
self.tname=input("Enter Teacher Name:")
self.subject=input("Enter Teacher Subject:")
self.epr=int(input("Enter Teacher Experience:"))

class Hyd:
@staticmethod
def dispobjdata( obj):
print("---------------------------------------------")
for k,v in obj.__dict__.items():
print("\t{}--->{}".format(k,v))
print("---------------------------------------------")

#main program
s=Student()
e=Employee()
t=Teacher()
print("-----------------------------------------------")
s.getstuddata()
print("-----------------------------------------------")
e.getempdata()
print("-----------------------------------------------")
t.getteacherdet()
print("-----------------------------------------------")
Hyd.dispobjdata(s) # calling Static Method w.r.t Class name by passing any class object
Hyd.dispobjdata(e)
Hyd.dispobjdata(t)

#Program for Demonstrating Static Method


#StaticMethodEx2.py
class Student:
def getstuddata(self):
self.sno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.marks=float(input("Enter Student Marks:"))

class Employee:
def getempdata(self):
self.eno=int(input("Enter Employee Number:"))
self.ename=input("Enter Employee Name:")

class Teacher:
def getteacherdet(self):
self.tno=int(input("Enter Teacher ID:"))
self.tname=input("Enter Teacher Name:")
self.subject=input("Enter Teacher Subject:")
self.epr=int(input("Enter Teacher Experience:"))

class Hyd:
@staticmethod
def dispobjdata( obj,objinfo):
print("---------------------------------------------")
print("Information abount:{}".format(objinfo))
print("---------------------------------------------")
for k,v in obj.__dict__.items():
print("\t{}--->{}".format(k,v))
print("---------------------------------------------")

#main program
s=Student()
e=Employee()
t=Teacher()
print("-----------------------------------------------")
s.getstuddata()
print("-----------------------------------------------")
e.getempdata()
print("-----------------------------------------------")
t.getteacherdet()
print("-----------------------------------------------")
Hyd.dispobjdata(s,"Student") # calling Static Method w.r.t Class name by passing any class
object
Hyd.dispobjdata(e,"Employee")# calling Static Method w.r.t Class name by passing any class
object
Hyd.dispobjdata(t,"Teacher")# calling Static Method w.r.t Class name by passing any class
object

#Program for Demonstrating Static Method


#StaticMethodEx3.py
class Student:
def getstuddata(self):
self.sno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.marks=float(input("Enter Student Marks:"))

class Employee:
def getempdata(self):
self.eno=int(input("Enter Employee Number:"))
self.ename=input("Enter Employee Name:")

class Teacher:
def getteacherdet(self):
self.tno=int(input("Enter Teacher ID:"))
self.tname=input("Enter Teacher Name:")
self.subject=input("Enter Teacher Subject:")
self.epr=int(input("Enter Teacher Experience:"))

class Hyd:
@staticmethod
def dispobjdata( obj,objinfo):
print("---------------------------------------------")
print("Information abount:{}".format(objinfo))
print("---------------------------------------------")
for k,v in obj.__dict__.items():
print("\t{}--->{}".format(k,v))
print("---------------------------------------------")

#main program
s=Student()
e=Employee()
t=Teacher()
print("-----------------------------------------------")
s.getstuddata()
print("-----------------------------------------------")
e.getempdata()
print("-----------------------------------------------")
t.getteacherdet()
print("-----------------------------------------------")
h=Hyd()
h.dispobjdata(s,"Student") # calling Static Method w.r.t object name by passing any class
object
h.dispobjdata(e,"Employee")# calling Static Method w.r.t object name by passing any class
object
h.dispobjdata(t,"Teacher")# calling Static Method w.r.t object name by passing any class object

#Program for Demonstrating Static Method


#StaticMethodEx4.py
class Student:
def getstuddata(self):
self.sno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.marks=float(input("Enter Student Marks:"))

class Employee:
def getempdata(self):
self.eno=int(input("Enter Employee Number:"))
self.ename=input("Enter Employee Name:")

class Teacher:
def getteacherdet(self):
self.tno=int(input("Enter Teacher ID:"))
self.tname=input("Enter Teacher Name:")
self.subject=input("Enter Teacher Subject:")
self.epr=int(input("Enter Teacher Experience:"))

class Hyd:
@staticmethod
def dispobjdata( obj,objinfo):
print("---------------------------------------------")
print("Information abount:{}".format(objinfo))
print("---------------------------------------------")
for k,v in obj.__dict__.items():
print("\t{}--->{}".format(k,v))
print("---------------------------------------------")
@classmethod
def getinformation(cls,obj,objinfo):
cls.dispobjdata(obj,objinfo) # Calling Static Method From Class Level Method
w.r.t cls

#main program
s=Student()
e=Employee()
t=Teacher()
print("-----------------------------------------------")
s.getstuddata()
print("-----------------------------------------------")
e.getempdata()
print("-----------------------------------------------")
t.getteacherdet()
print("-----------------------------------------------")
Hyd.getinformation(s,"Student") # calling Class Level Method w.r.t class name by passing any
class object
Hyd.getinformation(e,"Employee")# calling Class Level Methodw.r.t class name by passing
any class object
Hyd.getinformation(t,"Teacher")# calling Class Level Method w.r.t class name by passing any
class object

#Program for Demonstrating Static Method


#StaticMethodEx5.py
class Student:
def getstuddata(self):
self.sno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.marks=float(input("Enter Student Marks:"))

class Employee:
def getempdata(self):
self.eno=int(input("Enter Employee Number:"))
self.ename=input("Enter Employee Name:")

class Teacher:
def getteacherdet(self):
self.tno=int(input("Enter Teacher ID:"))
self.tname=input("Enter Teacher Name:")
self.subject=input("Enter Teacher Subject:")
self.epr=int(input("Enter Teacher Experience:"))

class Hyd:
@staticmethod
def dispobjdata( obj,objinfo):
print("---------------------------------------------")
print("Information abount:{}".format(objinfo))
print("---------------------------------------------")
for k,v in obj.__dict__.items():
print("\t{}--->{}".format(k,v))
print("---------------------------------------------")
@classmethod
def getinformation(cls,obj,objinfo):
Hyd.dispobjdata(obj,objinfo) # Calling Static Method From Class Level Method
w.r.t cls

#main program
s=Student()
e=Employee()
t=Teacher()
print("-----------------------------------------------")
s.getstuddata()
print("-----------------------------------------------")
e.getempdata()
print("-----------------------------------------------")
t.getteacherdet()
print("-----------------------------------------------")
Hyd.getinformation(s,"Student") # calling Class Level Method w.r.t class name by passing any
class object
Hyd.getinformation(e,"Employee")# calling Class Level Methodw.r.t class name by passing
any class object
Hyd.getinformation(t,"Teacher")# calling Class Level Method w.r.t class name by passing any
class object

#Program for Demonstrating Static Method


#StaticMethodEx6.py
class Student:
def getstuddata(self):
self.sno=int(input("Enter Student Number:"))
self.sname=input("Enter Student Name:")
self.marks=float(input("Enter Student Marks:"))

class Employee:
def getempdata(self):
self.eno=int(input("Enter Employee Number:"))
self.ename=input("Enter Employee Name:")

class Teacher:
def getteacherdet(self):
self.tno=int(input("Enter Teacher ID:"))
self.tname=input("Enter Teacher Name:")
self.subject=input("Enter Teacher Subject:")
self.epr=int(input("Enter Teacher Experience:"))

class Hyd:
@staticmethod
def dispobjdata( obj,objinfo):
print("---------------------------------------------")
print("Information abount:{}".format(objinfo))
print("---------------------------------------------")
for k,v in obj.__dict__.items():
print("\t{}--->{}".format(k,v))
print("---------------------------------------------")
def getinformation(self,obj,objinfo):
self.dispobjdata(obj,objinfo) # Calling Static Method From Instance Method w.r.t
self

#main program
s=Student()
e=Employee()
t=Teacher()
print("-----------------------------------------------")
s.getstuddata()
print("-----------------------------------------------")
e.getempdata()
print("-----------------------------------------------")
t.getteacherdet()
print("-----------------------------------------------")
h=Hyd()
h.getinformation(s,"Student") # calling Class Level Method w.r.t class name by passing any
class object
h.getinformation(e,"Employee")# calling Class Level Methodw.r.t class name by passing any
class object
h.getinformation(t,"Teacher")# calling Class Level Method w.r.t class name by passing any
class object

day --- 72
=============================================
Constructors in Python
=============================================
=>The purpose of Constructors in python is that " To initlize the object".
=>Initlizing the object is nothing but Placing our own data in object without leaving object
empty.
---------------------------------------
Definition of Constructor
---------------------------------------
=>A Constructor is one of the special method which is automatically / Implicitly called by
PVM During Object Creation and whose purpose is to initlize the object..
-----------------------------------------------------------------
Syntax for defining Constructor:
-----------------------------------------------------------------
def __init__(self, list of formal params if any):
--------------------------------------------
Block of Statements
Performs Initlization
--------------------------------------------
-----------------------------------------------------------------
Rules or Properties of Constructors
-----------------------------------------------------------------
1. The Name of the constructor is always def __init__(self,....)
2. Constructors will call automatically / implciitly by PVM during object creation
3. Constructors will not return any value except None.
4. In Python, Constructors can participate in Inheritance Process.
5. In Python, Conctructors can be Overridden
--------------------------------------------------------------------------------------------------------.

#Non-Const.ex.py
class Employee:
def getempdata(self):
self.eno=10
self.ename="Rossum"

#main program
e1=Employee() # Object Creation
print("Content of e1=",e1.__dict__) # {}
e1.getempdata() # We are calling the method Explicitly
print("Content of e1=",e1.__dict__) # {........}.

#ConstEx1.py
class Employee:
def __init__(self): # Default Constructor
print("i am from Constructor")
self.eno=10
self.ename="Rossum"

#main program
e1=Employee() # Object Creation----PVM Calls Constructor
print("Content of e1=",e1.__dict__) # {}
e2=Employee() # Object Creation----PVM Calls Constructor
print("Content of e1=",e1.__dict__) # {}

#ConstEx2.py
class Employee:
def __init__(self,eno,ename): # Parameterized Constructor
print("i am from Constructor")
self.eno=eno
self.ename=ename

#main program
e1=Employee(100,"Rossum") # Object Creation----PVM Calls Parameterized Constructor
print("Content of e1=",e1.__dict__) # {}
e2=Employee(200,"Travis") # Object Creation----PVM Calls Constructor
print("Content of e2=",e2.__dict__) # {}

#Program for default and Parameterized Constructor


#DefaultParamConstEx1.py
class Test:
def __init__(self,a=1,b=2):
print("Default / Parametrized Constructor")
self.a=a
self.b=b
print("----------------------------------------")
print("Val of a:{}".format(self.a))
print("Val of b:{}".format(self.b))
print("----------------------------------------")

#main program
t1=Test() # Object Creation--PVM Calls Default Constructor
t2=Test(10,20) # Object Creation--PVM Calls Parameterized Constructor
t3=Test(100) # Object Creation--PVM Calls Parameterized Constructor
t4=Test(b=100) # Object Creation--PVM Calls Parameterized Constructor
t5=Test(b=1000,a=2000) # Object Creation--PVM Calls Parameterized Constructo

=============================================
Types of Constructors in Python
=============================================
=>In Python Programming, we have two types of Constructors. they are
1. Default or Parameter Less Constructor
2. Parameterized Constructor
--------------------------------------------------------------------------------------------------------------------------
---------------
1. Default or Parameter Less Constructor
--------------------------------------------------------------------------------------------------------------------------
---------------
=>A Default or Parameter Less Constructor is one, which never takes any Formal Parameters except
self.
=>The purpose of Default or Parameter Less Constructor is that " To Initlize Multiple objects of
same
class with Same Values".
=>Syntax: def __init__(self):
---------------------------
Block of statements
Performs Initlization Process
---------------------------
Example:
#program for demonstrating Default Constructor
#DefaultConstEx1.py
class Test:
def __init__(self):
print("i am from default constructor:")
self.a=10
self.b=20
print("\ta={}\tb={}".format(self.a,self.b))

#main program
t1=Test()# Object creation calls default constructor
t2=Test()# Object creation calls default constructor
t3=Test()# Object creation calls default constructor
--------------------------------------------------------------------------------------------------------------------------
---------------
2. Parameterized Constructor
--------------------------------------------------------------------------------------------------------------------------
---------------
=>A Parameterized Constructor is one, which always takes Formal Parameters after self.
=>The purpose of Parameterized Constructor is that " To Initlize Multiple objects of same
class with Different Values".
=>Syntax: def __init__(self,list of formal params):
---------------------------
Block of statements
Performs Initlization Process
---------------------------
Examples:
-----------------
#program for demonstrating Parametrized Constructor
#ParamConstEx1.py
class Test:
def __init__(self,k,v):
print("i am from Parametrized constructor:")
self.a=k
self.b=v
print("\ta={}\tb={}".format(self.a,self.b))

#main program
t1=Test(10,20)# Object creation calls Parametrized Constructor
t2=Test(100,200)# Object creation calls Parametrized Constructor
t3=Test(1000,2000)# Object creation calls Parametrized Constructor
--------------------------------------------------------------------------------------------------------------------------
---------------
Most Imp Point:
-----------------------------
Note: In Class of Python, we can't define both default and Parameterized constructors bcoz PVM can
remember only latest constructor (due to its interpretation Process) . To full fill the need of both
default and parameterized constructors , we define single constructor with default parameter
mechanism.

#program for demonstrating Parametrized and DefaultConstructor


#ParamDefualtConstEx1.py
class Test:
def __init__(self,k=1,v=2): # default and parameterized
print("i am from default / Parametrized constructor:")
self.a=k
self.b=v
print("\ta={}\tb={}".format(self.a,self.b))

#main program
t1=Test()# Object creation calls default Constructor
t2=Test(10,20)# Object creation calls Parametrized Constructor
=============================================
Constructors in Python
=============================================
Index
----------
=>purpose of Constructor
=>Definition of Constructor
=>Syntax for defining Constructor
=>Rules / Properties of Constructors
=>Types of Constructors
=>Programming Examples
-----------------------------------------------------------------------------------------------------------.

#program for Generating student Marks Report


#StudentMarksReportWithDB.py
#Validation of Student Number
class StudentMarksReport:
def __init__(self):
while(True):
self.sno=int(input("Enter Student Number:"))
if(self.sno>0):
break
print("\t{} Is Invalid Student Number:".format(self.sno))
#Accept Student Name
self.sname=input("Enter Student Name:")
#Validation of C lang Marks(0-100)
while(True):
self.cm=int(input("Enter Marks in C:"))
if(self.cm>=0) and (self.cm<=100):
break
print("\t{} Is Invalid Marks in C:".format(self.cm))
#Validation of CPP lang Marks(0-100)
while(True):
self.cppm=int(input("Enter Marks in C++:"))
if(0<=self.cppm<=100):
break
print("\t{} Is Invalid Marks in C++:".format(self.cppm))

#Validation of PYTHON lang Marks(0-100)


while(True):
self.pym=int(input("Enter Marks in PYTHON:"))
if(0<=self.pym<=100):
break
print("\t{} Is Invalid Marks in PYTHON:".format(self.pym))
def compute(self):
#Compute TotalMarks and Percentage
self.totmarks=self.cm+self.cppm+self.pym
self.percent=(self.totmarks/300)*100
#Decide the grade
if(self.cm<40) or (self.cppm<40) or (self.pym<40):
self.grade="FAIL"
else:
if(self.totmarks>=250) and (self.totmarks<=300):
self.grade="DISTINCTION"
elif(self.totmarks>=200) and (self.totmarks<=249):
self.grade="FIRTST"
elif(self.totmarks>=150) and (self.totmarks<=199):
self.grade="SECOND"
elif(self.totmarks>=120) and (self.totmarks<=149):
self.grade="THIRD"
def dispmarksreport(self):
#Display Student Marks Report
print("="*50)
print("\t\tStudent Marks Report:")
print("="*50)
print("\tStudent Number:{}".format(self.sno))
print("\tStudent Name:{}".format(self.sname))
print("\tStudent Marks in C:{}".format(self.cm))
print("\tStudent Marks in C++:{}".format(self.cppm))
print("\tStudent Marks in PYTHON:{}".format(self.pym))
print("-"*50)
print("\tStudent Total Marks:{}".format(self.totmarks))
print("\tStudent Percentage of Marks:{}".format(self.percent))
print("\tStudent Grade:{}".format(self.grade))
print("="*50)

#main program
so=StudentMarksReport()
so.compute()
so.dispmarksreport()

#program for Generating student Marks Report


#StudentMarksReportWithDBMySQL.py
#mysql> create table result(sno int,name varchar(10),cm int,cpp int,python int,totmarks int,percent
float,grade varchar(13));
#Validation of Student Number
import mysql.connector
class StudentMarksReport:
def __init__(self):
while(True):
self.sno=int(input("Enter Student Number:"))
if(self.sno>0):
break
print("\t{} Is Invalid Student Number:".format(self.sno))
#Accept Student Name
self.sname=input("Enter Student Name:")
#Validation of C lang Marks(0-100)
while(True):
self.cm=int(input("Enter Marks in C:"))
if(self.cm>=0) and (self.cm<=100):
break
print("\t{} Is Invalid Marks in C:".format(self.cm))
#Validation of CPP lang Marks(0-100)
while(True):
self.cppm=int(input("Enter Marks in C++:"))
if(0<=self.cppm<=100):
break
print("\t{} Is Invalid Marks in C++:".format(self.cppm))

#Validation of PYTHON lang Marks(0-100)


while(True):
self.pym=int(input("Enter Marks in PYTHON:"))
if(0<=self.pym<=100):
break
print("\t{} Is Invalid Marks in PYTHON:".format(self.pym))
def compute(self):
#Compute TotalMarks and Percentage
self.totmarks=self.cm+self.cppm+self.pym
self.percent=(self.totmarks/300)*100
#Decide the grade
if(self.cm<40) or (self.cppm<40) or (self.pym<40):
self.grade="FAIL"
else:
if(self.totmarks>=250) and (self.totmarks<=300):
self.grade="DISTINCTION"
elif(self.totmarks>=200) and (self.totmarks<=249):
self.grade="FIRTST"
elif(self.totmarks>=150) and (self.totmarks<=199):
self.grade="SECOND"
elif(self.totmarks>=120) and (self.totmarks<=149):
self.grade="THIRD"
def dispmarksreport(self):
#Display Student Marks Report
print("="*50)
print("\t\tStudent Marks Report:")
print("="*50)
print("\tStudent Number:{}".format(self.sno))
print("\tStudent Name:{}".format(self.sname))
print("\tStudent Marks in C:{}".format(self.cm))
print("\tStudent Marks in C++:{}".format(self.cppm))
print("\tStudent Marks in PYTHON:{}".format(self.pym))
print("-"*50)
print("\tStudent Total Marks:{}".format(self.totmarks))
print("\tStudent Percentage of Marks:{}".format(self.percent))
print("\tStudent Grade:{}".format(self.grade))
print("="*50)
def savestuddata(self):
try:
#write PDBC Code
con=mysql.connector.connect(host="127.0.0.1",
user="root",

passwd="root",

database="batch6pm")
cur=con.cursor()
iq="insert into result values(%d,'%s',%d,%d,%d,%d,%f,'%s')"
cur.execute(iq %
(self.sno,self.sname,self.cm,self.cppm,self.pym,self.totmarks,round(self.percent,2),self.grade))
con.commit()
print("{} Student Record Inserted--Verify".format(cur.rowcount))
except mysql.connector.DatabaseError as db:
print("Problem in MySQL",db)

#main program
so=StudentMarksReport()
so.compute()
so.dispmarksreport()
so.savestuddata()

===================================================
objects in Python
===================================================
=>When we define a class, memory space is not created for Data Members and Methods but whose
memory is created when we create an object w.r.t class name.
=>The Purpose of creating an object is that "To store the Data".
=>To do any Data Processing, It is mandatory to create an object.
=>To create an object, there must exists a class Definition otherwise we get NameError.

Definition of object:
-----------------------------------
=>Instance of a class is called object ( Instance is nothing but allocating sufficient memory space for
the Data Members and Methods of a class).
-------------------------------------------------
Syntax for creating an object
-------------------------------------------------
varname=classname()
(or)
varname=classname(Val1,Val2...val-n)

Examples: create an object of Student

so=Student()
Example:- create an object Employee

eo=Employee(10,"Rossum")
-----------------------------------------------------------------------------------------------
Differences Between Classes and Objects
-----------------------------------------------------------------------
Class:
------------
1) A class is a collection of Data Members and Methods
2) When we define a class, memory space is not created for Data Members and Methods and it can be
treated as specification / model for real time application.
3) Definition of a perticular exists only once
4) When we develop any Program with OOPs principles, Class Definition Loaded First in main
memory only once.
---------------
Objects:
--------------
1) Instance of a class is called Object
2) When we create an object, we get the memory space for Data members and Methods of Class.
3) w.r.t One class Definition, we can create multiple objects.
4) we can crate an object after loading the class definition otherwise we get NameError
===============================X=================================

day --- 73
======================================
Destructors in Python
and
Garbage Collector
======================================
=>We know that Garbage Collector is one of the in-built program in python, which is running behind
of every python program and whose is role is to collect un-used memory space and it improves the
performance of python based applications.
=>Every Garbage Collector Program is internally calling its Own Destructor Functions.
=>The destructor function name in python is def __del__(self).
=>By default ,The destructor always called by Garbage Collector when the program execution
completed for de-allocating the memory space of objects which are used in that program. Where as
constructor called By PVM implicitly when object is created for initlizing the object.

=>When the program execution is completed, GC calls its own destructor to de-allocate the memory
space of objects present in program and it is called automatic Garbage Collection.

=>Hence , We have THREE programming conditions for calling GC and to make the garbage
collector to call destructor Function.

a) By default (or) automatically GC calls destructor, when the program execution completed.
b) Make the object reference as None for calling Forcefull Garbage Collection
Syntax : objname=None
c) delete the object by using del operator for calling Forcefull Garbage Collection
Syntax:- del objname

-----------------
=>Syntax:
-----------------
def
__del__(self):
-----------------------
-----------------------
=>No Need to write destructor in class of Python bcoz GC contains its own Destructor
=======================================================================
Garbage Collector
--------------------------------------------------------------------------------------------------------------------------
-
=>Garbage Collector contains a pre-defined module called "gc"
=>Here gc contains the following Functions.

1) isenabled()
2) enable()
3) disable()
=>GC is not under the control of Programmer but it always maintained and mangaged by OS
and PVM.
NOTE: Python Programmers need not to write destructor method / function and need not
to deal with Garbage Collection Process by using gc module bcoz PVM and OS takes care
about Automatic Garbage Collection Process.
==============================x=========================================
===
.#Program for demonstrating Destructors
#non-destex1.py
class Employee:
def __init__(self,eno,ename):
self.eno=eno
self.ename=ename
print("--------------------------------------------------")
print("Employee Number:{}".format(self.eno))
print("Employee Name:{}".format(self.ename))
print("--------------------------------------------------")

#Main program
print("Program Execution Started")
e1=Employee(10,"Rossum")
e2=Employee(20,"Travis")
print("Program Execution Ended")

#Program for demonstrating Destructors


#destex1.py
import time
class Employee:
def __init__(self,eno,ename):
print("I am from Constructor")
self.eno=eno
self.ename=ename
print("--------------------------------------------------")
print("Employee Number:{}".format(self.eno))
print("Employee Name:{}".format(self.ename))
print("--------------------------------------------------")
def __del__(self):
print("Garbage Collectors calls __del__(self) for De-allocating Mem Space")

#Main program
print("Program Execution Started")
e1=Employee(10,"Rossum")
e2=Employee(20,"Travis")
print("Program Execution Ended")
time.sleep(10)
#By default after program execution completed GC calls Its Destructor automatically for de-
allocating the memory space. This Process is Called Automatic Garbage Collection.

#Program for demonstrating Destructors


#destex2.py
import time,sys
class Employee:
def __init__(self,eno,ename):
print("I am from Constructor")
self.eno=eno
self.ename=ename
print("--------------------------------------------------")
print("Employee Number:{}".format(self.eno))
print("Employee Name:{}".format(self.ename))
print("--------------------------------------------------")
def __del__(self):
print("Garbage Collectors calls __del__(self) for De-allocating Mem Space")
global totmemspace
totmemspace=totmemspace-sys.getsizeof(self)
print("Now Avaliable Memory Space:{}".format(totmemspace))

#Main program
print("Program Execution Started")
e1=Employee(10,"Rossum")
e2=Employee(20,"Travis")
e3=Employee(30,"Ritche")
#to find the memory space of any object----sys.getsize(objectname)
totmemspace=sys.getsizeof(e1)+sys.getsizeof(e2)+sys.getsizeof(e3)
print("Total Memory space =",totmemspace)
print("---------------------------------------------------------------")
print("Program Execution Ended")
time.sleep(5)

#Program for demonstrating Destructors


#destex3.py
import time,sys
class Employee:
def __init__(self,eno,ename):
print("I am from Constructor")
self.eno=eno
self.ename=ename
print("--------------------------------------------------")
print("Employee Number:{}".format(self.eno))
print("Employee Name:{}".format(self.ename))
print("--------------------------------------------------")
def __del__(self):
print("Garbage Collectors calls __del__(self) for De-allocating Mem Space")

#Main program
print("Program Execution Started")
e1=Employee(10,"Rossum")
print("No Longer Interrested in maintaining the memory space for e1 object")
time.sleep(5)
e1=None # GC calls Destrutor forcefully--Forceful Garbage Collection
e2=Employee(20,"Travis")
e3=Employee(30,"Ritche")
print("---------------------------------------------------------------")
print("Program Execution Ended")
time.sleep(5)

#Program for demonstrating Destructors


#destex4.py
import time,sys
class Employee:
def __init__(self,eno,ename):
print("I am from Constructor")
self.eno=eno
self.ename=ename
print("--------------------------------------------------")
print("Employee Number:{}".format(self.eno))
print("Employee Name:{}".format(self.ename))
print("--------------------------------------------------")
def __del__(self):
print("Garbage Collectors calls __del__(self) for De-allocating Mem Space")

#Main program
print("Program Execution Started")
e1=Employee(10,"Rossum")
print("No Longer Interrested in maintaining the memory space for e1 object")
time.sleep(5)
e1=None # GC calls Destrutor forcefully--Forceful Garbage Collection
e2=Employee(20,"Travis")
print("No Longer Interrested in maintaining the memory space for e2 object")
time.sleep(5)
e2=None # GC calls Destrutor forcefully--Forceful Garbage Collection
e3=Employee(30,"Ritche")
print("No Longer Interrested in maintaining the memory space for e3 object")
time.sleep(5)
e3=None # GC calls Destrutor forcefully--Forceful Garbage Collection
print("---------------------------------------------------------------")
print("Program Execution Ended")
time.sleep(5)
#Program for demonstrating Destructors
#destex5.py
import time,sys
class Employee:
def __init__(self,eno,ename):
print("I am from Constructor")
self.eno=eno
self.ename=ename
print("--------------------------------------------------")
print("Employee Number:{}".format(self.eno))
print("Employee Name:{}".format(self.ename))
print("--------------------------------------------------")
def __del__(self):
print("Garbage Collectors calls __del__(self) for De-allocating Mem Space")

#Main program
print("Program Execution Started")
e1=Employee(10,"Rossum")
print("No Longer Interrested in maintaining the memory space for e1 object")
time.sleep(5)
del e1 # GC calls Destrutor forcefully--Forceful Garbage Collection
e2=Employee(20,"Travis")
print("No Longer Interrested in maintaining the memory space for e2 object")
time.sleep(5)
del e2 # GC calls Destrutor forcefully--Forceful Garbage Collection
e3=Employee(30,"Ritche")
print("No Longer Interrested in maintaining the memory space for e3 object")
time.sleep(5)
del e3 # GC calls Destrutor forcefully--Forceful Garbage Collection
print("---------------------------------------------------------------")
print("Program Execution Ended")
time.sleep(5)

#Program for demonstrating Destructors


#destex6.py
import time,sys
class Employee:
def __init__(self,eno,ename):
print("I am from Constructor")
self.eno=eno
self.ename=ename
print("--------------------------------------------------")
print("Employee Number:{}".format(self.eno))
print("Employee Name:{}".format(self.ename))
print("--------------------------------------------------")
def __del__(self):
print("Garbage Collectors calls __del__(self) for De-allocating Mem Space")

#Main program
print("Program Execution Started")
e1=Employee(10,"Rossum")
e2=e1 # Deep Copy
e3=e1 # Deep copt
print(e1.__dict__, id(e1))
print(e2.__dict__,id(e2))
print(e3.__dict__,id(e3))
print("---------------------------------------------------------------")
print("Program Execution Ended")
time.sleep(5)

#Program for demonstrating Destructors


#destex7.py
import time,sys
class Employee:
def __init__(self,eno,ename):
print("I am from Constructor")
self.eno=eno
self.ename=ename
print("--------------------------------------------------")
print("Employee Number:{}".format(self.eno))
print("Employee Name:{}".format(self.ename))
print("--------------------------------------------------")
def __del__(self):
print("Garbage Collectors calls __del__(self) for De-allocating Mem Space")

#Main program
print("Program Execution Started")
e1=Employee(10,"Rossum")
e2=e1 # Deep Copy
e3=e1 # Deep cop5
print("No Longer Interrested in maintaining the memory space for e1 object")
time.sleep(5)
e1=None # GC never calls Destrutor forcefully--bcoz e2 and e3 points to memory space
print("No Longer Interrested in maintaining the memory space for e2 object")
time.sleep(5)
del e2 # GC never calls Destrutor forcefully--bcoz e3 points to memory space
print("No Longer Interrested in maintaining the memory space for e3 object")
time.sleep(5)
del e3 # GC calls Destrutor forcefully--bcoz No Objects points Object memory space.
print("---------------------------------------------------------------")
print("Program Execution Ended")
time.sleep(5)

#program for demonstarting gabage Collector running Process


#GCEX1.py
import gc
print("Program Execution started")
print("Initially, Is GC Running:",gc.isenabled()) # True
a=100
b=200
c=a+b
print("Val of a={}".format(a))
gc.disable()
print("Val of b={}".format(b))
print("Now Is GC Running:",gc.isenabled()) # False
print("sum={}".format(c))
gc.enable()
print("Now Is GC Running:",gc.isenabled()) # True
print("Program Execution Ended")

#Program for demonstrating Destructors


#GCEX2.py
import time,sys,gc
class Employee:
def __init__(self,eno,ename):
print("I am from Constructor")
self.eno=eno
self.ename=ename
print("--------------------------------------------------")
print("Employee Number:{}".format(self.eno))
print("Employee Name:{}".format(self.ename))
print("--------------------------------------------------")
def __del__(self):
print("Garbage Collectors calls __del__(self) for De-allocating Mem Space")
global totmemspace
totmemspace=totmemspace-sys.getsizeof(self)
print("Now Avaliable Memory Space:{}".format(totmemspace))

#Main program
print("Program Execution Started")
print("Initially, Is GC Running:",gc.isenabled()) # True
print("-------------------------------------------------------")
gc.disable()
print("Now, Is GC Running after disable:",gc.isenabled()) # False
time.sleep(10)
e1=Employee(10,"Rossum")
e2=Employee(20,"Travis")
e3=Employee(30,"Ritche")
#to find the memory space of any object----sys.getsize(objectname)
totmemspace=sys.getsizeof(e1)+sys.getsizeof(e2)+sys.getsizeof(e3)
print("Total Memory space =",totmemspace)bbvb
print("---------------------------------------------------------------")
print("Program Execution Ended")
print("Now, Is GC Running after disable:",gc.isenabled()) # False
time.sleep(5)

day – 74

=============================================
Data Encapsulation and Data Abstraction
=============================================
Data Encapsulation:
--------------------------------
=>The Process of Hiding the confidential Information / Data / Methods from external Programmers /
end users is called Data Encapsulation.
=>The Purpose of Encapsulation concept is that "To Hide Confidental Information / Features of Class
(Data Members and Methods ) ".
=>Data Encapsulation can be applied in two levels. They are
a) At Data Members Level
b) At Methods Level

=>To implement Data Encapsulation in python programming, The Data Members , Methods must
be preceded with double under score ( _ _ )

Syntax1:- (Data member Lavel )

class <ClassName>:
def methodname(self):
self.__Data MemberName1=Value1
self.__Data MemberName2=Value2
--------------------------------------------------
self.__Data MemberName-n=Value-n

(OR)

Syntax1:- ( Data member Lavel )

class <ClassName>:
def __init__(self):
self.__Data MemberName1=Value1
self.__Data MemberName2=Value2
--------------------------------------------------
self.__Data MemberName-n=Value-n

Syntax2:- (Method Level)

class <ClassName>:
def __methodname(self):
self.Data MemberName1=Value1
self.Data MemberName2=Value2
--------------------------------------------------
self.Data MemberName-n=Value-n

==============================================================
Data Abstraction:
-------------------------------
=>The Process of retrieving / extracting Essential Details without considering Hidden Details is
called Data Abstraction.
--------------------------------------------------------------------------------------------------------------------------
--------
Note:- We can't apply Data Encapsulation on Constructors in Python but whose Initlized Data
Memebrs can be encapsulated.
#Account1.py------File name and Module Name ----Data Encapsulation
class Account:
def __init__(self):
self.__acno=1234
self.cname="Naresh"
self.__bal=3.4
self.__pin=8989
self.bname="SBI"

#others1.py--Data Abstraction
from Account1 import Account
ac=Account()
#print("Account Number:{}".format(ac.acno))
print("Account Holder Name:{}".format(ac.cname))
#print("Account Balance:{}".format(ac.bal))
#print("Account Pin:{}".format(ac.pin))
print("Account Branch Name:{}".format(ac.bname))

#Account2.py------File name and Module Name ----Data Encapsulation


class Account:
def getaccdetails(self):
self.__acno=1234
self.cname="Naresh"
self.__bal=3.4
self.__pin=8989
self.bname="SBI"

#others2.py--Data Abstraction
from Account2 import Account
ac=Account()
ac.getaccdetails()
#print("Account Number:{}".format(ac.acno))
print("Account Holder Name:{}".format(ac.cname))
#print("Account Balance:{}".format(ac.bal))
#print("Account Pin:{}".format(ac.pin))
print("Account Branch Name:{}".format(ac.bname))

#Account3.py------File name and Module Name ----Data Encapsulation


class Account:
def __getaccdetails(self):
self.acno=1234
self.cname="Naresh"
self.bal=3.4
self.pin=8989
self.bname="SBI"

#others3.py--Data Abstraction
from Account3 import Account
ac=Account()
#ac.getaccdetails()
#print("Account Number:{}".format(ac.acno))
#print("Account Holder Name:{}".format(ac.cname))
#print("Account Balance:{}".format(ac.bal))
#print("Account Pin:{}".format(ac.pin))
#print("Account Branch Name:{}".format(ac.bname))

#Account4.py------File name and Module Name ----Data Encapsulation


class __Account:
def getaccdetails(self):
self.acno=1234
self.cname="Naresh"
self.bal=3.4
self.pin=8989
self.bname="SBI"

#Note: Once we we make class name preceded with __ then that class name can't be imported in
Other Programs.

#others4.py--Data Abstraction
from Account4 import Account # will get Error bcoz Account made as encapsulated __Account
ac=Account()
ac.getaccdetails()
print("Account Number:{}".format(ac.acno))
print("Account Holder Name:{}".format(ac.cname))
print("Account Balance:{}".format(ac.bal))
print("Account Pin:{}".format(ac.pin))
print("Account Branch Name:{}".format(ac.bname))

#Account5.py------File name and Module Name ----Data Encapsulation


class Account:
def ______init__(self):
self.acno=1234
self.cname="Naresh"
self.bal=3.4
self.pin=8989
self.bname="SBI"

#others5.py--Data Abstraction
from Account5 import Account
ac=Account()
ac.______init__() # Method Call
print("Account Number:{}".format(ac.acno))
print("Account Holder Name:{}".format(ac.cname))
print("Account Balance:{}".format(ac.bal))
print("Account Pin:{}".format(ac.pin))
print("Account Branch Name:{}".format(ac.bname))

#SameAccount.py------File name and Module Name ----Data Encapsulation


class Account:
def __init__(self):
self.__acno=1234
self.cname="Naresh"
self.__bal=3.4
self.__pin=8989
self.bname="SBI"
def __samecustomer(self):
print("---------------------------------------------")
print("Current customer details")
print("---------------------------------------------")
print("Account Number:{}".format(self.__acno))
print("Account Holder Name:{}".format(self.cname))
print("Account Balance:{}".format(self.__bal))
print("Account Pin:{}".format(self.__pin))
print("Account Branch Name:{}".format(self.bname))
print("---------------------------------------------")
def show(self):
Account.__samecustomer(self)

#main program
ao=Account() # Object Creation calls default Constructor
ao.show()

which will except student number ,student name ,student marks and save those details in a file by
usinfg clases and objects with pickling operations

write a python program whicg will read student records from the file and display by usinf clases and
objects with unpickiling operations

#Student.py--File Name and Module Name


class Student:
def __init__(self,sno,sname,marks):
self.sno=sno
self.sname=sname
self.marks=marks
def dispstuddata(self):
print("{}\t{}\t{}".format(self.sno,self.sname,self.marks))

#Program saving the details of Student in studentpick file


#StudentPickle.py--File Name and Module Name
import pickle
from Student import Student
class StudentPickle:
def savestuddata(self):
with open("studpick.data","ab") as fp:
#accept the student data from keyboard
print("-"*50)
sno=int(input("Enter Student Number:"))
sname=input("Enter Student Name:")
marks=float(input("Enter Student Marks:"))
#create an object of student class
s=Student(sno,sname,marks) # Object Creation--PVM Calls Parameterized Constructor
print("-"*50)
pickle.dump(s,fp)
print("Student record saved in a file successfully")
print("-"*50)

#Program for reading the student records from file(studpick.data)


#StudentUnPickle.py--File Name and Module Name
import pickle
class StudentUnPickle:
def readstudrecords(self):
try:
with open("studpick.data","rb") as fp:
print("--------------------------------------------------------")
while(True):
try:
obj=pickle.load(fp)
obj.dispstuddata()
except EOFError:
print("--------------------------------------------------------")
break

except FileNotFoundError:
print("File does not exist")

#StudentPickMenu.py--File Name and Module Name


class Menu:
def menu(self):
print("-------------------------------------------------------")
print("\tStudent Operations")
print("-------------------------------------------------------")
print("\t1. Student Pickle Operation")
print("\t2. Student UnPickle Operation")
print("\t3. Exit")
print("-----------------------------------------------------
#StudentPickUnPickProgram.py
from StudentPickMenu import Menu
from StudentPickle import StudentPickle
from StudentUnPickle import StudentUnPickle
while(True):
Menu().menu()
try:
ch=int(input("Enter Ur Choice:"))
match(ch):
case 1:
so=StudentPickle()
so.savestuddata()
case 2:
sp=StudentUnPickle()
sp.readstudrecords()
case 3:
print("Thx for this Program")
break
case _:
print("Ur Selection Operation is wrong-try again")
except ValueError:
print("Don't Enter alnums,strs and symbols for Choice")

You might also like