0% found this document useful (0 votes)
12 views

Python Notes

Uploaded by

vinayduddukuri17
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Python Notes

Uploaded by

vinayduddukuri17
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 307

PYTHON FULL STACK NOTES

==============================================================
R eal Time Applications Developed by Using PYTHON Programming
==============================================================
=>By using python Programming Lang and Some Combined technolgies , we develop the following Real Time
Applications.

1. Development of Web Applications (Web Sites )

a) Java Programming Lang<----------Tech: Servlets, JSP, Hibernate,Spring, Spring Boot, Spring with Micro
Services...etc

(Sun Micro System INC USA--->Oracle Corp)

b) C#.net Programming Lang<------Tech: ASP.net, ASP with Micro Services.

(Micro Soft)

c) PYTHON Programming Language<------Tech: Django, Flask,Bottle,Pyramid

Python----Says--"Less Lines of Code and Gives more Meaning"

Bcoz of Rich set of MODULES are Present in PYTHON

Learning Python=Learning About Modules

2. Development of Gaming Applications.

3. Development of Aritificial Intelligence(AI) Applications

a) Machine Learning (ML)

b) Deep Learning (DL)

4. Development of Image Processing Applications.

5. Development of Audio and Video Based Applications

6. Development of Web Scrapping / Web Harvesting

7. Development of Bussiness Applications (Apps)

8. Development of Scientiifc Applications


1
9. Development of Software Development (Project Development)

10. Development of OS Installers

11. Development of Languages (Spark, Scala)

12. Development of DeskTop GUI Applications

13. Development of Data Analysis and Data Analytics

14. Development of Automation of Testing

15. Development of Complex Math Operations

16. Devevelopment of Console Based Applications (Non-GUI)

17. Development of Animation Applications

18. Development of CAD and CAM Based Applications

19. Development of Computer Vision

20. Python Used in Education System

==========================================================
History of Python
==========================================================
=>The Python Programming Language Concevied (Foundation Stone Laid down) in the Year 1980

=>The Python Programming Language Implemented(Bring into an action) in the Year 1989.

=>The Python Programming Language Offcially Released in the Year 1991 Feb.

=>The Python Programming Language Developed by "Guido Van Rossum" (Father OR Author of Python).

=>The Python Programming Language Developed at CWI (Centrum Wiskunde Informatica) Reasearch Institute
in the Country Nether Landas.

=>The Python Programming Language Maintained and Managed by a Non-Commercial Organization Called PSF
(Python Software Foundation).

=>The official website of PSF is www.python.org.

=========================================================================

2
Version of Python--Used in MNCs
=========================================================================
1. =>Python Programming Language Contains 3 Types of Versions. They are
1. Python 1.x --->Here 1 Is called Major Version and X Represents 0 1 2 3,4,....etc and these called Minor
Version
i. Python 1.x was already Outdated
ii. Python 2.x does not Support Backward Compatability with Python 1.x
2. Python 2.x---->Here 2 Is called Major Version and X Represents 0 1 2 3,4,5,6,7....etc and these called
Minor
3. Version
1. Python 2.x was already Outdated
2. Python 3.x does not Support Backward Compatability with Python 2.x.
4. Python 3.x----Here 3 Is called Major Version and X Represents 0 1 2 3,4,5,6,7,8,9,10,11,12,13 and these
called Minor
5. Version
i. Here Python 3.x is called Current Version
ii. Python 3.8,3.9,3.10 Industry Current Industury Version Used for Developing Real Time
Applications (Secured)
iii. Python 3.11,3.12----Are the Latest versions (BugFix Stage)
iv. Python 3.13-------Pre-Release / Future Version

=========================================================================

DownLoading and Installation Process of Python


=========================================================================
=>Goto www.python.org

=>Choose DownLoads----> Python 3.12.2 (click)

=>Ensure that Python 3.12.2 downloaded

=>Double Click on Python 3.12.2---ensure u Must set the Path--->Choose Install Now

Features of Python

=========================================================================

3
=>Features of a Language are Nothing but Services OR Faclilities Provided by Language Developers in the
Languages, which are used by Language Programmers in development of Real Time Applications.

=>In Python Programming, we have 11 Features. They are

1. Simple

2. Platform Indepedent Langauge

3. Dynamically Typed

4. Interpreted

5. High Level

6. Robust (Strong)

7. Freeware and Open Source

8. Extensible

9. Embedded

10. Both Functional and Object Oriented Programming Lang

11. Supports Third Party APIs Such as numpy, pandas, matplotlib, scipy, scikit,
nltk,keras,scilearn..etc

========================================================================

1.SIMPLE
=========================================================================
=>Python Programming is of one the SIMPLE Programming Language bcoz of THREE Important Technical
Factors.

Factor-1: Python Programming Provides "Rich Set of MODULES"

-------------- So that Python Programmer can Re-Use the Pre-Defined Code which is Present in MODULES
without writing Our Own Source Code

Examples: calendar,random,math,cmath,os,oracledb,mysql.connector...etc

---------------------------
Definition of Module:
4
-------------------------------
A Module is a Collection of Functions, Data Members and Class names

=========================================================================

Factor-2: Python Programming Provides In-Built Facility Called Garbage Collector.

------------- So Garbage Collector Collects Un-Used Memory Space and Improves the perfomance of
Python Based Applications.

Definition of Garbage Collector:

=>A Garbage Collector is one of Python Background Program running Behind of Regular Python Program and
whose Role is that To Collect Un-used memory Space and Improves the Performance of Python Based
Applications.

=>Hence Garbage Collector takes care about automatic Memory Management

Factor-3:

=>The Python Programming Provides User-Friendly Syntaxes and Makes to Programmer to write Error-Free
Programs in Limited span of Time.

====================================================================

2. Platform Indepedent Langauge--Most Imp


====================================================================
=>A platform is Nothing but Type of OS Being Used to Run our Application / Project / Program.

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

Definition of OS(Operating System):


---------------------------------------------------------
=>OS is a Software and It acts as Resource Allocation Manager and Resource De-Allocation Manager

(OR)

=>OS is one of Interface Between Program and Computer Hardware( Memory , Processor , I/O Devices..etc)

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

=>In IT, we have Two Types of Programming Languages. They are


5
1. Platform Dependent Languages

2. Platform Inependent Languages

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

1. Platform Dependent Lang


------------------------------------------------------------------
=>In Platform Dependent Lang, Data Types differes from One OS to Another OS and and These Lang are
PLATFORM DEPENDENT.

Example: C,C++....etc

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

2. Platform Independent Lang


--------------------------------------------------------------------------
=>In Platform Independent Lang, Data Types memory space 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.

====================================================================

3. Dynamically Typed
====================================================================
=>In IT , we have Two Types of Programming Languages. They are

1. Static Typed Programming Language.

2. Dynamically Typed Programming Language.

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

1. Static Typed Programming Language.

6
------------------------------------------------------------------------------------------------------------------

=>In Static Typed Programming Language, It mandatory for the programmer To Specify Variable Declaration
(Data Type+ Identifiers) Otherwise we get Compile Time Errors

Example Task: Compute Sum of Two Numbers in C, C++, Java--------------------

int a=10; // Variable Declaration

int b=20; // Variable Declaration

int c=a+b //Variable Declaration

OR

int a=10,b=20; // Variable Declaration

int c=a+b //Variable Declaration

=>The Problem of Static Typed Programming Languages is that The Programmer May not be Knowing The Data
Type of Value accurately.

=>In Static Typed Programming Languages , It stored Perticular Type Value Only But never allows to store Other
Types of Values.

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

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

2. Dynamically Typed Programming Language.


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

=>In Dynamically Typed Programming Language, Programmers Need not write Variable Declration. Internally
Programming Language Execution Environment will data type of value, which is entered By Programmer.

=>The Advantage of Dynamically Typed Programming Languages, is that

i) Programmer Need not write Data Type

ii) Depends type of Value, Execution Environment will assign the Data type

Examples:

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

7
>>> a=10

>>> b=20

>>> c=a+b

>>> print(a,type(a))---------------10 <class 'int'>

>>> print(b,type(b))---------------20 <class 'int'>

>>> print(c,type(c))---------------30 <class 'int'>

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

>>> a=100

>>> b=1.2

>>> c=a+b

>>> print(a,type(a))--------------100 <class 'int'>

>>> print(b,type(b))--------------1.2 <class 'float'>

>>> print(c,type(c))--------------101.2 <class 'float'>

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

Examples Languages: 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

8
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) 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)

=========================================================================

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:

9
-----------------------------------------------------------------
=>In Low Programming Languages, data is always stored in the form low level values such as Binary data, Octal
Data and Hexa Decimal data. These Number Systems are not directly understandable end-users .

Example : a=0b1010101010----Binary Data

b=0xBEE--------------Hexa Decimal Data

c=0o23-----------------Octal Data

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

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 Language.

Examples:

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

>>> a=0b101010111110000

>>> b=0b10101111000

>>> print(a)-----------------------22000

>>> print(b)----------------------1400

>>> a=0xBEE

>>> print(a)-----------------------3054

>>> bin(22000)-----------------'0b101010111110000'

>>> hex(3054)----------------'0xbee'

=========================================================================

7. Freeware and Open Source


=========================================================================

10
Freeware:

=>If any Programming Language is Freely DownLoadable from OfficiaL Source(www.python.org from PSF)
then that language is called Freeware.

Examples: PYTHON, Java

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

Open Source:
---------------------
=>The Standard Name of Python Software is "CPYTHON".

=>Open Source is Nothing but making the Software to be available to all People.

=>Once the Software is Open Source then Some Software Companies came forward and Customized the Python
Software for their In-House Tools Like Performance Evaluation, Quality of Testing, Releasing Process...etc.

=>The Customized Softwares of Python are called "Python Distributions".

=>Some of the Python Distributions are

1. JPython OR Jython----->Used for Running Java Based Applications.

2. IronPython OR Ipython--->Used for Ruuning C#.net Based Applications

3. Micro Python ---------------->Used for development of Micro Controller Applications.

4. Anaconda Python---------->Used for Developing Big Data OR Hadoop Based Applications

5. StackLess Python--------->used for developing Concurrency Applications..............etc

=========================================================================

6. Robust (Strong)
=========================================================================
=>Python Programming Provides a Programming Feature called "Exception Handling".
=>Due to exception handling facility, Python Based Application becomes Robust(Strong).

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

Definiton of Exception :
----------------------------------------------
11
=>Every Runtime Error of the Program is Called Exception

(Invalid Input----->Runtime Error---->Exception)

=>By default All Exceptions (Runtime Errors) gives Technical Error Message. Which are understandable by
Programmers But not by End-Users and This is Not a Recommended Process in software industry.

=>software industry recommeds convert echnical Error Message into User Friendly Error Message by using
Exception Handling.

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

Definiton of Exception Handling


----------------------------------------------
=>The Process of Converting Technical Error Message into User-Friendly Error Message is Called Exception
Handling

====================================================================

9. Extensible
10. Embedded
===================================================================
Extensible:- Python Programming Provides Its Module Services to Other language Programmers for easy to use
by writing Less Code with More Meaning.

Since Python Programming Provides Its Services to Other languages and hence Python is One of The Extensible
Programming Lang.

Embedded: Python Programming will use Other language Services / Libraries also. In Otherwords, we cal call
Other language code inside of Python Program and Hence Python Programing Lang is Embedded Programming
Lang.

===================================================================
Supports Third Party APIs Such as numpy, pandas, scipy, scipy,scikit, matplotlib, nlp..etc
>Most of theTime Python Programming Supports Third Party APIs Such as numpy, pandas, scipy, scikit, keras,
matplotlib, nlp..etc are providing Easiness to Python programmer in the case of Complex Maths
Calculations(Numpy), Businness Analysis and Analytics (Pandas)..etc

=========================================================================
12
Data Representation in Python
=========================================================================

Index

=>What is Data

=>Purpose of Data

=>Types of Literals OR Values

=>Importance of Identifiers OR Variables

=>Rules for Using Variables OR Identifiers in Python

=========================================================================

What is Data
=========================================================================

=>The processed Information is called Data

(OR)

=>Studying the insights of Information is called Data

=>The purpose of Data is that "To Effective Decisions in Organizations".

=========================================================================

Types of Literals (OR) Values (OR) Data


=========================================================================

In Python Programming, we have Different Types of Literals OR Values OR Data

1. Integer Literals

2. Float Literals

3. String Literals

4. Boolean Literals

5. Collections Literals
13
=========================================================================

Importance of Identifiers OR Variables


=========================================================================
=>In Any Programming Language, Literals Must be Stored in Main Memory by allocating Sufficient Amount of
Memory space with the Help Of Data Types.

=>We know that All types Literals are stored in main memory by having memory space.

=>To Process values which are present in memory space , Programmers must give DISTINCT NAMES to the
created memory spaces. These DISTINCT NAMES makes us to identify the values present in memory space and
hence they are called IDENTIFIERS.

=>The IDENTIFIER Values are Changing/ Varying during Program Execution and hence IDENTIFIERS are also
called VARIABLES.

=>Hence All types of LITERALS are stored in the form VARIABLES and all Variables are called OBJECTS.

Definition of Variable:

A Variable is an Identifier, whose Value can be Changed OR Varying During the Program Execution.

=========================================================================

Rules for Using Variables OR Identifiers in Python


=========================================================================
=>To use Variables in Python Program, we must follow the Rules.

=>The Rules for using Variables in Python Program are

RULE-1: The Variable Name is a Combination of Alphabets, Digits and Special Symbol Under Score ( _ ).

-----------

RULE-2: The First Letter of Variables Name must starts either with Alphabet OR Special Symbol Under Score (
_ ) only.

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

Examples:

123sal=23----------Invalid

14
_sal=45-------------Valid

sal12=34------------valid

__sal=45------valid

_1=12----------valid

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

RULE-3: Within the variable name, special symbols are not allowed except under score(_)

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

EXAMPLES:

emp sal=34---------Invalid

emp_sal=45------valid

emp-sal=45------invalid

emp$sal=45----Invalid

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

RULE-4 :No Keywords to be used as Variable Names ( bcoz Keywords are the Reserved Words and gives special
Meaning to the Language Compilers)

Examples:

while=45-----Invalid

while1=45-----Valid

if=34-----invalid

_if=45-------Valid

True=56----Invalid

true=56----Valid

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

RULE-5: All the Variable Names in Python are Case Sensitive.

15
--------------------

Examples:

>>> age=99

>>> AGE=98

>>> Age=97

>>> aGe=96

>>> print(age,AGE,Age,aGe)--------99 98 97 96

====================================================================

Data types in Python


====================================================================
=>The purpose of Data Types in Python is that "To allocate Sufficient Amount of Memory Space in Main Memory
for storing the Data".

=>In Python Programming, we have 14 Data Types and they are Classified into 6 categories. They are

I. Fundamental Category Data Types

1. int

2. float

3. bool

4. complex

II. Sequence Category Data Types

1. str

2. bytes

3. bytearray

4. range

III. List Category Data Types (Collections Data Types)

16
1. list

2. tuple

IV. Set Category Data Types(Collections Data Types)

1. set

2. frozenset

V. Dict Category Data Type (Collection Data Types)

1. dict

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
=========================================================================
=>'int' is one of the pre-defined class and treated as Fundamental Data Type

=>The purpose of int Data Type is that "To Store Whole Numbers OR Integral Values (Values without Decimal
Places)" such as sno,htno,empno,acno..etc

Examples
17
Python Instructions Output

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

>>> a=10

>>> print(a)----------------------------------- 10

>>> print(type(a))--------------------------- <class 'int'>

>>> print(a,type(a))------------------------ 10 <class 'int'>

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

>>> 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'>

>>> print(a,b,c)-------------------------- 100 200 300

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

=>By using int Data type, we can also store Different type of Number Systems.

=>In Python Programming, 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


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

18
=>This Number System is the Default Number System followed by all Human Beings for Their Day-to-Day
Operations

=>This Number System contains the following

Digits: 0 1 2 3 4 5 6 7 8 9-----Total Digits: 10

Base : 10

=>All Base 10 Values are called Decimal Number System Values.

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

2. Binary Number System


-------------------------------------------------
=>This Number System understandable by OS and Processor.

=>This Number System contains the following

Digits: 0 1 -----Total Digits: 2

Base : 2

=>All Base 2 Values are called Binary Number System Values.

=>In Python Programming, to Store Binary Data, The Binary Data must be preceded with a letter 0b OR 0B.

Syntax: varname=0b Binary Value

(OR)

varname=0B Binary Value

=>In Python Programming, even though we store Binary Data, Internally Python Execution Environment
automatically OR Implicitly Converts into Decimal Number Sytsem.

Examples

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

>>> a=0b1011

>>> print(a,type(a))-------------------------11 <class 'int'>

>>> a=0b1111

19
>>> print(a,type(a))-------------------------15 <class 'int'>

>>> a=0B10000

>>> print(a,type(a))-------------------------16 <class 'int'>

>>> a=0b10102----------SyntaxError: invalid digit '2' in binary literal

NOTE:To Convert Decimal,Octal, Hexa Decimal Number System Value into Binary Number System Value, we
use a Pre-defined Function called bin()

varname=bin(Decimal / Octal / Hexa Decimal)

Examples

>>> bin(11)----------------------'0b1011'

>>> bin(15)----------------------'0b1111'

>>> bin(13)----------------------'0b1101'

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

3. Octal Number System


-------------------------------------------------
=>This Number System understandable by Micro Processor Kits Like in 8086 OR Assembly Language
Programming.

=>This Number System contains the following

Digits: 0 1 2 3 4 5 6 7 -----Total Digits: 8

Base : 8

=>All Base 8 Values are called Octal Number System Values.

=>In Python Programming, to Store Octal Data, The Octal Data must be preceded with a letter 0o OR 0O.

Syntax: varname=0o Octal Value

(OR)

varname=0O Octal Value

20
=>In Python Programming, even though we store Octal Data, Internally Python Execution Environment
automatically OR Implicitly Converts into Decimal Number Sytsem.

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

Examples
-------------------------------------
>>> a=0o17

>>> print(a,type(a))---------------15 <class 'int'>

>>> a=0O123

>>> print(a,type(a))--------------83 <class 'int'>

>>> a=0o168-----------------------SyntaxError: invalid digit '8' in octal literal

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

NOTE:To Convert Decimal,Binary, Hexa Decimal Number System Value into Octal Number System Value, we
use a Pre-defined Function called oct()

varname=oct(Decimal / Binary / Hexa Decimal)

Examples

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

>>> oct(83)-------------'0o123'

>>> oct(15)--------------'0o17'

>>> oct(23)--------------'0o27'

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

4. Hexa Decimal Number System


--------------------------------------------------------------
=>This Number System used in Development of OSes

=>This Number System contains the following

Digits: 0 1 2 3 4 5 6 7 8 9

21
A(10) B(11) C(12) D(13) E(14) F(15)---Total : 16

(OR)

a(10) b(11) c(12) d(13) e(14) f(15)

Base: 16

=>All Base 16 Values are called Hexa Decimal Number System Values.

=>In Python Programming, to Store Hexa Decimal, The Hexa Decimal Data must be preceded with a letter 0x
OR 0X.

Syntax: varname=0x Hexa Decimal Value

(OR)

varname=0X Hexa Decimal Value

=>In Python Programming, even though we store Hexa Decimal Number System Values, Internally Python
Execution Environment automatically OR Implicitly Converts into Decimal Number Sytsem.

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=0xFACER--------------------------SyntaxError: invalid hexadecimal literal

>>> a=0xACE

>>> print(a,type(a))-----------------------2766 <class 'int'>

NOTE:To Convert Decimal,Binary, Octal System Value into Hexa Decimal Number Value, we use a Pre-defined
Function called hex()

22
varname=hex(Decimal / Binary / Octal)

Examples

>>> hex(172)----------------'0xac'

>>> hex(3054)--------------'0xbee'

>>> hex(64206)-------------'0xface'

>>> hex(2766)---------------'0xace'

23
====================================================================

Base Conversions Techniques in Python


====================================================================
=>In Python Programming, we have 3 types of Base Conversions Functions. They are

1. bin()

2. oct()

3. hex()

1. bin()

=>To Convert Decimal,Octal, Hexa Decimal Number System Values into Binary Number System Value, we use
a Pre-defined Function called bin()

varname=bin(Decimal / Octal / Hexa Decimal)

Examples

>>> a=10

>>> bin(a)-----------'0b1010' # Dec to Binary

>>> a=0o17

>>> bin(a)----------'0b1111' # Octal to Binary

>>> a=0xB

>>> bin(a)-------------'0b1011' # Hexa Decial to Binary

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

2. oct( )
-----------------------------------
=>To Convert Decimal,Binary, Hexa Decimal Number System Value into Octal Number System Value, we use a
Pre-defined Function called oct()

varname=oct(Decimal / Binary / Hexa Decimal)

Examples

24
------------------------------------------

>>> a=15

>>> oct(a)-------------------'0o17' # Decimal to Octal

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

>>> a=0b10000

>>> oct(a)----------------'0o20' # Binary to Octal

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

>>> a=0XC

>>> oct(a)--------------'0o14' # Hexa Dec to Oct

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

3. hex()
-----------------------------------
NOTE:To Convert Decimal,Binary, Octal Number System Values into Hexa Decimal Number Value, we use a
Pre-defined Function called hex()

varname=hex(Decimal / Binary / Octal)

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

Examples
-----------------------------
>>> a=15

>>> hex(a)---------'0xf' # Decimal to Hexa Decimal

>>> hex(162)------'0xa2'

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

>>> a=0b0011010

>>> hex(a)---------------'0x1a' # Binary to Hexa Decimal

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

25
>>> a=0o86-------------------SyntaxError: invalid digit '8' in octal literal

>>> a=0o76

>>> hex(a)-------------------'0x3e' # Octal to Hexa Decimal

====================================================================

2. FLOAT
====================================================================
=>'float' is one of the pre-defined class and treated as Fundamental Data Type.

=>The purpose of float data type is that "To Store Real Constant Values OR Floating Point Values (Numbers with
decimal values)".

=>The float data type is also used for Storing the Floating Point Value in the Scienticfic Notation. The Syntax of
Scienticfic Notation is " Mantisa e Exponent " OR " Mantisa e -Exponent "

=>The Eqv Floating Point Value for Scienticfic Notation if given Bellow" Mantisa e Exponent " is Mantisa x 10
to the power of exponent

=>The Advanatge of Scienticfic Notation is to Save Memory Space for Stroing Big Floating point Values.

=>The float data type never allows the programmer to specify the Binary , Octal and Hexa decimal values. But it
allows only Decimal Number System Values.

--------------------------------------------------------------
Examples
--------------------------------------------------------------
>>> a=2.3

>>> print(a,type(a))-------------------2.3 <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'>

26
>>> print(c,type(c))------------------11.2 <class 'float'>

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

>>> a=3e2

>>> print(a,type(a))--------------300.0 <class 'float'>

>>> a=3.2e3

>>> print(a,type(a))-------------3200.0 <class 'float'>

>>> a=10e-2

>>> print(a,type(a))------------0.1 <class 'float'>

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

>>> a=0.00000000000000000000000000000000000000000000005

>>> print(a,type(a))-------------5e-47 <class 'float'>

>>> a=0.000000000000000000000000025

>>> print(a,type(a))-------------2.5e-26 <class 'float'>

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

>>> a=0b1010.0b1111------------------------SyntaxError: invalid decimal literal

>>> a=0o12.0o34------------------------------SyntaxError: invalid decimal literal

>>> a=0xacc.0b111---------------------------SyntaxError: invalid decimal literal

=====================================================================
3.BOOL
=====================================================================
=>'bool' is one of pre-defined class treated as Fundamental Data Type.

=>The purpose of bool data type is that "To Store True and False Values(Logical Values) ".

=>Here True and False are Keywords and considered as Values for bool data type.

=>Internally, The True value is Treated as 1 and False is treated as 0.

=>On Bool Values , We can Perform Arithmetic Operations.


27
------------------------------------------------------------------------------------------------------------------
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.

>>> b=false-----------------------NameError: name 'false' is not defined.

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

>>> a=True

>>> b=False

>>> c=a+b

>>> print(c,type(c))---------1 <class 'int'>

>>> print(True+True)------2

>>> print(True+False-True)---0

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

>>> print(True+2-1)-----2

>>> print(3*True+2)----5

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

>>> print(0b1111+True)------16

>>> print(0xC-True)----------11

>>> print(0o8-True)----------SyntaxError: invalid digit '8' in octal literal

------------------------------------
28
>>> print(True/True)----------1.0

>>> print(True//True)---------1

>>> print(False/True)---------0.0

>>> print(True/False)-----------ZeroDivisionError: division by zero (Most Imp)

====================================================================
4. COMPLEX
====================================================================
=>'complex' is one of the pre-defined data type and treated as Fundametal Data Type.

=>The purpose of complex data type is that "To Store Complex Values and perform operations complex values".

=>The General Notation of Complex Number is Given Bellow.

a+bj OR a-bj

=>Here 'a' is called Real part

=>Here 'b' is called Imaginary part

=>here the Letter 'j' Represents sqrt(-1) OR sqr(j) = -1

=>Internally, Real part and Imaginary Part are Considered as float values.

=>To get Real part and Imaginary parts from Complex Object, we use Two Pre-Defined Attributes. they are'

1. real

2. Imag

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

Syntax2: complexobj.imag----->Gives Imaginary Part of Complex object

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

Examples
------------------------------------------------------------------------------------------------------------------
>>> a=2+3j

>>> print(a,type(a))--------------------(2+3j) <class 'complex'>

29
>>> b=2-5j

>>> print(b,type(b))--------------------(2-5j) <class 'complex'>

>>> c=-2+4j

>>> print(c,type(c))--------------------(-2+4j) <class 'complex'>

>>> d=-2-5j

>>> print(d,type(d))--------------------(-2-5j) <class 'complex'>

>>> a=2+3J

>>> print(a,type(a))-------------------(2+3j) <class 'complex'>

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

>>> a=2.3+3.4j

>>> print(a,type(a))--------------------(2.3+3.4j) <class 'complex'>

>>> b=-2.5-4.5j

>>> print(b,type(b))--------------------(-2.5-4.5j) <class 'complex'>

>>> c=-4.5+4.6j

>>> print(c,type(c))--------------------(-4.5+4.6j) <class 'complex'>

>>> d=3.4-10.2j

>>> print(d,type(d))--------------------(3.4-10.2j) <class 'complex'>

>>> e=2+4.5j

>>> print(e,type(e))-------------------(2+4.5j) <class 'complex'>

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

>>> a=10j

>>> print(a,type(a))----------------10j <class 'complex'>

>>> b=2.3j

>>> print(b,type(b))----------------2.3j <class 'complex'>

30
>>> c=-3j

>>> print(c,type(c))----------------(-0-3j) <class 'complex'>

>>> d=-3.5j

>>> print(d,type(d))---------------- (-0-3.5j) <class 'complex'>

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

>>> a=2+3j

>>> print(a,type(a))-----------------(2+3j) <class 'complex'>

>>> print(a.real)--------------------- 2.0

>>> print(a.imag)--------------------- 3.0

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

>>> a=-2.3+4.5j

>>> print(a,type(a))-------------------(-2.3+4.5j) <class 'complex'>

>>> print(a.real)----------------------- -2.3

>>> print(a.imag)--------------------- 4.5

>>> a=3-4.5j

>>> print(a,type(a))------------------ (3-4.5j) <class 'complex'>

>>> print(a.real)---------------------- 3.0

>>> print(a.imag)--------------------- -4.5

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

>>> a=-2.5j

>>> print(a,type(a))-------------------(-0-2.5j) <class 'complex'>

>>> print(a.real)----------------------- -0.0

>>> print(a.imag)--------------------- -2.5

>>> print(a.imaginary)--------------AttributeError: 'complex' object has no attribute 'imaginary’

31
====================================================================
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
=====================================================================
Index

=>What is str

=>Definition of str

=>Notations of str

=>Types of strs

=>Syntax for storing str data

=>Memory Management of str data

a) +Ve Indexing

b) -Ve Indexing

=>Operations on str data

a) Indexing

b) Slicing Operation

=>Programming Examples

32
====================================================================
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

33
String Data2

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

String data-“ “”

(OR)

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

String Data2

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

String data-n ' ' '

=>With the help 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'>

>>> s1="123456"

>>> print(s1,type(s1))-------------------------123456 <class 'str'>

>>> s2="Python3.11"

>>> print(s2,type(s2))------------------------Python3.11 <class 'str'>

34
>>> s3="123$456_abc"

>>> print(s3,type(s3))------------------------123$456_abc <class 'str'>

>>> s4="@#$%^&8912"

>>> print(s4,type(s4))-------------------------@#$%^&8912 <class 'str'>

>>> s1="Python Programming"

>>> print(s1,type(s1))-----------------------Python Programming <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

... FNO:3-4, Hill Side

... Python Software Foundation

... Nether Lands-56 " " "

>>> print(addr1,type(addr1))

Guido Van Rossum

FNO:3-4, Hill Side

Python Software Foundation

Nether Lands-56 <class 'str'>

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

>>> addr2= ' ' ' Travis Oliphant

... HNO:12-34, Sea Side

35
... Numpy Organization

... Nether lands-58 ' ' '

>>> print(addr2,type(addr2))

Travis Oliphant

HNO:12-34, Sea Side

Numpy Organization

Nether lands-58 <class 'str'>

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

>>> s1="""Python Programming"""

>>> print(s1,type(s1))------------Python Programming <class 'str'>

>>> s1='''Python Programming'''

>>> print(s1,type(s1))-------------------Python Programming <class 'str'>

>>> s2="""A"""

>>> print(s2,type(s2))------------------A <class 'str'>

>>> s2='''A'''

>>> print(s2,type(s2))---------------A <class 'str'>

=====================================================================
Operations on str data
=====================================================================
=>On str Data, we can perform two Types of Operations. They are

1. Indexing Operation

2. Slicing Operations

36
1. Indexing Operation
=>The purpose of Indexing Operation is that "To get One Value at a time from str object".

=>In otherwords, The Process of Obtaining One Value from str object by passing valid Index is called Indexing.

=>Syntax: strobj[ Index ]

=>Here strobj is an object of <class,'str'>

=>Here Index can be either +VE or -VE

=>If we enter Valid Index then we get Corresponding Value from str object.

=>If we enter Invalid Index then we get IndexError as a Result.

Examples

>>> s="PYTHON"

>>> print(s,type(s))------------------PYTHON <class 'str'>

>>> print(s[0])------------------------P

>>> s[0]---------------------------------'P'

>>> s[2]---------------------------------'T'

>>> s[3]---------------------------------'H'

>>> s[5]---------------------------------'N'
37
>>> s[1]---------------------------------'Y'

>>> s[8]---------------------------------IndexError: string index out of range

>>> s[len(s)-1]------------------------'N'-----> Here len(s) gives Number of Chars in 's' object i.e.6

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

>>> s="PYTHON"

>>> print(s,type(s))--------------PYTHON <class 'str'>

>>> s[-2]----------------------------'O'

>>> s[-3]----------------------------'H'

>>> s[-5]----------------------------'Y'

>>> s[-4]----------------------------'T'

>>> s[-6]----------------------------'P'

>>> s[-1]----------------------------'N'

>>> s[-11]---------------------------IndexError: string index out of range

>>> s[-len(s)]----------------------'P'

>>> s[len(s)]-----------------------IndexError: string index out of range

-----------------------------------------------------------------------------------------------------------
2. Slicing Operations
----------------------------------------------------------------
=>The Process of Obtaining Range Chars OR Values(Sub String) from Main String is called Slicing.
=>To Perform Slicing Operation, we have 5 Types of Syntaxes.
Syntax-1 : strobj[BeginIndex : EndIndex ]
****************************************************************
=>This Syntax Gives of Range Chars from BEGININDIEX to ENDIndex -1 provided BeginIndex<EndIndex
Otherwise we
get Space or ' ' as Result
----------------
Examples
----------------
>>> s="PYTHON"
38
>>> print(s)-------------------PYTHON
>>> s[0:4]---------------------'PYTH'
>>> s[2:5]---------------------'THO'
>>> s[5:2]---------------------' '
>>> s[1:5]--------------------'YTHO'
>>> s[2:6]--------------------'THON'
>>> s[4:6]--------------------'ON'
>>> s[3:6]--------------------'HON'
>>> s[1:6]--------------------'YTHON'
>>> s[0:6]--------------------'PYTHON'
--------------------------
>>> s="PYTHON"
>>> print(s)---------------PYTHON
>>> s[-5:-1]---------------'YTHO'
>>> s[-2:-5]---------------' '
>>> s[-5:-2]---------------'YTH'
>>> s[-6:-1]---------------'PYTHO'
>>> s[-3:-1]----------------'HO'
>>> s[-5:-3]----------------'YT'
>>> s[-6:-3]---------------'PYT'
--------------------------------------------
Most Imp Point--Sub Point
*******************************************
>>> s="PYTHON"
>>> print(s)--------------PYTHON
>>> s[2:-2]---------------'TH'
>>> s[1:-1]---------------'YTHO'
>>> s[3:-1]---------------'HO'
>>> s[1:-2]---------------'YTH'
>>> s[0:-1]---------------'PYTHO'
>>> s[2:-1]---------------'THO'
>>> s[3:-2]---------------'H'
---------------------------------

39
>>> s="PYTHON"
>>> print(s)----------------------PYTHON
>>> s[-6:4]-----------------------'PYTH'
>>> s[-5:4]-----------------------'YTH'
>>> s[-4:5]-----------------------'THO'
>>> s[-6:3]-----------------------'PYT'
>>> s[-5:3]-----------------------'YT'
>>> s[-3:1]-----------------------''
>>> s[-4:0]-----------------------''
>>> s[-4:2]-----------------------''
>>> s[-4:3]----------------------'T'
----------------------------------------------
Most PowerFull Point
----------------------------------------------
>>> s="PYTHON"
>>> print(s)------------------PYTHON
>>> s[0:6]--------------------'PYTHON'
>>> s[0:122]-----------------'PYTHON'
>>> s[2:150]-----------------'THON'
>>> s[5:122]-----------------'N'
>>> s[122:345]--------------' '
----------------------
>>> s="PYTHON"
>>> print(s)------------PYTHON
>>> s[-122:-5]---------'P'
>>> s[-10:-1]-----------'PYTHO'
>>> s[-9:-3]------------'PYT'
>>> s[-10:0]-----------' '
>>> s[-10:0]-----------' '
------------------------------------------
>>> s="PYTHON Prog"
>>> print(s)---------------------PYTHON Prog
>>> s[-122:456]---------------'PYTHON Prog'

40
>>> s[-333:333]---------------'PYTHON Prog'
>>> "JAVA"[-4:3]-------------'JAV'
>>> "JAVA"[3:123]-----------'A'
>>> "JAVA"[3:-1]-------------' '
>>> "JAVA"[0:-1]-------------'JAV'
------------------------------------------------------
>>> "HYDERABAD"[-122:0]----------' '
>>> "HYDERABAD"[-122:1]----------'H'
>>> "HYDERABAD"[-122:122]-------'HYDERABAD'
****************************************************************
Syntax-2: StrObj [ BEGINIndex : ]
*****************************************************************
=>In This Syntax, We Specify BEGIN Index and we Don'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 the Range of Chars from BEGIN Index to Last Character.
OR
=>This Syntax gives Range of Chars from BEGIN Index to Last Character.
------------------------------------
Examples
------------------------------------
>>> s="PYTHON"
>>> print(s)-------------------------PYTHON
>>> s[0:]-----------------------------'PYTHON'
>>> s[2:]-----------------------------'THON'
>>> s[3:]-----------------------------'HON'
>>> s[1:]-----------------------------'YTHON'
>>> s[4:]-----------------------------'ON'
---------------------
>>> s[4:]
'ON'
>>> s="PYTHON"
>>> print(s)--------------PYTHON

41
>>> s[-122:]-------------'PYTHON'
>>> s[-2:]-----------------'ON'
>>> s[-6:]-----------------'PYTHON'
>>> s[-5:]-----------------'YTHON'
>>>s[0:]------------------PYTHON
>>> s="PYTHON"
>>> print(s)---------------PYTHON
>>> s[True:]--------------'YTHON'
>>> s[False:]-------------'PYTHON'
>>> s[False:True]-------'P'
>>> s[-0xf:]----------------'PYTHON'
>>> s[-True:]-----------------'N'
****************************************************************
Syntax-3: StrObj [ : EndIndex]
****************************************************************
=>In This Syntax, We Specify END Index and we Don't Specify BEGIN Index.
=>If we don't specify BEGIN Index Then PVM Takes BEGIN Index as Either 0 (+Ve) or -len(strobj]
OR
=>If we don't specify BEGIN Index Then PVM Takes the Range of Chars from First Character ENDIndex-1 .
OR
=>This Syntax gives Range of Chars from Range of Chars from First Character ENDIndex-1.
------------------------------------
Examples
------------------------------------
>>> s="PYTHON"
>>> print(s)-------------------PYTHON
>>> s[:5]-----------------------'PYTHO'
>>> s[:3]-----------------------'PYT'
>>> s[:4]-----------------------'PYTH'
>>> s[:6]-----------------------'PYTHON'
>>> s[:-3]----------------------'PYT'
>>> s[:-1]----------------------'PYTHO'
>>> s[:-2]----------------------'PYTH'
42
>>> s[:0]-----------------------' '
*****************************************************************
Syntax-4: StrObj [ : ]
*****************************************************************
=>In this Syntax, we did't specify Begin Index and End Index.
=>If we don't Specify Begin Index then we get First Character Onwards
=>If we don't Specify End Index then we get upto Last Character Onwards
=>Hence This Syntax Gives Range Chars from First Character to Last Character (Complete Str Data)
--------------------------------------------------------
Examples
--------------------------------------------------------
>>> s="PYTHON"
>>> print(s,type(s))-----------------PYTHON <class 'str'>
>>> s[:]---------------------------------'PYTHON'
>>> s[-122:222]---------------------'PYTHON'
>>> s[0:]------------------------------'PYTHON'
>>> s[-6:]-----------------------------'PYTHON'
>>> s[:122]---------------------------'PYTHON'
------------------------------
>>> s="JAVA"
>>> print(s)-------------------JAVA
>>> s[:]-------------------------'JAVA'
>>> s[0:]------------------------'JAVA'
>>> s[-4:]-----------------------'JAVA'
>>> s[:4]------------------------'JAVA'
>>> s[-122:333]---------------'JAVA'
>>> s[-122:]--------------------'JAVA'
>>> s[:333]---------------------'JAVA'
NOTE: ALL THE ABOVE SYNTAXES ARE GIVING RANGE OF VALUES (SUB STRINGS) IN
FORWARD DIRECTION WITH
DEFAULT STEP +1
*************************************************************************
Syntax-5: strobj[ Begin :End : Step ]
**************************************************************************
43
RULE-1:Here BEGIN , END and STEP values can be Either +VE or -VE
RULE-2: If the Value of STEP of +VE then PVM gets the Range of Values from BEGIN to END-1 Index in
FORWARD DIRECTION Provided BEGIN<END otherwise we get Space as Result OR ' ' as Result
RULE-3: If the Value of STEP of -VE then PVM get the Range of Values from BEGIN to END+1 Index in
BACKWARD DIRECTION Provided BEGIN>END otherwise we get Space as Result OR ' ' as Result
RULE-4: If FORWARD DIRECTION, if we specify the END INDEX as 0 then we get Space OR ' ' as Result
RULE-5: If BACKWARD DIRECTION, if we specify the END INDEX as -1 then we get Space OR ' ' as
Result
******************************************************************************
Examples--RULE-2
------------------------------
>>> s="PYTHON"
>>> print(s)-----------------PYTHON
>>> s[::1]--------------------'PYTHON'
>>> s[::]----------------------'PYTHON'
>>> s[::2]--------------------'PTO'
>>> s[::3]--------------------'PH'
>>> s[::4]--------------------'PO'
-------------------------------
>>> s="PYTHON"
>>> print(s)------------------PYTHON
>>> s[0:6:2]------------------'PTO'
>>> s[2:6:3]------------------'TN'
>>> s[4:2:2]-----------------' '
>>> s[1:5:3]-----------------'YO'
>>> s[1:10:2]----------------'YHN'
-------------------------------------
>>> s="PYTHON"
>>> print(s)----------------PYTHON
>>> s[-6:-1:2]--------------'PTO'
>>> s[-6:-2:4]--------------'P'
>>> s[-5:-1:3]--------------'YO'
>>> s[-6:-1:3]-------------'PH'

44
-----------------------------------------
>>> s="PYTHON"
>>> print(s)-----------------PYTHON
>>> s[0::2]------------------'PTO'
>>> s[2::3]------------------'TN'
>>> s[3::3]------------------'H'
>>> s[-6::2]-----------------'PTO'
>>> s[-5::1]-----------------'YTHON'
>>> s[-5::]-------------------'YTHON'
----------------------------------------------
>>> s="PYTHON"
>>> print(s)-------------------------PYTHON
>>> s[:4:2]---------------------------'PT'
>>> s[:6:3]---------------------------'PH'
>>> s[:3:]-----------------------------'PYT'
>>> s[:6:4]---------------------------'PO'
>>> s[:-1:1]--------------------------'PYTHO'
>>> s[:-5:2]---------------------------'P'
>>> s[:-122:1]-----------------------''
>>> s[122::1]------------------------''
---------------------------------------------------------------------------------------
Examples:--Rule-3
----------------------------------------------------------------------------------------
>>> s="PYTHON"
>>> print(s)------------------PYTHON
>>> s[5:1:-1]----------------'NOHT'
>>> s[4:0:-1]----------------'OHTY'
>>> s[5:0:-2]----------------'NHY'
>>> s[0:5:-2]-----------------' '
>>> s[5:1:-3]----------------'NT'
>>> s[::-2]-------------------'NHY'
----------------------------
>>> s="PYTHON"

45
>>> print(s)------------------PYTHON
>>> s[-6:-1:-1]---------------' '
>>> s[-1:-6:-1]--------------'NOHTY'
>>> s[-1:-6:-3]--------------'NT'
>>> s[-2:-7:-2]--------------'OTP'
>>> s[-3:-6:-3]--------------'H'
----------------------------------------
>>> s="PYTHON"
>>> print(s)---------------PYTHON
>>> s[4::-1]---------------'OHTYP'
>>> s[5::-2]---------------'NHY'
>>> s[3::-1]---------------'HTYP'
>>> s[4::-4]---------------'OP'
------------------------------------------
>>> s="PYTHON"
>>> print(s)-----------------PYTHON
>>> s[-6::-2]----------------'P'
>>> s[-7::-2]----------------' '
>>> s[-6::-3]----------------'P'
>>> s[-4::-2]----------------'TP'
>>> s[-1::-5]----------------'NP'
>>> s[-4::-3]---------------'T'
-------------------------------------------
>>> s="PYTHON"
>>> s[-6:5:-2]-------------''
>>> s[5:-6:1]-------------''
>>> s[126:-126:-1]--------'NOHTYP'
>>> s[4:-2:-1]-------------''
>>> s[4:-3:-1]-------------'O'
>>> s[-1:-5:-2]-------------'NH'
>>> s[6:-7:-2]--------------'NHY'

46
==================================
Examples: RULE-4:
---------------------------
>>> s="PYTHON"
>>> print(s)------------PYTHON
>>> s[:0:1]--------------''
>>> s[:0:2]--------------''
>>> s[2:0:2]------------''
==================================
Examples: RULE-5:
---------------------------
>>> s="PYTHON"
>>> print(s)----------------PYTHON
>>> s[:-1:-1]----------------''
>>> s[-6:-1:-2]--------------''
>>> s[:-1:-3]----------------''
=====================================================================
PALINDROME WORDS
---------------------------------
>>> s="LIRIL"
>>> s==s[::-1]------------True
>>> s="MADAM"
>>> s==s[::-1]-----------True
>>> s="RACECAR"
>>> s==s[::-1]--------True
>>> s="MOM"
>>> s==s[::-1]---------True
>>> s="DAD"
>>> s==s[::-1]-----------True
>>> s="PYTHON" # NOT a Palindrome Word
>>> s==s[::-1]--------------False
>>> s="WOW"
>>> s==s[::-1]--------------True
47
=====================================================================
Type Casting Techniques in Python
=====================================================================
=>The Process of Converting One Possible Type of Value into another Possible type of Value is Called Type
Casting.
=>In Python Programming, we have 5 Fundamental Type Casting Techniques. They are

1. int()
2. float()
3. bool()
4. complex()
5. str()
=====================================================================
1. int()
=====================================================================
=>int() is used for Converting One Type of Possible Value into int type Value.
=>Syntax: varname=int(float / bool / complex / str)
*****************************************************************************
Example-1: float type into 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.45
>>> print(a,type(a))------------------0.45 <class 'float'>
>>> b=int(a)
>>> print(b,type(b))------------------0 <class 'int'>
******************************************************************************
Example-2: bool type to int type--POSSIBLE
******************************************************************************
>>> a=True
>>> print(a,type(a))---------------True <class 'bool'>
48
>>> 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 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 type
******************************************************************************
Case-1: str int into int type--POSSIBLE
--------------------------------------------------------
>>> a="123"
>>> print(a,type(a))------------------123 <class 'str'>
>>> b=int(a)
>>> print(b,type(b))------------------123 <class 'int'>
--------------------------------------------------------
Case-2 : str float into int type--NOT POSSIBLE
--------------------------------------------------------
>>> a="123.45"
>>> print(a,type(a))---------123.45 <class 'str'>
>>> b=int(a)-------------------ValueError: invalid literal for int() with base 10: '123.45'
--------------------------------------------------------
Case-3: str bool into int type---NOT POSSIBLE
--------------------------------------------------------
>>> a="True"
>>> print(a,type(a))------------True <class 'str'>

49
>>> b=int(a)----------------------ValueError: invalid literal for int() with base 10: 'True'
>>> a="False"
>>> print(a,type(a))-------------False <class 'str'>
>>> b=int(a)-----------------------ValueError: invalid literal for int() with base 10: 'False'
--------------------------------------------------------
Case-4: str complex into int type--NOT POSSIBLE
--------------------------------------------------------
>>> a="2+3j"
>>> print(a,type(a))-----------2+3j <class 'str'>
>>> b=int(a)---------------------ValueError: invalid literal for int() with base 10: '2+3j'
--------------------------------------------------------
Case-5: pure str into int type--NOT POSSIBLE
--------------------------------------------------------
>>> a="PYTHON"
>>> print(a,type(a))-------------PYTHON <class 'str'>
>>> b=int(a)----------------------ValueError: invalid literal for int() with base 10: 'PYTHON
=====================================================================

2. float()
====================================================================
=>float() is used for Converting One Type of Possible Value into float type Value.
=>Syntax: varname=float(int / bool/ complex / str)
******************************************************************************
Example-1: int type into float type--POSSIBLE
******************************************************************************
>>> a=12
>>> print(a,type(a))--------------12 <class 'int'>
>>> b=float(a)
>>> print(b,type(b))--------------12.0 <class 'float'>
>>> a=0
>>> print(a,type(a))---------------0 <class 'int'>
>>> b=float(a)
>>> print(b,type(b))---------------0.0 <class 'float'>
******************************************************************************
50
Example-2: bool type to 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 to float type--NOT POSSIBLE
******************************************************************************
>>> a=2+2j
>>> print(a,type(a))-----------(2+2j) <class 'complex'>
>>> b=float(a)-------------------TypeError: float() argument must be a string or a real number, not 'complex'
******************************************************************************
Example-4: str type to float type
******************************************************************************
Case-1: str int into float type--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 into float type---POSSIBLE
--------------------------------------------------------
>>> a="12.34"
>>> print(a,type(a))------------12.34 <class 'str'>
>>> b=float(a)
>>> print(b,type(b))------------12.34 <class 'float'>

51
--------------------------------------------------------
Case-3: str bool into float type--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 into float type--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 into float type--NOT POSSIBLE
--------------------------------------------------------
>>> a="PYTHON"
>>> print(a,type(a))-------------PYTHON <class 'str'>
>>> b=float(a)--------------------ValueError: could not convert string to float: 'PYTHON'

===============================================================================

3. bool()
===============================================================================
=>bool() is used for Converting One Type of Possible Value into booltype Value.
=>Syntax: varname=bool(int / float / complex / str)
=>ALL NON-ZERO VALUES ARE TREATED AS TRUE
=>ALL ZERO VALUES ARE TREATED AS FALSE
*****************************************************************************
Example-1: int type into bool type--POSSIBLE
******************************************************************************
>>> a=100
>>> print(a,type(a))--------------100 <class 'int'>
>>> b=bool(a)
>>> print(b,type(b))--------------True <class 'bool'>

52
>>> a=-123
>>> print(a,type(a))---------------123 <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'>
******************************************************************************
Example-2: float type to bool type--POSSIBLE
******************************************************************************
>>> a=1.2
>>> print(a,type(a))------------1.2 <class 'float'>
>>> b=bool(a)
>>> print(b,type(b))-------------True <class 'bool'>
>>> a=0.0
>>> print(a,type(a))------------0.0 <class 'float'>
>>> b=bool(a)
>>> print(b,type(b))------------False <class 'bool'>
>>> a=0.000000000000000000000000000000000000000000000000001
>>> print(a,type(a))-----------1e-51 <class 'float'>
>>> b=bool(a)
>>> print(b,type(b))-----------True <class 'bool'>
>>> a=0.000000000000000000000000000000000000000000000000000000
>>> print(a,type(a))-----------0.0 <class 'float'>
>>> b=bool(a)
>>> print(b,type(b))-----------False <class 'bool'>
******************************************************************************
Example-3: complex type to bool type--POSSIBLE
**************************************************************************
>>> a=2+3j
>>> print(a,type(a))-----------------------(2+3j) <class 'complex'>
>>> b=bool(a)
53
>>> 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'>
*************************************************************************************
Example-4: str type to bool type
*************************************************************************************
Case-1: str int into bool type--POSSIBLE
--------------------------------------------------------
>>> a="10"
>>> print(a,type(a))-------------10 <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 into bool type--POSSIBLE
--------------------------------------------------------
>>> a="0.0"
>>> print(a,type(a))----------------0.0 <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))---------------True <class 'bool'>
>>> len(a)----------------------------3
--------------
>>> a="1.2"
>>> print(a,type(a))-------------1.2 <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))-------------True <class 'bool'>

54
--------------------------------------------------------
Case-3: str bool into bool type-----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 into bool type--POSSIBLE
--------------------------------------------------------
>>> a="2+3j"
>>> print(a,type(a))-----------2+3j <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))----------True <class 'bool'>
>>> a="0j"
>>> print(a,type(a))-----------0j <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))-----------True <class 'bool'>
--------------------------------------------------------
Case-5: pure str into bool type--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))-------------- " " <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))--------------True <class 'bool'>
>>> len(a)---------------------------4
55
>>> a=""
>>> len(a)---------------------------0
>>> print(a,type(a))--------------"" <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))------------------False <class 'bool’
====================================================================
4. complex()
====================================================================
=>complex() is used for Converting One Type of Possible Value into complex type Value.
=>Syntax: varname=complex(int / float / bool / str)
****************************************************************************
Example-1: int type into complex type--POSSIBLE
******************************************************************************
>>> a=10
>>> print(a,type(a))------------10 <class 'int'>
>>> b=complex(a)
>>> print(b,type(b))------------(10+0j) <class 'complex'>
******************************************************************************
Example-2: float type to complex type--POSSIBLE
******************************************************************************
>>> a=1.2
>>> print(a,type(a))--------1.2 <class 'float'>
>>> b=complex(a)
>>> print(b,type(b))-------(1.2+0j) <class 'complex'>
******************************************************************************
Example-3: bool type to 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'>
56
>>> b=complex(a)
>>> print(b,type(b))----------------0j <class 'complex'>
******************************************************************************
Example-4: str type to int type
******************************************************************************
Case-1: str int into complex type---POSSIBLE
--------------------------------------------------------
>>> a="10"
>>> print(a,type(a))------------10 <class 'str'>
>>> b=complex(a)
>>> print(b,type(b))------------(10+0j) <class 'complex'>
--------------------------------------------------------
Case-2 : str float into complex type----POSSIBLE
--------------------------------------------------------
>>> a="12.3"
>>> print(a,type(a))---------------12.3 <class 'str'>
>>> b=complex(a)
>>> print(b,type(b))---------------(12.3+0j) <class 'complex'>
--------------------------------------------------------
Case-3: str bool into complex type----NOT POSSIBLE
--------------------------------------------------------
>>> a="True"
>>> print(a,type(a))-------------True <class 'str'>
>>> b=complex(a)---------------ValueError: complex() arg is a malformed string
--------------------------------------------------------
Case-4: str complex into complex type--POSSIBLE
--------------------------------------------------------
>>> a="2+3j"
>>> print(a,type(a))-----------------2+3j <class 'str'>
>>> b=complex(a)
>>> print(b,type(b))----------------(2+3j) <class 'complex'>
>>> a="2.3+4.6j"

57
>>> print(a,type(a))-----------------2.3+4.6j <class 'str'>
>>> b=complex(a)
>>> print(b,type(b))-----------------(2.3+4.6j) <class 'complex'>
>>> a="2+4i"
>>> print(a,type(a))-----------------2+4i <class 'str'>
>>> b=complex(a)-------------------ValueError: complex() arg is a malformed string
--------------------------------------------------------
Case-5: pure str into complex type---NOT POSSIBLE
--------------------------------------------------------
>>> a="PYTHON"
>>> print(a,type(a))-------------------PYTHON <class 'str'>
>>> b=complex(a)---------------------ValueError: complex() arg is a malformed string
==============================================================
5. str()
==============================================================
=>str() is used for Converting All Types of Values into str type value.
=>Syntax: varname=str(int/ float / bool / complex )
---------------------------------------------------------------------------------------------------------------------
Examples
---------------------------------------------------------------------------------------------------------------------
>>> a=100
>>> print(a,type(a))-----------100 <class 'int'>
>>> b=str(a)
>>> print(b,type(b))-----------100 <class 'str'>
>>> b------------------------------'100'
---------------------
>>> a=12.34
>>> print(a,type(a))------------12.34 <class 'float'>
>>> b=str(a)
>>> print(b,type(b))------------12.34 <class 'str'>
>>> b-------------------------------'12.34'
-----------------------
>>> a=True
58
>>> print(a,type(a))----------True <class 'bool'>
>>> b=str(a)
>>> print(b,type(b))----------True <class 'str'>
>>> b-----------------------------'True'
--------------------------------
>>> a=2+3j
>>> print(a,type(a))-------------(2+3j) <class 'complex'>
>>> b=str(a)
>>> print(b,type(b))-------------(2+3j) <class 'str'>
>>> b--------------------------------'(2+3j)'
=====================================================================
2.Bytes
====================================================================
=>'bytes' is one of the Pre-Defined Class and Treated Sequence Data Type.
=>The Purpose of bytes data type is that "To Implement End-to-End Encryption" in network based Applications.
=>To Implement End-to-End encryption in network based Applications,bytes data type organizes the Numerical
Integer values in range of 0 to 256 i.e It stores 0 to 255 values Only.
=>bytes data type does not contain any symbolic notation for storing bytes data bcoz Programmer will not store
bytes data directly in the Program. But We Can convert any other type of values into bytes type by using bytes().
Syntax: varname=bytes(object)
=>An object of bytes maintains Insertion Order (Insertion order is Nothing but Whatever the order we organize
in the same order the data will be displayed)
=>On the Object of bytes, we can Perform Both Indexing and Slicing Operations.
=>An object of bytes belongs to IMMUTABLE bcoz bytes object does not support Item Assigment.
---------------------------------------------------------------------------------------------------------------------
Examples
---------------------------------------------------------------------------------------------------------------------
>>> lst=[100,200,10,0,256,45,67]
>>> print(lst,type(lst))----------------[100, 200, 10, 0, 256, 45, 67] <class 'list'>
>>> b=bytes(lst)-----------------------ValueError: bytes must be in range(0, 256)
>>> lst=[100,-200,10,0,255,45,67]
>>> print(lst,type(lst))---------------[100, -200, 10, 0, 255, 45, 67] <class 'list'>
>>> b=bytes(lst)-----------------------ValueError: bytes must be in range(0, 256)
59
----------------------------------
>>> lst=[100,200,10,0,255,45,67]
>>> print(lst,type(lst))---------------[100, 200, 10, 0, 255, 45, 67] <class 'list'>
>>> b=bytes(lst)
>>> print(b,type(b))------------b'd\xc8\n\x00\xff-C' <class 'bytes'>
---------------------------------------------
>>> lst=[100,200,10,0,255,45,67]
>>> print(lst,type(lst))
[100, 200, 10, 0, 255, 45, 67] <class 'list'>
>>> b=bytes(lst)
>>> print(b,type(b))--------------b'd\xc8\n\x00\xff-C' <class 'bytes'>
>>> for val in b:
... print(val)
100
200
10
0
255
45
67
-----------------------------------------------------
>>> b[0]-------------------100
>>> b[1]-------------------200
>>> b[-1]------------------67
>>> b[1:5]----------------b'\xc8\n\x00\xff'
>>> for val in b[1:5]:
... print(val)
...
200
10
0
255
>>> for val in b[::-1]:

60
... print(val)
...
67
45
255
0
10
200
100
-------------------------------------
>>> b[0]=200------------------TypeError: 'bytes' object does not support item assignment

==========================================================
Mutable and Immutable Objects
==========================================================
--------------
Mutable
--------------
=>A Mutable object is one, whose Content can be changed at the Same Address.
Examples:
---------------
list, set,dict

--------------------------
Immutable Object
--------------------------
=>An Object is said to Immutable iff It satisfies the following the Properties
1) Immutable Objects Value can't be Changed at Same Address
( Immutable Objects Value can be changed and Modified value can be
placed at Different Address)
2) Immutable Objects never allows us to Perform Item Assigment
Examples
---------------
int,float,bool,complex,str,bytes,range,tuple,set,frozenset,NoneType

=====================================================================
3. bytearray
=====================================================================
61
=>'bytearray' is one of the Pre-Defined Class and Treated Sequence Data Type.
=>The Purpose of bytearray data type is that "To Implement End-to-End Encryption" in network based
Applications.
=>To Implement End-to-End encryption in network based Applications,bytearray data type organizes the
Numerical Integer values in range of 0 to 256 i.e It stores 0 to 255 values Only.
=>bytearray data type does not contain any symbolic notation for storing bytearray data bcoz Programmer will
not store bytearray data directly in the Program. But We Can convert any other type of values into bytearray type
by using bytearray().
Syntax: varname=bytearray(object)
=>An object of bytearray maintains Insertion Order (Insertion order is Nothing but Whatever the order we
organize in the same order the data will be displayed)
=>On the Object of bytearray, we can Perform Both Indexing and Slicing Operations.
=>An object of bytearray belongs toMUTABLE bcoz bytearray object supports Item Assigment.
******************************************************************************
NOTE: The functionality of bytearray is exactly similar to bytes But the object of bytes belongs to
IMMUTABLE bcoz bytes object does not support Item Assigment where an object bytearray belongs to
MUTABLE bcoz an object of bytearray allows us to perform Item Assignment.
******************************************************************************
Examples
=====================================================================
>>> lst=[100,200,256,0,55,166]
>>> print(lst)----------------[100, 200, 256, 0, 55, 166]
>>> ba=bytearray(lst)----ValueError: byte must be in range(0, 256)
>>> lst=[100,-200,255,0,55,166]
>>> print(lst)-----------------[100, -200, 255, 0, 55, 166]
>>> ba=bytearray(lst)-------ValueError: byte must be in range(0, 256)
----------------------------------
>>> lst=[100,200,255,0,55,166]
>>> print(lst,type(lst))------------[100, 200, 255, 0, 55, 166] <class 'list'>
>>> ba=bytearray(lst)
>>> print(ba,type(ba))------------bytearray(b'd\xc8\xff\x007\xa6') <class 'bytearray'>
>>> for val in ba:
... print(val)
62
...
100
200
255
0
55
166
-----------------------------------------------
>>> lst=[100,200,255,0,55,166]
>>> ba=bytearray(lst)
>>> print(ba,type(ba))---------bytearray(b'd\xc8\xff\x007\xa6') <class 'bytearray'>
>>> ba[0]------------100
>>> ba[-1]-----------166
>>> for val in ba[::-1]:
... print(val)
...
166
55
0
255
200
100
-------------------------------------------------
>>> lst=[100,200,255,0,55,166]
>>> ba=bytearray(lst)
>>> print(ba,type(ba),id(ba))----bytearray(b'd\xc8\xff\x007\xa6') <class 'bytearray'> 2233418515568
>>> ba[0]-------100
>>> ba[0]=150 # Item Assigment
>>> print(ba,type(ba),id(ba))----bytearray(b'\x96\xc8\xff\x007\xa6') <class 'bytearray'> 2233418515568
>>> for val in ba:
... print(val)
...
150

63
200
255
0
55
166
=====================================================================
4. range
====================================================================
=>'range' is one of the pre-defined class and treated as Sequence Category Data type.
=>The purpose of range data type is that "To Maintain Sequence of Integer values by maintaining Equal Interval
of Value (Step)".
=>On the object of range, we can perform both Indexing and slicing Operations.
=>An object of range belongs to IMMUTABLE bcoz range object does not support Item Assigment.
=>An object of range Maintains Insertion Order.
=>To create an object of range for storing Range OR Sequence of Values, we use 3 Pre-Defined Functions. They
are
---------------------------------------------------------------------------------------------------------------------
Syntax1: range(value)
---------------------------------------------------------------------------------------------------------------------
=>This sytax generates range of values from 0 to value-1
Examples
----------------
>>> r=range(6)
>>> print(r,type(r))----------range(0, 6) <class 'range'>
>>> for val in r:
... print(val)
...
0
1
2
3
4
5
64
>>> for val in range(6):
... print(val)
...
0
1
2
3
4
5
---------------------------------------------------------------------------------------------------------------------
Syntax2: range(Start,Stop)
---------------------------------------------------------------------------------------------------------------------
=>This Syntax generates range of values from Start to Stop-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(100,106):
... print(val)
...
100
101
102

65
103
104
105
NOTE: The above TWO Syntaxes,By deafult uses +1 Step
---------------------------------------------------------------------------------------------------------------------
Syntax3: range(Start,Stop,Step)
---------------------------------------------------------------------------------------------------------------------
=>This Syntax generates range of values from Start to stop by maintaining Equal Interval of Value (Step).
----------------
Examples
----------------
>>> r=range(10,21,2)
>>> print(r,type(r))--------range(10, 21, 2) <class 'range'>
>>> for val in r:
... print(val)
...
10
12
14
16
18
20
>>> for val in range(100,107,2):
... print(val)
...
100
102
104
106
=====================================================================
Example
=====================================================================

66
Q1) 0 1 2 3 4 5 6 7 8 9 ------------range(10) OR range(0,10) OR range(0,10,1)
>>> for v in range(10):
... print(v)
...
0
1
2
3
4
5
6
7
8
9
>>> for v in range(0,10):
... print(v)
...
0
1
2
3
4
5
6
7
8
9
>>> for v in range(0,10,1):
... print(v)
...
0
1
2

67
3
4
5
6
7
8
9
---------------------------------------------------------------------------------------------------------------------------------------
Q2) 10 11 12 13 14 15 16 17 18 19 20-----range(10,21) OR range(10,21,1)
>>> for v in range(10,21):
... print(v)
...
10
11
12
13
14
15
16
17
18
19
20
>>> for v in range(10,21,1):
... print(v)
...
10
11
12
13
14
15
16

68
17
18
19
20
---------------------------------------------------------------------------------------------------------------------
Q3) 10 15 20 25 30 35 40 45 50----range(10,51,5)
>>> for val in range(10,51,5):
... print(val)
...
10
15
20
25
30
35
40
45
50

---------------------------------------------------------------------------------------------------------------------
Q4) 100 110 120 130 140 150-----range(100,151,10)
>>> for val in range(100,151,10):
... print(val)
...
100
110
120
130
140
150
---------------------------------------------------------------------------------------------------------------------

69
Q5) -9 -8 -7 -6 -5 -4 -3 -2 -1 -- range(-9,0,1) OR range(-9,0)
>>> for val in range(-9,0,1):
... print(val)
...
-9
-8
-7
-6
-5
-4
-3
-2
-1
>>> for val in range(-9,0):
... print(val)
...
-9
-8
-7
-6
-5
-4
-3
-2
-1
---------------------------------------------------------------------------------------------------------------------
Q6) -50 -40 -30 -20 -10 ----range(-50,-9,10)
>>> for v in range(-50,-9,10):
... print(v)
...
-50
-40
-30
70
-20
-10
>>> for v in range(-50,0,10):
... print(v)
...
-50
-40
-30
-20
-10
---------------------------------------------------------------------------------------------------------------------
Q7) -1 -2 -3 -4 -5 -6 -7 -8 -9-------------range(-1,-10,-1)
>>> for v in range(-1,-10,-1):
... print(v)
...
-1
-2
-3
-4
-5
-6
-7
-8
-9
---------------------------------------------------------------------------------------------------------------------
Q8) -100 -120 -140 -160 -180 -200-----range(-100,-201,-20)
>>> for v in range(-100,-201,-20):
... print(v)
...
-100
-120
-140
-160
71
-180
-200
>>> for v in range(-100,-220,-20):
... print(v)
...
-100
-120
-140
-160
-180
-200
---------------------------------------------------------------------------------------------------------------------
Q9) -5 -4 -3 -2 -1 0 1 2 3 4 5------range(-5,6) OR range(-5,6,1)
---------------------------------------------------------------------------------------------------------------------
>>> for val in range(-5,6):
... print(val)
...
-5
-4
-3
-2
-1
0
1
2
3
4
5
>>> for val in range(-5,6,1):
... print(val)
...
-5
-4

72
-3
-2
-1
0
1
2
3
4
5
>>>
---------------------------------------------------------------------------------------------------------------------
Q10) 1000 1010 1020 1030 1040 1050----range(1000,1051,10)
---------------------------------------------------------------------------------------------------------------------
>>> for v in range(1000,1051,10):
... print(v)
...
1000
1010
1020
1030
1040
1050
--------------------------------------------------------------------------------------------------------------------
>>> r=range(1000,1041,10)
>>> r[0]-------------1000
>>> r[-1]---------------1040
>>> r[0:3]-----------range(1000, 1030, 10)
>>> for v in r[0:3]:
... print(v)
... 1000
1010
1020
>>> r[0]=120------------------TypeError: 'range' object does not support item assignment

73
==========================================================
List Category Data Types (Collections Data Types)
==========================================================
=>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 Duplicates ".
=>We have 2 Data Types in List Category. They are
1. list (Mutable)
2. tuple (Immutable)
=====================================================================
FDT-----Single Value
SDT-----Sequence of Values
My Requirement today
1. I want to store 100 10 120 1000 -456 100 2000 400 10 12.34
Numerical values----Duplicates and UniquValues
2 I want to store 10 "Rossum",45.67,"Python",56.78,True
Numerical vals+Different types of Values+Both type
Store Employee Values in single object
eno,ename,sal,dsg,city
==============================================================
1. list
==============================================================
Index
=>Purpose of list
=>Notation for storing list Data
=>Create an object of list
=>Types of Lists
=>Memory Management of List
=>Operations on List
=>Pre-Defined Functions in list
=>Inner List OR Nested List
=>Programming Examples

74
=====================================================================
Properties of List
---------------------------------------------------------------------------------------------------------------------
=>'list' is one of the pre-defined class and treated as List Category 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 Duplicates".
=>To Store the List data, we use Square Brackets. In Otherwords, the elements of list must be enclosed within
Square
Brackets [ ] and Values Separated by Comma.
Syntax: varname=[Val1,Val2,......,Val-n]
=>Here varname is an object of list
=>An object of list Maintains Insertion Order.
=>On the object of list, we can perform Both Indexing and Slicing Operations.
=>An object of list belongs to MUTABLE bcoz list object allows us to perfom Modification / Updations /
Assignments
by using Indexing and Slicing.
=>We can create Two types of list objects. They are
1. Empty list
2. Non-Empty list
-------------------------
Empty List
-------------------------
=>An empty list is one, which does not contain any Elements and whose length is 0.
=>Syntax1: listobj=[ ]
=>Syntax2: listobj=list()
-------------------------
Non-Empty List
-------------------------
=>A Non-Empty list is one, which contains Elements and whose length is > 0.
=>Syntax1: listobj=[Val1,Val2,....,Val-n]

=>Syntax2: listobj=list(object)
75
----------------------------------------------------------------------------------------------------------------
Examples
------------------------------------------------------------------------------------------------------------------
>>> lst1=[10,20,30,10,20,30,40]
>>> print(lst1,type(lst1))------------------[10, 20, 30, 10, 20, 30, 40] <class 'list'>
>>> lst2=[100,"RS",34.56,True,2+3j]
>>> print(lst2,type(lst2))------------------[100, 'RS', 34.56, True, (2+3j)] <class 'list'>
--------------------------------------
>>> lst2=[100,"RS",34.56,True,2+3j]
>>> print(lst2,type(lst2))-------------[100, 'RS', 34.56, True, (2+3j)] <class 'list'>
>>> lst2[0]--------------------------------100
>>> lst2[-1]-------------------------------(2+3j)
>>> lst2[len(lst2)-1]--------------------(2+3j)
>>> lst2[-len(lst2)]---------------------100
>>> lst2[1:4]-----------------------------['RS', 34.56, True]
>>> lst2[::2]-----------------------------[100, 34.56, (2+3j)]
>>> lst2[::-1]----------------------------[(2+3j), True, 34.56, 'RS', 100]
-------------------------------------------------
>>> lst2=[100,"RS",34.56,True,2+3j]
>>> print(lst2,type(lst2),id(lst2))---------------[100, 'RS', 34.56, True, (2+3j)] <class 'list'> 2234809075520
>>> lst2[1]-------------------------'RS'
>>> lst2[1]="Guido Van Rossum" # Indexed Based Assignment
>>> print(lst2,type(lst2),id(lst2))------------[100, 'Guido Van Rossum', 34.56, True, (2+3j)] <class 'list'>
2234809075520
>>> lst2[2:4]--------------------------------[34.56, True]
>>> lst2[2:4]=[55.55,False] # Slice Based Assignment
>>> print(lst2,type(lst2),id(lst2))---------[100, 'Guido Van Rossum', 55.55, False, (2+3j)] <class 'list'>
2234809075520
>>> lst2=[100,"RS",34.56,True,2+3j]
>>> print(lst2,type(lst2),id(lst2))-------------[100, 'RS', 34.56, True, (2+3j)] <class 'list'> 2234809078784
>>> lst2[::2]=[1000,44.44,-4-4.5j]
>>> print(lst2,type(lst2),id(lst2))------------[1000, 'RS', 44.44, True, (-4-4.5j)] <class 'list'> 2234809078784
---------------------------------------------------

76
>>> lst1=[100,"RS"]
>>> print(lst1,type(lst1))----------------[100, 'RS'] <class 'list'>
>>> len(lst1)--------------------------------2

>>> lst1=[]
>>> print(lst1,type(lst1))---------------[] <class 'list'>
>>> len(lst1)-------------------------------0
OR
>>> lst2=list()
>>> print(lst2,type(lst2))--------------[] <class 'list'>
>>> len(lst2)------------------------------0
--------------------------------------------------------------------
>>> s="MISSISSIPPI"
>>> print(s,type(s))--------------------------MISSISSIPPI <class 'str'>
>>> lst=list(s)
>>> print(lst,type(lst))----------------------['M', 'I', 'S', 'S', 'I', 'S', 'S', 'I', 'P', 'P', 'I'] <class 'list'>
>>> s="ABRAKADABRA"
>>> print(s,type(s))-------------------------ABRAKADABRA <class 'str'>
>>> lst=list(s)
>>> print(lst,type(lst))---------------------['A', 'B', 'R', 'A', 'K', 'A', 'D', 'A', 'B', 'R', 'A'] <class 'list'>
>>> lst=[10,20,30,40]
>>> print(lst,type(lst))--------------------[10, 20, 30, 40] <class 'list'>
>>> b=bytes(lst)
>>> print(b,type(b))-----------------------b'\n\x14\x1e(' <class 'bytes'>
>>> lst1=list(b)
>>> print(lst1,type(lst1))----------------[10, 20, 30, 40] <class 'list'>
------------------------------------------------------------------------------------
#All Fundamental value are Not Possible to Convert into List bcoz they are all NON-ITERABLE Objects
>>>a=10
>>> lst=list(a)-------------------TypeError: 'int' object is not iterable
>>> lst=list(1.2)-----------------TypeError: 'float' object is not iterable
>>> lst=list(True)----------------TypeError: 'bool' object is not iterable
>>> lst=list(2+3j)----------------TypeError: 'complex' object is not iterable

77
-----------------------------------------------------------------------------------------------------
>>> lst=list([10]) # POSSIBLE
>>> print(lst,type(lst))---------[10] <class 'list'>
>>> lst=list([10.45])
>>> print(lst,type(lst))-----------[10.45] <class 'list'>
>>> lst=list([True])
>>> print(lst,type(lst))----------[True] <class 'list'>
-----------------------------------------------------------------------------------------------------
>>> s="MISSISSIPPI"
>>> print(s,type(s))---------------MISSISSIPPI <class 'str'>
>>> lst=list([s])
>>> print(lst,type(lst))-------------['MISSISSIPPI'] <class 'list'>
=============================================x=======================
==============================================================
Pre-Defined Functions in list
==============================================================
=>We know that on the object of list, we can perform both Indexing and Slicing Operations
=>With Indexing, we get / Access Single Value and we can update single value of List object
=>With Slicing Operation we get / access multiple values and we can update Multiple Values of list object.
=>Hence with index and slicing Operation on list, we can access and update value(s).
=>To do More Operation on list object along with index and slicing Operation, we use the pre-defined functions
present in list object.
=>The pre-defined functions of list are given bellow.
---------------------------------------------------------------------------------------------------------------------
1. append()
---------------------------------------------------------------------------------------------------------------------
=>This function is used for adding the element / value at the end of list (called Appending)
=>Syntax: listobj.append(Value)
--------------
Examples
--------------
>>> lst=[10,"RS"]
>>> print(lst,id(lst))-----------[10, 'RS'] 2234811887168
78
>>> lst.append("Python")
>>> print(lst,id(lst))-----------[10, 'RS', 'Python'] 2234811887168
>>> lst.append(34.56)
>>> print(lst,id(lst))-----------[10, 'RS', 'Python', 34.56] 2234811887168
-----------------------
>>> lst=[]
>>> print(lst,id(lst))-----------[] 2234812410688
>>> lst.append(10)
>>> lst.append(1.2)
>>> lst.append(True)
>>> print(lst,id(lst))-----------[10, 1.2, True] 2234812410688
------------------------------------------------------------------------------------------------------------------
2. insert()
------------------------------------------------------------------------------------------------------------------
=>Syntax: listobj.insert(Index,value)
=>This function is used for Inserting an Element in the Existing List at Specified Index
=>Here the Index Can be either +Ve or -Ve
=>If we Specify Invalid +VE Index then the Value Inserted as last Element in list
=>If we Specify Invalid -VE Index then the Value Inserted as First Element in list
------------------

Examples
------------------
>>> lst=[10,"RS",34.56]
>>> print(lst,type(lst),id(lst))-----------[10, 'RS', 34.56] <class 'list'> 2189625840192
>>> lst.insert(2,"Python")
>>> print(lst,type(lst),id(lst))-----------[10, 'RS', 'Python', 34.56] <class 'list'> 2189625840192
>>> lst.insert(1,"GUIDO")
>>> print(lst,type(lst),id(lst))-----------[10, 'GUIDO', 'RS', 'Python', 34.56] <class 'list'> 2189625840192
--------------------
>>> lst=[10,"RS",34.56]
>>> print(lst,type(lst),id(lst))------------[10, 'RS', 34.56] <class 'list'> 2189626161728
>>> lst.insert(-1,"Python")
>>> print(lst,type(lst),id(lst))------------[10, 'RS', 'Python', 34.56] <class 'list'> 2189626161728
79
>>> lst.insert(-2,"HTML")
>>> print(lst,type(lst),id(lst))------------[10, 'RS', 'HTML', 'Python', 34.56] <class 'list'> 2189626161728
------------------------
>>> lst=[10,"RS",34.56]
>>> print(lst,type(lst),id(lst))--------------[10, 'RS', 34.56] <class 'list'> 2189625840192
>>> lst.insert(100,"PYTHON")
>>> print(lst,type(lst),id(lst))--------------[10, 'RS', 34.56, 'PYTHON'] <class 'list'> 2189625840192
>>> lst.insert(-100,"HYD")
>>> print(lst,type(lst),id(lst))--------------['HYD', 10, 'RS', 34.56, 'PYTHON'] <class 'list'> 2189625840192
---------------------------------------------------------------------------------------------------------------------------------------
3. remove()----------Based on Value Removing
---------------------------------------------------------------------------------------------------------------------------------------
=>Syntax: listobj.remove(Value)
=>This function is used for Removing the First Occurence of Specified Value from List Object.
=>If the Specified value does not exist then we get ValueError
----------------
Examples
----------------
>>> lst=['HYD', 10, 'RS', 34.56, 'PYTHON']
>>> print(lst,id(lst))--------------['HYD', 10, 'RS', 34.56, 'PYTHON'] 2189626161728
>>> lst.remove(10)
>>> print(lst,id(lst))-------------['HYD', 'RS', 34.56, 'PYTHON'] 2189626161728
>>> lst.remove("HYD")
>>> print(lst,id(lst))-------------['RS', 34.56, 'PYTHON'] 2189626161728
>>> lst.remove("PYTHON")
>>> print(lst,id(lst))-------------['RS', 34.56] 2189626161728
>>> lst.remove("HYD")------------ValueError: list.remove(x): x not in list
--------------------------------
>>> lst=[10,20,20,10,30,40,10,40]
>>> print(lst,id(lst))-----------[10, 20, 20, 10, 30, 40, 10, 40] 2189625840192
>>> lst.remove(10)
>>> print(lst,id(lst))-----------[20, 20, 10, 30, 40, 10, 40] 2189625840192
>>> lst.remove(20)

80
>>> print(lst,id(lst))-----------[20, 10, 30, 40, 10, 40] 2189625840192
>>> lst.remove(10)
>>> print(lst,id(lst))-----------[20, 30, 40, 10, 40] 2189625840192
>>> lst.remove(100)-----------ValueError: list.remove(x): x not in list
-----------------------------------
>>> [].remove(100)------------------ValueError: list.remove(x): x not in list
>>> list().remove("PYTHON")----ValueError: list.remove(x): x not in list
---------------------------------------------------------------------------------------------------------------------------------------
4. pop(index)------Based Index Removing
---------------------------------------------------------------------------------------------------------------------------------------
=>Syntax: listobj.pop(index)
=>This Function is used for Removing an Element of List Based on Valid Index
=>Here Index can b either +ve or -ve
=>If we enter Invalid Index then we get IndexError
---------------------------
Examples
---------------------------
>>> lst=[10,20,20,10,30,40,10,40]
>>> print(lst,id(lst))-----------[10, 20, 20, 10, 30, 40, 10, 40] 2189628867520
>>> lst.pop(3)-------------------10
>>> print(lst,id(lst))------------[10, 20, 20, 30, 40, 10, 40] 2189628867520
>>> lst.pop(2)-------------------20
>>> print(lst,id(lst))------------[10, 20, 30, 40, 10, 40] 2189628867520
>>> lst.pop(-2)------------------10
>>> print(lst,id(lst))------------[10, 20, 30, 40, 40] 2189628867520
>>> lst.pop(-2)-------------------40
>>> print(lst,id(lst))--------------[10, 20, 30, 40] 2189628867520
>>> lst.pop(4)----------------------IndexError: pop index out of range
---------------------
>>> [].pop(0)--------IndexError: pop from empty list
>>> list().pop(-1)---IndexError: pop from empty list

81
---------------------------------------------------------------------------------------------------------------------------------------
5. pop()
---------------------------------------------------------------------------------------------------------------------------------------
=>Syntax: listobj.pop()
=>This Function is used for Removing the Last Element of List
=>If we call this function in empty list object then we get IndexError
--------------------
Examples
--------------------
>>> lst=[10,20,20,10,30,40,10,40]
>>> print(lst,id(lst))-----------[10, 20, 20, 10, 30, 40, 10, 40] 2189628907136
>>> lst.pop()--------------------40
>>> print(lst,id(lst))------------[10, 20, 20, 10, 30, 40, 10] 2189628907136
>>> lst.pop()---------------------10
>>> print(lst,id(lst))----------[10, 20, 20, 10, 30, 40] 2189628907136
>>> lst.pop()-------------------40
>>> print(lst,id(lst))----------[10, 20, 20, 10, 30] 2189628907136
>>> lst.pop()--------------------30
----------------------------
>>> lst=[10,20,30]
>>> print(lst)-----------[10, 20, 30]
>>> lst.pop()------------30
>>> print(lst)------------[10, 20]
>>> lst.pop()-------------20
>>> print(lst)-------------[10]
>>> lst.pop()--------------10
>>> print(lst)--------------[]
>>> lst.pop()---------------IndexError: pop from empty list
>>> list().pop()--------IndexError: pop from empty list
***********************************************************
NOTE : del operator
***********************************************************
Syntax-1: del listobj[Index]-----Removes One Element from List Based Indexing
82
Syntax-2: del listobj[Begin Index : End Index:Step]-->Removes Element(s) based on Slicing
Syntax-3: del listobj------------->Removes All Elements + List Object also
---------------
Most IMP: del Operator Can Remove Elements of MUTABLE Objects either With Indexing, Slicing and
entire Object also where del operator can't be used to Elements of IMMUTABLE Objects bUt we can remove
Entire Immutable Object (Content +Physical object)
=>Once we Remove The Mutable OR Immutable Object by using del Operator, whose memory space collected
by Garbage Collector
--------------------
Examples
--------------------
>>> lst=[10,"RS","PYTHOn",34.56,True,2+3j]
>>> print(lst,id(lst))---------[10, 'RS', 'PYTHOn', 34.56, True, (2+3j)] 2189628867520
>>> del lst[-3]
>>> print(lst,id(lst))---------[10, 'RS', 'PYTHOn', True, (2+3j)] 2189628867520
>>> del lst[2:4]
>>> print(lst,id(lst))---------[10, 'RS', (2+3j)] 2189628867520
>>> del lst[::]
>>> print(lst,id(lst))---------[] 2189628867520
------------------------
>>> lst=[10,"RS","PYTHOn",34.56,True,2+3j]
>>> print(lst,id(lst))--------[10, 'RS', 'PYTHOn', 34.56, True, (2+3j)] 2189628901568
>>> del lst
>>> print(lst,id(lst))------------NameError: name 'lst' is not defined
-------------------------------------------------
>>> s="PYTHON"
>>> print(s,type(s))---------PYTHON <class 'str'>-------Its an IMMUTABLE
>>> del s[-2]----------TypeError: 'str' object doesn't support item deletion
>>> del s[::2]---------TypeError: 'str' object does not support item deletion
>>> del s # Immutable Objects can Removed
>>> print(s,type(s))----------NameError: name 's' is not defined

83
---------------------------------------------------------------------------------------------------------------------------------------
6. clear()
---------------------------------------------------------------------------------------------------------------------------------------
=>Syntax: listobj.clear()
=>This Function is used for Removing all Elements from List object
=>If we call this function upon empty list object then we get Space or None as Result.
-----------------
Examples
------------------
>>> lst=[10,"RS","PYTHOn",34.56,True,2+3j]
>>> print(lst,id(lst))-------[10, 'RS', 'PYTHOn', 34.56, True, (2+3j)] 2189628901568
>>> len(lst)------------------6
>>> lst.clear()
>>> print(lst,id(lst))-------[] 2189628901568
>>> len(lst)------------------0
---------------------------
>>> print([].clear())---------None
OR
>>> print(list().clear())----None
---------------------------------------------------------------------------------------------------------------------------------------
7. index()
---------------------------------------------------------------------------------------------------------------------------------------
=>Syntax: listobj.index(Value)
=>This Function is used for Obtaining the Index of First occurence of Specified Element.
=>If the Specified values does not exist then we get ValueError
-------------------------------
Examples
-------------------------------
>>> lst=[10,20,30,40,10,50,60,10,20,10]
>>> print(lst)--------------[10, 20, 30, 40, 10, 50, 60, 10, 20, 10]
>>> lst.index(10)----------0
>>> lst.index(20)----------1
>>> lst.index(200)------------ValueError: 200 is not in list
84
***********************************
enumerate()
***********************************
=>This Function is used for obtaining Index and Value Entries for Every Element of Iterable
Object(Contains More
than One Value)
=>Syntax: enumerate (IterableObject)
-----------------
Examples
-----------------
>>> lst=[10,20,30,40,10,50,60,10,20,10]
>>> print(lst,type(lst))---------[10, 20, 30, 40, 10, 50, 60, 10, 20, 10] <class 'list'>
>>> for i,v in enumerate(lst):
... print(i,"--->",v)
...
0 ---> 10
1 ---> 20
2 ---> 30
3 ---> 40
4 ---> 10
5 ---> 50
6 ---> 60
7 ---> 10
8 ---> 20
9 ---> 10
>>> for i,v in enumerate(lst):
... if(v==10):
... print(i,"--->",v)
...
0 ---> 10
4 ---> 10
7 ---> 10
9 ---> 10

85
>>> for i,v in enumerate(lst):
... if(v==20):
... print(i,"--->",v)
...
1 ---> 20
8 ---> 20
>>> s="MISSISSIPPI"
>>> for index,Value in enumerate(s):
... print(index,"--->",Value)
...
0 ---> M
1 ---> I
2 ---> S
3 ---> S
4 ---> I
5 ---> S
6 ---> S
7 ---> I
8 ---> P
9 ---> P
10 ---> I
>>> for index,Value in enumerate(s):
... if(Value=="I"):
... print(index,"--->",Value)
...
1 ---> I
4 ---> I
7 ---> I
10 ---> I
>>> for index,Value in enumerate(s):
... if(Value=="S"):
... print(index,"--->",Value)
...

86
2 ---> S
3 ---> S
5 ---> S
6 ---> S
----------------------------------------------------------------------------------------------------------------------------------
8. copy()
----------------------------------------------------------------------------------------------------------------------------------
=>Syntax: listobj2=listobj1.copy()
=>This Function is used for Copying the content of One List Object to Another List Object (It Implements
Shallow Copy).
-------------------
Examples
-------------------
>>> lst1=[100,"RS"]
>>> print(lst1,type(lst1),id(lst1))----------[100, 'RS'] <class 'list'> 1376488641088
>>> lst2=lst1.copy() # Shallow Copy
>>> print(lst2,type(lst2),id(lst2))---------[100, 'RS'] <class 'list'> 1376491603904
>>> lst1.append("Python")
>>> lst2.insert(0,"NL")
>>> print(lst1,type(lst1),id(lst1))---------[100, 'RS', 'Python'] <class 'list'> 1376488641088
>>> print(lst2,type(lst2),id(lst2))---------['NL', 100, 'RS'] <class 'list'> 1376491603904
----------------------------------------------------------------------------------------------------------------------------------
9. count()
----------------------------------------------------------------------------------------------------------------------------------
Syntax: listobj.count(Value)
=>This Function is used for Counting Number of Occurences of Specified Value.
=>If the Specified Value does not exist then we get 0.
--------------------
Examples
--------------------
>>> lst=[10,20,30,40,10,50,60,10,20,10,20,30,40,20]
>>> print(lst,type(lst))----[10, 20, 30, 40, 10, 50, 60, 10, 20, 10, 20, 30, 40, 20] <class 'list'>
>>> lst.count(10)----------4
87
>>> lst.count(20)----------4
>>> lst.count(30)----------2
>>> lst.count(40)----------2
>>> lst.count(50)----------1
>>> lst.count(60)-----------1
>>> lst.count(160)--------0
>>> [].count(10)------------0
>>> list().count(100)------0
--------------------------
>>> s="MISSISSIPPI"
>>> lst=list(s)
>>> print(lst)-------------['M', 'I', 'S', 'S', 'I', 'S', 'S', 'I', 'P', 'P', 'I']
>>> lst.count("I")-------4
>>> lst.count("S")------4
>>> lst.count("M")-----1
>>> lst.count("P")------2
---------------------
>>> list("NISSON").count("S")----------------2
>>> ["ABRAKADABRA"].count("A")--------0
>>> ["A","B","R","A","K","A","D","A","B","R","A"].count("A")---5
>>> list(["ABRAKADABRA"][0]).count("R")--------2
>>> ["ABRAKADABRA"][0]------------------------------'ABRAKADABRA'
----------------------------------------------------------------------------------------------------------------------------------
10. reverse()
----------------------------------------------------------------------------------------------------------------------------------
Syntax: listobj.reverse()
=>This Function is used for reversing the elements(Front Elements becomes backelements and Vice-Versa)
of listobject and Reversed Eleemnts placed in same listobj itself.
-----------------
Examples
-----------------
>>> lst=[10,20,15,12,6,17]
>>> print(lst,id(lst))-------[10, 20, 15, 12, 6, 17] 1376491602752

88
>>> lst1=lst.reverse()
>>> print(lst,id(lst))--------[17, 6, 12, 15, 20, 10] 1376491602752
>>> print(lst1)---------None
>>> lst1=["Python","Java","HTML","C"]
>>> print(lst1,id(lst1))--------['Python', 'Java', 'HTML', 'C'] 1376491547520
>>> lst1.reverse()
>>> print(lst1,id(lst1))--------['C', 'HTML', 'Java', 'Python'] 1376491547520
----------------------------------------------------------------------------------------------------------------------------------
11. sort()-----Most Imp
----------------------------------------------------------------------------------------------------------------------------------
=>Syntax1: listobj.sort()-------------------->Gives the List Data in ASCENDING ORDER(Here by default
reverse is False)
=>Syntax2: listobj.sort(reverse=False)--->Also Gives the List Data in ASCENDING ORDER
=>Syntax3: listobj.sort(reverse=True)------>Gives the List Data in DESCENDING ORDER
=>When we sort the Data, Data must Similar Otherwise we get TypeError
-------------------
Examples
-------------------
>>> lst1=[10,12,4,-5,0,23,11]
>>> print(lst1,id(lst1))-----------[10, 12, 4, -5, 0, 23, 11] 1376491603200
>>> lst1.sort()
>>> print(lst1,id(lst1))-------[-5, 0, 4, 10, 11, 12, 23] 1376491603200
>>> lst1.reverse()
>>> print(lst1,id(lst1))--------[23, 12, 11, 10, 4, 0, -5] 1376491603200
------------------
>>> lst1=[10,12,4,-5,0,23,11]
>>> print(lst1,id(lst1))--------[10, 12, 4, -5, 0, 23, 11] 1376491547520
>>> lst1.sort(reverse=True)
>>> print(lst1,id(lst1))-------[23, 12, 11, 10, 4, 0, -5] 1376491547520
-------------------
>>> lst1=[10,12,4,-5,0,23,11]
>>> print(lst1,id(lst1))-------[10, 12, 4, -5, 0, 23, 11] 1376491603200
>>> lst1.sort(reverse=False)
89
>>> print(lst1,id(lst1))--------[-5, 0, 4, 10, 11, 12, 23] 1376491603200
--------------------
>>> lst1=[10,"RS",23.45,True,2+3j]
>>> lst1.sort()---------TypeError: '<' not supported between instances of 'str' and 'int'
----------------------------------------------------------------------------------------------------------------------------------
12. extend()
----------------------------------------------------------------------------------------------------------------------------------
=>Syntax: listobj1.extend(listobj2)
=>This function is used for Merging the content of Two List Objects.
=>Here The content of Listobj2 is Merged with Listobj1
OR
Syntax: lstobj1=lstobj1+lstobj2+.......+lstobj-n
-----------------
Examples
------------------
>>> lst1=[10,20,30,40]
>>> lst2=["RS","TR","SR"]
>>> print(lst1)----------[10, 20, 30, 40]
>>> print(lst2)----------['RS', 'TR', 'SR']
>>> lst1.extend(lst2)
>>> print(lst1)----------[10, 20, 30, 40, 'RS', 'TR', 'SR']
--------------------------------------------------
OR
--------------------------------------------------
>>> lst1=[10,20,30,40]
>>> lst2=["RS","TR","SR"]
>>> print(lst1,id(lst1))------------[10, 20, 30, 40] 1376491603200
>>> print(lst2,id(lst2))------------['RS', 'TR', 'SR'] 1376491547520
>>> lst1=lst1+lst2
>>> print(lst1,id(lst1))-----------[10, 20, 30, 40, 'RS', 'TR', 'SR'] 1376492918528
===================================x=========================================

90
===============================================================
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 Outer List Elements
Here val11,val12...val1n are called One inner Elements
Here val21,val22...val2n are called another inner Elements
=>On Inner List, we can perform Both Indexing and Slicing Operations
=>On Inner List, we can apply all types of Pre-defined functions of list
=============================================================================
Examples
=============================================================================
>>> lst=[10,"RS",[15,17,19] ,[79,66,80],"OUCET"]
>>> print(lst)------[10, 'RS', [15, 17, 19], [79, 66, 80], 'OUCET']
>>> for val in lst:
... print(val,type(val),type(lst))
...
10 <class 'int'> <class 'list'>
RS <class 'str'> <class 'list'>
[15, 17, 19] <class 'list'> <class 'list'>
[79, 66, 80] <class 'list'> <class 'list'>
OUCET <class 'str'> <class 'list'>
------------------------------------------------------------------------------
>>> lst=[10,"RS",[15,17,19] ,[79,66,80],"OUCET"]
>>> print(lst,type(lst))----------[10, 'RS', [15, 17, 19], [79, 66, 80], 'OUCET'] <class 'list'>
>>> print(lst[2],type(lst[2]))--------[15, 17, 19] <class 'list'>
>>> print(lst[-2],type(lst[-2]))---------[79, 66, 80] <class 'list'>
>>> lst[0:3]----------------------------[10, 'RS', [15, 17, 19]]
>>> lst[2:4]-----------------------------[[15, 17, 19], [79, 66, 80]]
>>> lst[2][::2]--------------------------[15, 19]
>>> lst[-2][-2]-------------------------66
>>> lst[-2][-2]=68

91
>>> print(lst,type(lst))----------------[10, 'RS', [15, 17, 19], [79, 68, 80], 'OUCET'] <class 'list'>
>>> lst[-2][::2]=[75,76]
>>> print(lst,type(lst))--------------[10, 'RS', [15, 17, 19], [75, 68, 76], 'OUCET'] <class 'list'>
>>> lst[-3].append(14)
>>> print(lst,type(lst))------------[10, 'RS', [15, 17, 19, 14], [75, 68, 76], 'OUCET'] <class 'list'>
>>> lst[-2].insert(-2,65)
>>> print(lst,type(lst))------------[10, 'RS', [15, 17, 19, 14], [75, 65, 68, 76], 'OUCET'] <class 'list'>
>>> lst[2].sort()
>>> print(lst,type(lst))------------[10, 'RS', [14, 15, 17, 19], [75, 65, 68, 76], 'OUCET'] <class 'list'>
>>> lst[-2].sort(reverse=True)
>>> print(lst,type(lst))------------[10, 'RS', [14, 15, 17, 19], [76, 75, 68, 65], 'OUCET'] <class 'list'>
>>> del lst[2][1::2]
>>> print(lst,type(lst))------------[10, 'RS', [14, 17], [76, 75, 68, 65], 'OUCET'] <class 'list'>
>>> lst[3].clear()
>>> print(lst,type(lst))----------[10, 'RS', [14, 17], [], 'OUCET'] <class 'list'>
>>> lst[-2].append(67)
>>> print(lst,type(lst))-----------------------[10, 'RS', [14, 17], [67], 'OUCET'] <class 'list'>
>>> del lst[2]
>>> print(lst,type(lst))----------------------[10, 'RS', [67], 'OUCET'] <class 'list'>
>>> lst.insert(2,[16,14,18])
>>> print(lst,type(lst))----------------------[10, 'RS', [16, 14, 18], [67], 'OUCET'] <class 'list'>
>>> lst[3].append(80)
>>> lst[3].append(77)
>>> print(lst,type(lst))----------------------[10, 'RS', [16, 14, 18], [67, 80, 77], 'OUCET'] <class 'list'>
>>> del lst[2:4]
>>> print(lst,type(lst))---------------------[10, 'RS', 'OUCET'] <class 'list'>
=============================================================================
>>> matrix1=[[10,20,30],[40,50,60],[70,80,90]]
>>> for row in matrix1:
... print(row)
...
[10, 20, 30]
[40, 50, 60]

92
[70, 80, 90]
>>> matrix2=[[1,2,3],[4,5,6],[7,8,9]]
>>> for row in matrix2:
... print(row)
...
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
>>> mat3=matrix1+matrix2
>>> for row in mat3:
... print(row)
...
[10, 20, 30]
[40, 50, 60]
[70, 80, 90]
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
=============================================================================
2. tuple
=============================================================================
Index
--------------------
=>Properties of tuple
=>What is tuple
=>Notations of tuple
=>Types of tuple
=>Operations on tuple
=>Pre-defined Functions in tuple
=>Nested OR Inner tuple
=>Combination tuples with list
=>Programming Examples

93
---------------------------------------------------------------------------------------------------------------------------------------
Properties of tuple
---------------------------------------------------------------------------------------------------------------------------------------
=>'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 of Same Type OR Different Type Or the
Both the Types with Unique and Duplicate Values in Single Object . In otherwords tuple used for storing
Constant Values of Multiple Values of Same Type OR Different Type Or the Both the Types with Unique and
Duplicate Values in Single Object.
=>To store the Elements OR Values in the object of tuple, we use braces ( ) and the Values separated by
comma.
=>On the object of tuple, we can perform Both Indexing and Slicing Operations.
=>An object of tuple belongs to IMMUTABLE bcoz tuple object does not allows us to perform Item
Assigment.
=>An Object of tuple maintains Insertion Order.
=>In Python Programming, we can create Two Types of tuple objects. They are
1) Empty tuple
2) Non-Empty tuple
------------------------------------
1) Empty tuple
------------------------------------
=>An Empty tuple is one which does not contain any Elements and whose length is 0
=>Syntax: varname=()
(OR)
varname=tuple()
---------------------------------
2) Non-Empty tuple
------------------------------------
=>A Non-Empty tuple is one which contains Elements and whose length is >0
=>Syntax: varname=(Val1,Val2,.....,Val-n)
OR
varname=tuple(object)
OR
varname=Val1,Val2,.....,Val-n
94
OR
varname=(Val1,)
---------------------------------------------------------------------------------------------------------------------------------------
NOTE: The Functionality of tuple is exactly similar to list, But an Object list belongs to MUTABLE where an
object of tuple belongs to IMMUTABLE.

Examples
---------------------------------------------------------------------------------------------------------------------------------------
>>> t1=(10,20,30,10,40,20-23,2.3)
>>> print(t1,type(t1))---------------(10, 20, 30, 10, 40, -3, 2.3) <class 'tuple'>
>>> t2=(10,"RS",34.56,True,2+3j)
>>> print(t2,type(t2))---------------(10, 'RS', 34.56, True, (2+3j)) <class 'tuple'>
-----------------------------------------------
>>> t3=10,"TR",45.67,True,"NL"
>>> print(t3,type(t3))--------------(10, 'TR', 45.67, True, 'NL') <class 'tuple'>
------------------------------------------------
>>> t4=(10)
>>> print(t4,type(t4))--------------10 <class 'int'>
>>> t4=(10,)
>>> print(t4,type(t4))---------------(10,) <class 'tuple'>
>>> t4=10,
>>> print(t4,type(t4))---------------(10,) <class 'tuple'>
-----------------------------------------
>>> t1=(10,20,30,10,40,20-23,2.3)
>>> print(t1,type(t1))-------------------------(10, 20, 30, 10, 40, -3, 2.3) <class 'tuple'>
>>> t1[0]-----------------------------------------10
>>> t1[-1]----------------------------------------2.3
>>> t1[2]----------------------------------------30
>>> t1[2:]---------------------------------------(30, 10, 40, -3, 2.3)
>>> t1[::2]-------------------------------------(10, 30, 40, 2.3)
>>> t1[::-1]------------------------------------(2.3, -3, 40, 10, 30, 20, 10)
-----------------------------------------------------
>>> t1=(10,20,30,10,40,20-23,2.3)
95
>>> print(t1,type(t1),id(t1))-----------(10, 20, 30, 10, 40, -3, 2.3) <class 'tuple'> 1785575627680
>>> t1[0]=25-------TypeError: 'tuple' object does not support item assignment---IMMUTABLE
---------------------------------------------------------
>>> s="MISSISSIPPI"
>>> print(s,type(s))---------------------MISSISSIPPI <class 'str'>
>>> t=tuple(s)
>>> print(t,type(t))------------------------('M', 'I', 'S', 'S', 'I', 'S', 'S', 'I', 'P', 'P', 'I') <class 'tuple'>
>>> l1=[10,20,30,40]
>>> print(l1,type(l1))----------------------[10, 20, 30, 40] <class 'list'>
>>> t1=tuple(l1)
>>> print(t1,type(t1))-------------------------(10, 20, 30, 40) <class 'tuple'>
>>> t1=tuple(range(10,20,2))
>>> print(t1,type(t1))------------------------(10, 12, 14, 16, 18) <class 'tuple'>
----------------------------------------
MOST IMP
----------------------------------------
>>> a=10
>>> print(a,type(a))---------10 <class 'int'>
>>> t=tuple(a)--------------------TypeError: 'int' object is not iterable
>>> t=tuple(12.34)--------------TypeError: 'float' object is not iterable
>>> a=10
>>> print(a,type(a))-----------10 <class 'int'>
>>> t=tuple(a,)-----------TypeError: 'int' object is not iterable
>>> t=tuple([a]) # Possible
>>> print(t,type(t))-----------(10,) <class 'tuple'>
>>> t=tuple((a))--------------TypeError: 'int' object is not iterable
===============================================================================
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 present in tuple.

96
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
-----------------------------------------------------
>>> t1=(10,20,30,40,50,10)
>>> print(t1,id(t1),type(t1))---------(10, 20, 30, 40, 50, 10) 2420310634464 <class 'tuple'>
>>> t2=t1 # Deep Copy Possible but Not Shallow Copy
>>> print(t2,id(t2),type(t2))----------(10, 20, 30, 40, 50, 10) 2420310634464 <class 'tuple'>
>>> t3=t1 # Deep Copy Possible but Not Shallow Copy
>>> print(t3,id(t3),type(t3))---------(10, 20, 30, 40, 50, 10) 2420310634464 <class 'tuple'>
-------------------------------------------------
The Functions not present in tuple
-------------------------------------------------
append()
insert()
remove()
clear()
pop(index)

97
pop()
reverse()
sort()
copy()
extend()
---------------------------------------
NOTE:- By Using del Operator we can't delete values of tuple object By using Indexing and slicing bcoz
tuple object belongs to Immutable but we can delete entire tuple 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'>
>>> 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]
98
>>> 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'>
====================================================
Types of Copy Techniques in Python
====================================================
=>In Python Programming, we have 2 Types of Copy Techniques. They are
1. Shallow Copy
2. Deep Copy
************************************************
1. Shallow Copy
************************************************
=>The Properties of Shallow Copy are
a) The Initial Content of Both the Objects are Same.
b) The Memory Address of Both the Objects are Different.
c) The Modifications are Independent.
(Whatever the Changes we do on one Object, Those Changes are not Reflecting to another object bcoz
Memory address are Different)
=>To Implement Shallow Copy, we use copy()
=>Syntax: Object2=Object1.copy()
-----------------------------------------------------
Examples
-----------------------------------------------------
>>> lst1=[100,"RS"]
99
>>> print(lst1,type(lst1),id(lst1))----------[100, 'RS'] <class 'list'> 1376488641088
>>> lst2=lst1.copy() # Shallow Copy
>>> print(lst2,type(lst2),id(lst2))---------[100, 'RS'] <class 'list'> 1376491603904
>>> lst1.append("Python")
>>> lst2.insert(0,"NL")
>>> print(lst1,type(lst1),id(lst1))---------[100, 'RS', 'Python'] <class 'list'> 1376488641088
>>> print(lst2,type(lst2),id(lst2))---------['NL', 100, 'RS'] <class 'list'> 1376491603904
************************************************
2. Deep Copy
************************************************
=>The Properties of Deep Copy are
a) The Initial Content of Both the Objects are Same.
b) The Memory Address of Both the Objects are Same.
c) The Modifications are Dependent.
(Whatever the Changes we do on one Object, Those Changes are Reflecting to another object bcoz
Memory address are Same)
=>To Implement Deep Copy, we use Assignment Operator ( = ) Only.
=>Syntax: Object2 = Object1
----------------------------
Examples
----------------------------
>>> lst1=[100,"RS"]
>>> print(lst1,type(lst1),id(lst1))--------[100, 'RS'] <class 'list'> 1376492918528
>>> lst2=lst1 # Deep Copy
>>> print(lst2,type(lst2),id(lst2))--------[100, 'RS'] <class 'list'> 1376492918528
>>> lst1.append("PYTHON")
>>> print(lst1,type(lst1),id(lst1))--------[100, 'RS', 'PYTHON'] <class 'list'> 1376492918528
>>> print(lst2,type(lst2),id(lst2))-------[100, 'RS', 'PYTHON'] <class 'list'> 1376492918528
>>> lst1.insert(1,"Guido")
>>> print(lst1,type(lst1),id(lst1))-------[100, 'Guido', 'RS', 'PYTHON'] <class 'list'> 1376492918528
>>> print(lst2,type(lst2),id(lst2))------[100, 'Guido', 'RS', 'PYTHON'] <class 'list'> 1376492918528
>>> lst2.remove("RS")
>>> print(lst1,type(lst1),id(lst1))------[100, 'Guido', 'PYTHON'] <class 'list'> 1376492918528
100
>>> print(lst2,type(lst2),id(lst2))------[100, 'Guido', 'PYTHON'] <class 'list'> 1376492918528

=============================================
Nested OR Inner tuple
=============================================
=>The Process of Defining One tuple Inside of Another tuple is called Inner OR Nested tuple.
=>Syntax: tplobj=(Val1,Val2......(Val11,Val12....Val-1n), (Val21,Val22,...Val-2n),....Val-n)
=>Here (Val1,Val2......,....Val-n) is called Outer tuple Eleemnts
=>Here (Val11,Val12....Val-1n) is called Inner tuple Elements
=>Here (Val21,Val22,...Val-2n) is also another Inner tuple Elements.
=>On the Inner tuple Objects, we can also Perform Both Indexing and Slicing Operations.
=>On the Objects Inner tuple, we can apply all the Pre-defined Functions of tuple ( index(), count() )
==============================================================================
Examples
==============================================================================
>>> t1=(10,"RS",(16,18,17),(67,80,78),"OUCET")
>>> print(t1,type(t1))-------------(10, 'RS', (16, 18, 17), (67, 80, 78), 'OUCET') <class 'tuple'>
>>> for val in t1:
... print(val,type(val),type(t1))
...
10 <class 'int'> <class 'tuple'>
RS <class 'str'> <class 'tuple'>
(16, 18, 17) <class 'tuple'> <class 'tuple'>
(67, 80, 78) <class 'tuple'> <class 'tuple'>
OUCET <class 'str'> <class 'tuple'>
------------------------------------------------------------------------------------------------
>>> t1=(10,"Rossum",(17,16,18),(77,78,66),"OUCET")
>>> print(t1,type(t1))------------(10, 'Rossum', (17, 16, 18), (77, 78, 66), 'OUCET') <class 'tuple'>
>>> t1[0]----------------------------10
>>> t1[1]----------------------------'Rossum'
>>> t1[2]----------------------------(17, 16, 18)
>>> t1[3]----------------------------(77, 78, 66)
>>> t1[2][1]------------------------16
101
>>> t1[-2][-1]----------------------66
============================================================================
Possibility 1: List in Tuple
============================================================================
=>Syntax: tplobj=(Val1,Val2......[Val11,Val12....Val-1n], [Val21,Val22,...Val-2n],....Val-n)

=>Here (Val1,Val2......,....Val-n) is called Outer tuple Eleemnts


=>Here [Val11,Val12....Val-1n] is called Inner list Elements
=>Here [Val21,Val22,...Val-2n] is also another Inner list Elements.
---------------------------------------
Examples
---------------------------------------
>>> t1=(10,"Rossum",[17,16,18],[77,78,66],"OUCET")
>>> print(t1,type(t1))---------------(10, 'Rossum', [17, 16, 18], [77, 78, 66], 'OUCET') <class 'tuple'>
>>> print(t1[2],type(t1[2]))-----------[17, 16, 18] <class 'list'>
>>> print(t1[3],type(t1[3]))-----------[77, 78, 66] <class 'list'>
>>> t1[2].sort()
>>> print(t1,type(t1))------------------(10, 'Rossum', [16, 17, 18], [77, 78, 66], 'OUCET') <class 'tuple'>
>>> t1[3].sort(reverse=True)
>>> print(t1,type(t1))------------------(10, 'Rossum', [16, 17, 18], [78, 77, 66], 'OUCET') <class 'tuple'>
==============================================================================
Possibility 2: tuple in list
============================================================================
=>Syntax: listobj=[Val1,Val2......(Val11,Val12....Val-1n), (Val21,Val22,...Val-2n),....Val-n]

=>Here [Val1,Val2......,....Val-n] is called Outer list Eleemnts


=>Here (Val11,Val12....Val-1n]) is called Inner tuple Elements
=>Here (Val21,Val22,...Val-2n) is also another Inner tuple Elements.
---------------------------------------
Examples
---------------------------------------
>>> l1=[10,"Rossum",(17,16,18),(77,78,66),"OUCET"]
>>> print(l1,type(l1))-----------------[10, 'Rossum', (17, 16, 18), (77, 78, 66), 'OUCET'] <class 'list'>
102
>>> l1[1]---------------------------------'Rossum'
>>> print(l1[2],type(l1[2]))---------(17, 16, 18) <class 'tuple'>
>>> print(l1[3],type(l1[3]))---------(77, 78, 66) <class 'tuple'>
==================================x============================================
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)
=====================================================
Set Category Data Types
=====================================================
=>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 Elements Only (Duplicates are not allowed)".
=>We have 2 Data Types in Set Category. They are
1. set ( Mutable and Immutable)
2. frozenset ( Immutable )
=========================================================
set
=========================================================
Index
--------------------
=>Properties of set
=>What is set
=>Notations of set
=>Types of sets
=>Operations on sets
=>Pre-defined Functions in sets
=>Nested OR Inner sets
=>Combination set with tuples with list
=>Programming Examples
============================================================================
103
=>'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 Elements Only (Duplicates are not allowed)".
=>The values of set must stored within Curly Braces { } and Values must be separated by comma.
Syntax: setobj={Val1,Val2,.....,Val-n}
=>Set Object never maintains Insertion Order bcoz PVM Displays any of the Possiblity of the elements of set.
=>On the Object of set, we can't perform Indexing and Slicing Operations bcoz set never mainatins Insertion
order.
=>An object of set belongs to Both Mutable bcoz doing changes at Same Address and Immutable bcoz It never
allows us to perform item assignment
=>In Python Programming, 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 contains any Elements and whose length is 0
=>Syntax: setobj=set()
-------------------------
b) Non-Empty-Set
--------------------------
=>A Non-Empty-Set is one which contains Elements and whose length is >0
=>Syntax: setobj={Val1,Val2,.....,val-n}
OR
setobj=set(object)

*****************************************************************************************
Examples
******************************************************************************************
>>> s1={10,20,30,40,50,10,20}
>>> print(s1,type(s1))--------------{50, 20, 40, 10, 30} <class 'set'>
>>> s2={"Python","HTML","CSS",23,45.78,True}
>>> print(s2,type(s2))---------{'CSS', True, 'HTML', 23, 45.78, 'Python'} <class 'set'>
104
------------------------------
>>> s2={"Python","HTML","CSS",23,45.78,True}
>>> print(s2,type(s2))------------{'CSS', True, 'HTML', 23, 45.78, 'Python'} <class 'set'>
>>> s2[0]-----------------------------TypeError: 'set' object is not subscriptable
>>> s2[0:4]--------------------------TypeError: 'set' object is not subscriptable
-----------------------------------
>>> s1={10,"RS",34.56,True}
>>> print(s1,type(s1),id(s1))----------{True, 10, 'RS', 34.56} <class 'set'> 1796075992480
>>> s1[0]=False---------------------------TypeError: 'set' object does not support item assignment--Immutable
>>> s1.add(2+3j)
>>> print(s1,type(s1),id(s1))-----------{True, 'RS', 34.56, 10, (2+3j)} <class 'set'> 1796075992480--Mutable
--------------------------------------
>>> s1=set()
>>> print(s1,type(s1))-----------------set() <class 'set'>
>>> len(s1)-------------------------------0
>>> s2={10,20,30,40,20}
>>> print(s2,type(s2))---------------{40, 10, 20, 30} <class 'set'>
>>> len(s2)-----------------------------4
----------------------------------------
>>> lst1=[10,20,30,10,20,10]
>>> print(lst1,type(lst1))-----------------[10, 20, 30, 10, 20, 10] <class 'list'>
>>> s1=set(lst1)
>>> print(s1,type(s1))--------------------{10, 20, 30} <class 'set'>
>>> s="MISSISSIPPI"
>>> print(s,type(s))-----------------------MISSISSIPPI <class 'str'>
>>> s1=set(s)
>>> print(s1,type(s1))--------------------{'I', 'P', 'M', 'S'} <class 'set'>
=========================================================
Pre-defined Functions in sets
=========================================================
=>We know that on the object of set, we can't perform Indexing and slicing Operations bcoz set never maintains
Insertion Order.

105
=>But On set objects we can perform different operations by using Pre-Defined Functions which are present in
set object. They ate
******************************************************************************
1. add()
******************************************************************************
=>Syntax: setobj.add(Value)
=>This Function is used adding the value to set object.
----------------
Examples
----------------
>>> s1={10,"Rossum",34.56}
>>> print(s1,type(s1),id(s1))-----------{10, 'Rossum', 34.56} <class 'set'> 1796075985760
>>> s1.add("Python")
>>> print(s1,type(s1),id(s1))------------{10, 'Rossum', 34.56, 'Python'} <class 'set'> 1796075985760
>>> s1.add(34.67)
>>> print(s1,type(s1),id(s1))-----------{34.56, 34.67, 10, 'Python', 'Rossum'} <class 'set'> 1796075985760

>>> s1=set()
>>> print(s1,type(s1),id(s1))-----------set() <class 'set'> 1796075990240
>>> s1.add(100)
>>> s1.add("Travis")
>>> s1.add(True)
>>> s1.add(34.67)
>>> print(s1,type(s1),id(s1))------------{True, 34.67, 100, 'Travis'} <class 'set'> 1796075990240
*************************************************************************************
2) remove()
*************************************************************************************
Syntax: setobj.remove(value)
=>This Function is used for Removing the Value from set object
=>If the value does not exist in set object and if try to remove then we get KeyError
---------------------------
Examples
---------------------------
106
>>> s1={10,"RS",34.56,True,2+3j}
>>> print(s1,type(s1),id(s1))-----------{True, 34.56, 'RS', 10, (2+3j)} <class 'set'> 2000798133472
>>> s1.remove(10)
>>> print(s1,type(s1),id(s1))-----------{True, 34.56, 'RS', (2+3j)} <class 'set'> 2000798133472
>>> s1.remove(34.56)
>>> print(s1,type(s1),id(s1))----------{True, 'RS', (2+3j)} <class 'set'> 2000798133472
>>> s1.remove(100)----------------------KeyError: 100
-------------------------------
>>> s=set()
>>> s.remove(100)-------------KeyError: 100
>>> set().remove(12.34)------KeyError: 12.34
******************************************************************************************
3) discard()
******************************************************************************************
Syntax: setobj.discard(Value)
=>This Function is used for Removing the Value from set object
=>If the value does not exist in set object and if try to discard then we never get KeyError
---------------------
Examples
--------------------
>>> s1={10,"RS",34.56,True,2+3j}
>>> print(s1,type(s1),id(s1))---------{True, 34.56, 'RS', 10, (2+3j)} <class 'set'> 2000798135712
>>> s1.discard(10)
>>> print(s1,type(s1),id(s1))---------{True, 34.56, 'RS', (2+3j)} <class 'set'> 2000798135712
>>> s1.discard(34.56)
>>> print(s1,type(s1),id(s1))---------{True, 'RS', (2+3j)} <class 'set'> 2000798135712
>>> s1.discard(100)-----------No KeyError will come
>>> s1.remove(100)-----------KeyError: 100
----------------------------
>>> set().discard(100)
OR
>>> print(set().discard(100))-----------None
>>> set().remove(100)-------------------KeyError: 100
107
**************************************************************************************
4) pop()
*************************************************************************************
=>Syntax: setobj.pop()
=>This Function is used for Removing any ARBITRARY ELEMENT from set Object Provided NO ORDER OF
DISPLAY
=>This Function is used for Removing always FIRST ELEMENT from set Object Provided ORDER OF
DISPLAY is shown
---------------------------
Examples
---------------------------
>>> s1={10,"RS",34.56,True,2+3j} # NO Order of Display
>>> s1.pop()------------True
>>> s1.pop()------------34.56
>>> s1.pop()------------'RS'
>>> s1.pop()------------10
>>> s1.pop()------------(2+3j)
>>> s1.pop()------------KeyError: 'pop from an empty set'
>>> set().pop()---------KeyError: 'pop from an empty set'
--------------------------------
>>> s2={10,20,30,40,50,50,60,70}
>>> print(s2,type(s2),id(s2))----{50, 20, 70, 40, 10, 60, 30} <class 'set'> 2000798135712----Order of Display
>>> s2.pop()------------50
>>> print(s2,type(s2),id(s2))----{20, 70, 40, 10, 60, 30} <class 'set'> 2000798135712
>>> s2.pop()-------20
>>> print(s2,type(s2),id(s2))----{70, 40, 10, 60, 30} <class 'set'> 2000798135712
>>> s2.pop()----70
>>> s2.pop()----40
>>> s2.pop()-----10
******************************************************************************************
5) clear()
******************************************************************************************
=>Syntax: setobj.clear()
108
=>This function is used for Removing all the Elements from non-empty set object.
=>If we call this Function empty set object then we get none as a result
-------------------------
Examples
-------------------------
>>> s1={10,"RS",34.56,True,2+3j}
>>> print(s1,type(s1),id(s1))-----------{True, 34.56, 'RS', 10, (2+3j)} <class 'set'> 2000798128992
>>> len(s1)---------------5
>>> print(s1,type(s1),id(s1))-----------set() <class 'set'> 2000798128992
>>> len(s1)--------------------------------0
>>> print(s1.clear())--------------------None
>>> print(set().clear())-----------------None
***************************************************************************************
6) isdisjoint()
***************************************************************************************
=>Syntax: setobj1.isdisjoint(setobj2)
=>This Function returns True provided There is no common element present in setobj1 and setobj2(called Disjoint
Sets)
=>This Function returns False provided There is atleast one common element present in setobj1 and setobj2(called
Non-Disjoint Sets)
-----------------------
Examples
-----------------------
>>> s1={10,20,30,40}
>>> s2={15,25,35}
>>> s3={15,10,56}
>>> s1.isdisjoint(s2)----------True
>>> s1.isdisjoint(s3)----------False
>>> s2.isdisjoint(s3)----------False
>>> s2.isdisjoint(s1)----------True
--------------------------------
>>> s1=set()
>>> s2=set()
109
>>> s1.isdisjoint(s2)----------True
>>> set().isdisjoint(set())-----True
>>> set().isdisjoint({10,20,30})---True
***************************************************************************************
7) issuperset()
***************************************************************************************
=>Syntax: setobj1.issuperset(setobj2)
=>This Function returns True provided setobj1 contains all the elements of setobj2 Otherwise It returns False.
----------------
Examples
----------------
>>> s1={10,20,30,40}
>>> s2={10,20}
>>> print(s1,type(s1))----------{40, 10, 20, 30} <class 'set'>
>>> print(s2,type(s2))----------{10, 20} <class 'set'>
>>> s1.issuperset(s2)---------True
>>> s2.issuperset(s1)---------False
------------------------
>>> s1={10,20,30,40}
>>> s2={10,20,35,45}
>>> s1.issuperset(s2)------False
>>> set().issuperset(set())---True
>>> set().issubset({10,20,30})---True
*****************************************************************************************
8) issubset()
*****************************************************************************************
Syntax: setobj1.issubset(setobj2)
=>This Function returns True provided all the Elements of setobj1 are present in setobj2. Otherwise It returns
False.
----------------------
Examples
----------------------
>>> s1={10,20,30,40}
110
>>> s2={10,20,30,40,50,60,70}
>>> print(s1)----------{40, 10, 20, 30}
>>> print(s2)----------{50, 20, 70, 40, 10, 60, 30}
>>> s1.issubset(s2)----True
>>> s3={10,20,35,45,67}
>>> s1.issubset(s3)-------False
>>> s2.issubset(s1)-------False
>>> set().issubset(set())----True
>>> {10,20,30,40}.issubset(set())----False
***************************************************************************
9) union():
****************************************************************************
Syntax: setobj3=setobj1.union(setobj2)
=>This Function is used for Obtaining Unique Values of setobj1 and setobj2 and Place them in setobj3.
----------------------
Examples
----------------------
>>> s1={10,20,30,40}
>>> s2={10,20,25,35}
>>> print(s1,type(s1))----------{40, 10, 20, 30} <class 'set'>
>>> print(s2,type(s2))----------{25, 10, 35, 20} <class 'set'>
>>> s3=s1.union(s2)
>>> print(s3,type(s3))-----------{35, 40, 10, 20, 25, 30} <class 'set'>
---------------------
>>> x={"Python","HTML","Django"}
>>> y={"CSS","RestAPI","MySQL"}
>>> z=x.union(y)
>>> print(z,type(z))------{'CSS', 'Django', 'RestAPI', 'Python', 'HTML', 'MySQL'} <class 'set'>
--------------------------
>>> s1={10,20,30,40}
>>> s2={10,20,25,35}
>>> s3={1,2,"Python"}
>>> s4=s1.union(s2,s3)

111
>>> print(s4,type(s4))-----------{1, 2, 35, 40, 10, 20, 25, 'Python', 30} <class 'set'>
>>>
***************************************************************************************
10) intersection():
************************************************************************************
Syntax: setobj3=setobj1.intersection(setobj2)
=>This Function is used for Obtaining Common Elements from Both Setobj1 and setobj2
------------------------
Examples
------------------------
>>> s1={10,20,30,40}
>>> s2={10,20,25,35}
>>> print(s1,type(s1))----------{40, 10, 20, 30} <class 'set'>
>>> print(s2,type(s2))----------{25, 10, 35, 20} <class 'set'>
>>> s3=s1.intersection(s2)
>>> print(s3,type(s3))--------{10, 20} <class 'set'>
---------------------------
>>> x={"Python","HTML","Django"}
>>> y={"CSS","RestAPI","MySQL"}
>>> z=x.intersection(y)
>>> print(z,type(z))------------set() <class 'set'>
-----------------------------
>>> s1={10,20,30,40}
>>> s2={10,20,25,35}
>>> s3={1,2,"Python"}
>>> s4=s1.intersection(s2,s3)
>>> print(s4,type(s4))--------set() <class 'set'>
***************************************************************************************
11) difference():
*****************************************************************************************
=>Syntax: setobj3=setobj1.difference(setobj2)
=>This Function Removes the Common Elements from Both setobj1 and setobj2 and Takes Remaining Elements
from Setobj1 and place them in setobj3.
112
--------------------
Examples
--------------------
>>> s1={10,20,30,40}
>>> s2={10,20,25,35}
>>> print(s1,type(s1))----------{40, 10, 20, 30} <class 'set'>
>>> print(s2,type(s2))----------{25, 10, 35, 20} <class 'set'
>>>> s3=s1.difference(s2)
>>> print(s3,type(s3))--------{40, 30} <class 'set'>
>>> s4=s2.difference(s1)
>>> print(s4,type(s4))---------{25, 35} <class 'set'>
-----------------
>>> x={"Python","HTML","Django"}
>>> y={"CSS","RestAPI","MySQL"}
>>> z=x.difference(y)
>>> print(z,type(z))----------------{'Python', 'HTML', 'Django'} <class 'set'>
>>> z=y.difference(x)
>>> print(z,type(z))----------------{'RestAPI', 'MySQL', 'CSS'} <class 'set'>
-----------------------------
>>> k={10,20,30}
>>> v={10,20,30}
>>> r=k.difference(v)
>>> print(r,type(r))--------------set() <class 'set'>
*****************************************************************************************
12) symmetric_difference()----------In Maths , we call this Operation as Delta
*************************************************************************************
Syntax: setobj3=setobj1.symmetric_difference(setobj2)
=>This Function Removes the Common Elements from Both setobj1 and setobj2 and Takes Remaining Elements
from Setobj1 and setobj2 and place them in setobj3.
OR
Syntax: setobj3=setobj1.union(setobj2).difference(setobj1.intersection(setobj2))
--------------------
Examples

113
--------------------
>>> s1={10,20,30,40}
>>> s2={10,20,25,35}
>>> print(s1,type(s1))----------{40, 10, 20, 30} <class 'set'>
>>> print(s2,type(s2))----------{25, 10, 35, 20} <class 'set'
>>> s3=s1.symmetric_difference(s2)
>>> print(s3,type(s3))--------------{35, 40, 25, 30} <class 'set'>
----------------------------
>>> x={"Python","HTML","Django"}
>>> y={"CSS","RestAPI","MySQL"}
>>> z=x.symmetric_difference(y)
>>> print(z,type(z))-----------{'Django', 'CSS', 'HTML', 'RestAPI', 'Python', 'MySQL'} <class 'set'>
>>> k={10,20,30}
>>> v={10,20,30}
>>> r=k.symmetric_difference(v)
>>> print(r,type(r))------------set() <class 'set'>
-----------By Formula-------------
>>> s1={10,20,30,40}
>>> s2={10,20,25,35}
>>> s3=(s1.union(s2)).difference(s1.intersection(s2))
>>> print(s3,type(s3))------------{40, 25, 35, 30} <class 'set'>
******************************************************************************************
13) symmetric_difference_update():
******************************************************************************************
=>Syntax: setobj1.symmetric_difference_update(setobj2)
=>This Function Removes the Common Elements from Both setobj1 and setobj2 and Takes Remaining Elements
from Setobj1 and setobj2 and place them in setobj1 itself.
------------------
Examples
------------------
>>> s1={10,20,30,40}
>>> s2={10,20,25,35}
>>> s1.symmetric_difference_update(s2)

114
>>> print(s1,type(s1))---------{35, 40, 25, 30} <class 'set'>
******************************************************************************************
14) update():
*****************************************************************************************
Syntax: setobj1.update(setobj2)
=>This Function is used for Adding OR Merging of setobj2 Elements with setobj1
-----------------------
Examples
-----------------------
>>> s1={10,20,30,40}
>>> s2={10,20,25,35}
>>> s3=s1.update(s2)
>>> print(s1,type(s1))-----------{35, 40, 10, 20, 25, 30} <class 'set'>
>>> print(s3,type(s3))-----------None <class 'NoneType'>
-------------------------------------
>>> x={10,20}
>>> y={10,20}
>>> x.update(y)
>>> print(x,type(x))-----------{10, 20} <class 'set'>
==============================================================================
NOTE: del operator
----------------------------
>>> s1={10,20,30,40,50,60,70}
>>> print(s1,type(s1))---------{50, 20, 70, 40, 10, 60, 30} <class 'set'>
>>> del s1[1:4]------------------TypeError: 'set' object does not support item deletion
>>> del s1[0]--------------------TypeError: 'set' object doesn't support item deletion
>>> del s1 # Possible

115
=============================================================
Solve the Following Problem By using Sets with Set Functions
=============================================================
Consider the following
Set Cricket Players={"Rohit","Kohli","Rossum"}
Set Tennis Players={"Travis","Kinney","Rossum"}
Write the Code for the following
a) Find the names of all the players who are playing all types of Games
b) Find the names of the players who are playing Both Cricket and Tennis
c) Find the names of the players who are playing Only Cricket But not Tennis
d) Find the names of the players who are playing Only Tennis But not Cricket
e) Find the names of the players who are Exclusively playing Cricket and Tennis
==============================================
Solutions
==============================================
a) Find the names of all the players who are playing all types of Games--------union()
ANS:-
>>> cp={"Rohit","Kohli","Rossum"}
>>> tp={"Travis","Kinney","Rossum"}

116
>>> print(cp,type(cp))----------{'Rossum', 'Kohli', 'Rohit'} <class 'set'>
>>> print(tp,type(tp))------------{'Kinney', 'Travis', 'Rossum'} <class 'set'>
>>> allcptp=cp.union(tp)
>>> print(allcptp,type(allcptp))-----{'Kinney', 'Rossum', 'Rohit', 'Travis', 'Kohli'} <class 'set'>
==============================================
b) Find the names of the players who are playing Both Cricket and Tennis--intersection()
ANS:-
>>> cp={"Rohit","Kohli","Rossum"}
>>> tp={"Travis","Kinney","Rossum"}
>>> print(cp,type(cp))----------{'Rossum', 'Kohli', 'Rohit'} <class 'set'>
>>> print(tp,type(tp))------------{'Kinney', 'Travis', 'Rossum'} <class 'set'>
>>> bothcptp=cp.intersection(tp)
>>> print(bothcptp,type(bothcptp))-----------{'Rossum'} <class 'set'>
==============================================
c) Find the names of the players who are playing Only Cricket But not Tennis---difference()
ANS:-
>>> cp={"Rohit","Kohli","Rossum"}
>>> tp={"Travis","Kinney","Rossum"}
>>> print(cp,type(cp))----------{'Rossum', 'Kohli', 'Rohit'} <class 'set'>
>>> print(tp,type(tp))------------{'Kinney', 'Travis', 'Rossum'} <class 'set'>
>>> onlycp=cp.difference(tp)
>>> print(onlycp,type(onlycp))-----------{'Kohli', 'Rohit'} <class 'set'>

d) Find the names of the players who are playing Only Tennis But not Cricket---difference()
ANS:-
>>> cp={"Rohit","Kohli","Rossum"}
>>> tp={"Travis","Kinney","Rossum"}
>>> print(cp,type(cp))----------{'Rossum', 'Kohli', 'Rohit'} <class 'set'>
>>> print(tp,type(tp))------------{'Kinney', 'Travis', 'Rossum'} <class 'set'>
>>> onlycp=cp.difference(tp)
>>> print(onlycp,type(onlycp))-----------{'Kohli', 'Rohit'} <class 'set'>
>>> onlytp=tp.difference(cp)
>>> print(onlytp,type(onlytp))-----------{'Kinney', 'Travis'} <class 'set'>
==============================================
117
e) Find the names of the players who are Exclusively playing Cricket and Tennis--
symmetric_difference()
ANS:-
>>> cp={"Rohit","Kohli","Rossum"}
>>> tp={"Travis","Kinney","Rossum"}
>>> print(cp,type(cp))----------{'Rossum', 'Kohli', 'Rohit'} <class 'set'>
>>> print(tp,type(tp))------------{'Kinney', 'Travis', 'Rossum'} <class 'set'>
>>> exclcptp=cp.symmetric_difference(tp)
>>> print(exclcptp,type(exclcptp))---------{'Kinney', 'Travis', 'Kohli', 'Rohit'} <class 'set'>
===============================================================================
===================================================================
Solve the Following Problem By using Sets without using set Functions
Here we are solving the following Problem with BITWISE OPERATORS
===================================================================
Consider the following
Set Cricket Players={"Rohit","Kohli","Rossum"}
Set Tennis Players={"Travis","Kinney","Rossum"}
Write the Code for the following
a) Find the names of all the players who are playing all types of Games
b) Find the names of the players who are playing Both Cricket and Tennis
c) Find the names of the players who are playing Only Cricket But not Tennis
d) Find the names of the players who are playing Only Tennis But not Cricket
e) Find the names of the players who are Exclusively playing Cricket and Tennis

==============================================
Solutions
==============================================
a) Find the names of all the players who are playing all types of Games--------union() OR
Bitwise OR ( | )
ANS:-
>>> cp={"Rohit","Kohli","Rossum"}
>>> tp={"Travis","Kinney","Rossum"}
>>> print(cp,type(cp))----------{'Rossum', 'Kohli', 'Rohit'} <class 'set'>
118
>>> print(tp,type(tp))------------{'Kinney', 'Travis', 'Rossum'} <class 'set'>
>>> allcptp=cp|tp # Bitwise OR ( | )
>>> print(allcptp,type(allcptp))-----{'Kinney', 'Rossum', 'Rohit', 'Travis', 'Kohli'} <class 'set'>
==============================================
b) Find the names of the players who are playing Both Cricket and Tennis--intersection()
OR Bitwise AND ( & )
ANS:-
>>> cp={"Rohit","Kohli","Rossum"}
>>> tp={"Travis","Kinney","Rossum"}
>>> print(cp,type(cp))----------{'Rossum', 'Kohli', 'Rohit'} <class 'set'>
>>> print(tp,type(tp))------------{'Kinney', 'Travis', 'Rossum'} <class 'set'>
>>> bothcptp=cp&tp # Bitwise AND ( & )
>>> print(bothcptp,type(bothcptp))-----------{'Rossum'} <class 'set'>
==============================================
c) Find the names of the players who are playing Only Cricket But not Tennis---difference()
OR Arithmetic Minus ( - )
ANS:-
>>> cp={"Rohit","Kohli","Rossum"}
>>> tp={"Travis","Kinney","Rossum"}
>>> print(cp,type(cp))----------{'Rossum', 'Kohli', 'Rohit'} <class 'set'>
>>> print(tp,type(tp))------------{'Kinney', 'Travis', 'Rossum'} <class 'set'>
>>> onlycp=cp-tp # Arithmetic Minus ( - )
>>> print(onlycp,type(onlycp))-----------{'Kohli', 'Rohit'} <class 'set'>
==============================================
d) Find the names of the players who are playing Only Tennis But not Cricket---difference()
OR Arithmetic Minus ( - )
ANS:-
>>> cp={"Rohit","Kohli","Rossum"}
>>> tp={"Travis","Kinney","Rossum"}
>>> print(cp,type(cp))----------{'Rossum', 'Kohli', 'Rohit'} <class 'set'>
>>> print(tp,type(tp))------------{'Kinney', 'Travis', 'Rossum'} <class 'set'>
>>> onlycp=cp.difference(tp)

119
>>> print(onlycp,type(onlycp))-----------{'Kohli', 'Rohit'} <class 'set'>
>>> onlytp=tp-cp # Arithmetic Minus ( - )
>>> print(onlytp,type(onlytp))-----------{'Kinney', 'Travis'} <class 'set'>
==============================================
e) Find the names of the players who are Exclusively playing Cricket and Tennis --
symmetric_difference() OR Bitwise XOR ( ^ )
ANS:-
>>> cp={"Rohit","Kohli","Rossum"}
>>> tp={"Travis","Kinney","Rossum"}
>>> print(cp,type(cp))----------{'Rossum', 'Kohli', 'Rohit'} <class 'set'>
>>> print(tp,type(tp))------------{'Kinney', 'Travis', 'Rossum'} <class 'set'>
>>> exclcptp=cp^tp # Bitwise XOR ( ^ )
>>> print(exclcptp,type(exclcptp))---------{'Kinney', 'Travis', 'Kohli', 'Rohit'} <class 'set'>
================================================
Combination set with set,list and tuple
OR
Nested OR Inner Sets
================================================
Case-1 : It is Not Possible to Define One Set in Another Set bcoz sets are unhashable type(Not Possible
to apply Indexing + Not Possible to Modify)
--------------------------------------------------------------------------------------------------------------------------------
Examples:
----------------
>>> s1={10,"Rossum",{16,19,18},{77,76,75},"OUCET"}---------TypeError: unhashable type: 'set'
--------------------------------------------------------------------------------------------------------------------------------
Case-2: It is Not Possible to Define One List in Another Set bcoz sets are unhashable type(Not Possible
to apply Indexing + Not Possible to Modify)
----------------
Examples
----------------
>>> s1={10,"Rossum",[16,19,18],[77,76,75],"OUCET"}-----------TypeError: unhashable type: 'list'
--------------------------------------------------------------------------------------------------------------------------------
Case-3: It is Possible to Define One Tuple in Another Set bcoz tuples are Immutable
----------------------------
120
Examples
----------------------------
>>> s1={10,"Rossum",(16,19,18),(77,76,75),"OUCET"}
>>> print(s1,type(s1))-------{(77, 76, 75), (16, 19, 18), 'OUCET', 'Rossum', 10} <class 'set'>
>>> for val in s1:
... print(val,type(val))
...
(77, 76, 75) <class 'tuple'>
(16, 19, 18) <class 'tuple'>
OUCET <class 'str'>
Rossum <class 'str'>
10 <class 'int'>
--------------------------------------------------------------------------------------------------------------------------------
Case-4: It is Possible to Define One Set in Another List bcoz Lists are mutable and allows us to locate set
objects by using Indices.
------------------------
Examples
------------------------
>>> lst=[10,"Rossum",{16,19,18},{77,76,75},"OUCET"]
>>> print(lst,type(lst))----------[10, 'Rossum', {16, 18, 19}, {75, 76, 77}, 'OUCET'] <class 'list'>
>>> print(lst[2],type(lst[2]))---------{16, 18, 19} <class 'set'>
>>> lst[2].add(15)
>>> print(lst)---------[10, 'Rossum', {16, 18, 19, 15}, {75, 76, 77}, 'OUCET']
>>> lst[-2].add(66)
>>> print(lst)--------[10, 'Rossum', {16, 18, 19, 15}, {66, 75, 76, 77}, 'OUCET']
--------------------------------------------------------------------------------------------------------------------------------
Case-5: It is Possible to Define One Set in Another tuple bcoz Tuples are Immutable and allows us to
locate set objects by using Indices.
------------------------
Examples
------------------------
>>> tpl=(10,"Rossum",{16,19,18},{77,76,75},"OUCET")
>>> print(tpl,type(tpl))-------------(10, 'Rossum', {16, 18, 19}, {75, 76, 77}, 'OUCET') <class 'tuple'>
121
>>> print(tpl[2],type(tpl[2]))---------{16, 18, 19} <class 'set'>
>>> tpl[2].add(15)
>>> print(tpl,type(tpl))--------(10, 'Rossum', {16, 18, 19, 15}, {75, 76, 77}, 'OUCET') <class 'tuple'>
>>> tpl[-2].remove(76)
>>> print(tpl,type(tpl))--------(10, 'Rossum', {16, 18, 19, 15}, {75, 77}, 'OUCET') <class 'tuple'>
==============================================
frozenset
===============================================
=>'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 Simiar Type or Different
Type or Both the Types in Single Object with Unique Values".
=>The elements of frozenset must be obtained from different objects like set , tuple and list..etc.
Syntax: frozensetobj=frozenset(set/list/tuple/str/bytes/bytearray/range)
=>An Object of frozenset never maintains Insertion Order bcoz PVM can display any one of the
possibility of elements of frozenset object.
=>On the object of frozenset, we can't perform Indexing and Slicing Operations bcoz frozenset object
never maintains Insertion Order.
=>An object of frozenset belongs to Immutable bcoz frozenset' object does not support item assignment and not
possible to modify / Change / add.
=>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: frozensetobj=frozenset()
--------------------------------------
b) Non-Empty frozenset:
-------------------------------------
=>A Non-Empty frozenset is one, which contains elements and whose length is >0
=>Syntax: frozensetobj=frozenset( { val1, val2, ....val-n } )
=>Syntax: frozensetobj=frozenset( ( val1, val2, ....val-n ) )
122
=>Syntax: frozensetobj=frozenset( [ val1, val2, ....val-n ] )
---------------------------------------------------------------------------------------------------------------------------------------
NOTE: The Functionality of frozenset is exactly similar to set But an object of set belongs to both
Mutable(add,remove, pop, discard...etc) and also Immutable in the case of Item assigment Whereas frozenset
object belongs to Immutable bcoz neither Possible to perform add,remove, pop, discard...etc nor possible to
perform Item assigment.
==============================================================================
Examples
===============================================================================
>>> s1={10,20,30,10,20,60,70}
>>> print(s1,type(s1))-----------------{20, 70, 10, 60, 30} <class 'set'>
>>> fs1=frozenset(l1)
>>> print(fs1,type(fs1))--------------frozenset({20, 70, 10, 60, 30}) <class 'frozenset'>
>>> s1={10,"RS",33.33,True}
>>> print(s1,type(s1))---------------{33.33, 10, True, 'RS'} <class 'set'>
>>> fs2=frozenset(s1)
>>> print(fs2,type(fs2))------------frozenset({33.33, 10, True, 'RS'}) <class 'frozenset'>
>>> len(fs2)---------------------------4
>>> fs3=frozenset()
>>> print(fs3,type(fs3))----------frozenset() <class 'frozenset'>
>>> len(fs3)-------------------------0
---------
>>> s1={10,"RS",33.33,True}
>>> print(s1,type(s1))-----------{33.33, 10, True, 'RS'} <class 'set'>
>>> fs2=frozenset(s1)
>>> print(fs2,type(fs2))---------frozenset({33.33, 10, True, 'RS'}) <class 'frozenset'>
>>> fs2[0]-------------------------TypeError: 'frozenset' object is not subscriptable
>>> fs2[0:3]----------------------TypeError: 'frozenset' object is not subscriptable
>>> fs2[0]=23--------------------TypeError: 'frozenset' object does not support item assignment
---------------------------
>>> del fs2[0]-------------------TypeError: 'frozenset' object doesn't support item deletion
>>> del fs2[0:2]-----------------TypeError: 'frozenset' object does not support item deletion
>>> del fs2 # Possible

123
>>>print(fs2)-----------------NameError: name 'fs2' is not found

=====================================
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() # Deep 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 Memory Address and Not at all possible to Modify / Change their content. Hence
the copy procedure of Frozenet is considered as Deep Copy Only.
=>frozenset does not contain the following Functions
a) clear()
b) add()
c) remove()
d) discard()
e) pop()
f) update()
h) symmertic_difference_update()

124
---------------------------------------------------------------------------------------------------
Examples:
----------------------------------------------------------------------------------------------------
>>> print(fs1,type(fs1),id(fs1))-------frozenset({50, 20, 70, 40, 10, 60, 30}) <class 'frozenset'> 1558323909504
>>> fs2=fs1.copy()
>>> print(fs2,type(fs2),id(fs2))------frozenset({50, 20, 70, 40, 10, 60, 30}) <class 'frozenset'> 1558323909504
>>> print(fs1)----------frozenset({50, 20, 70, 40, 10, 60, 30})
-------------------
>>> fs1=frozenset({10,20,30,40,50,60,70})
>>> fs2=frozenset((10,20,30))
>>> fs1.issuperset(fs2)---------True
>>> fs2.issuperset(fs1)--------False
>>> fs2.issubset(fs1)----------True
>>> fs1.issubset(fs2)------------False
-----------------------------
>>> fs1=frozenset({10,20,30,40,50,60,70})
>>> fs2=frozenset((100,200,300))
>>> fs3=frozenset((10,2,3))
>>> fs1.isdisjoint(fs2)---------True
>>> fs1.isdisjoint(fs3)----------False
>>> print(fs1)-------------frozenset({50, 20, 70, 40, 10, 60, 30})
>>> print(fs2)-----------frozenset({200, 100, 300})
>>> fs1.union(fs2)----------frozenset({100, 70, 40, 200, 10, 300, 50, 20, 60, 30})
>>> fs1.intersection(fs2)---------frozenset()
>>> fs1.difference(fs2)-----------frozenset({70, 40, 10, 50, 20, 60, 30})
>>> fs2.difference(fs1)--------------frozenset({200, 100, 300})
>>> frozenset({10,20,30,40}).symmetric_difference(frozenset([10,20,50,60]) )
frozenset({40, 50, 60, 30})
>>> fs1|fs2--------------frozenset({100, 70, 40, 200, 10, 300, 50, 20, 60, 30})

125
==========================================================
Dict Category Data Type
==========================================================
=>The data Type in Dict Category is 'dict'.
=>dict is one of the pre-defined class
=>The purpose of dict data type is that "To Store the Data in the form of (Key,Value) ".
=>In (Key,value), the Values of Key Represents unique and Values of Value Represents May or May not be
Unique.
=>To store (Key,value) in dict, we use curly braces and (Key,value) separated by comma.
=>Syntax: varname={Key1:Val1,Key2:Val2,........,Key-n:Val-n}
here Key1,Key2...Key-n Represents of Values of Key
Val1,Val2,....Val-n Represents of Values of Values
=>An objct of dict maintains Insertion Order
=>An object of dict never Contains Indices. So that we can't perform Both Index and Slicing Operations.
=>An object of dict belongs to MUTABLE. In detail, the values of Key belongs to IMMUTABLE and Values of
Value belongs to MUTABLE.
=>In Python Programming, we can create Two Types of Dict Objects. They are
a) Empty Dict
b) Non-Empty Dict
-----------------------------
a) Empty Dict
-----------------------------
=>An Empty Dict is one, which does not contain any Elements and whose length is 0
=>Syntax: dictobj={}
(OR)
dictobj=dict()
-----------------------------
b) Non-Empty Dict
-----------------------------
=>A Non-Empty Dict is one, which contains Elements and whose length is >0
=>Syntax: dictobj={Key1:Val1,Key2:Val2,........,Key-n:Val-n}

126
******************************************************************************************
=>Syntax Adding (Key,value) to Empty / Non-Empty Dict
******************************************************************************************
dictobj[Key1]=Val1
dictobj[Key2]=Val2
--------------------------
--------------------------
dictobj[Key-n]=Val-n
=>here Key1,Key2...Key-n Represents of Values of Key
Val1,Val2,....Val-n Represents of Values of Values
=================
Examples
==================
>>> d1={10:"Apple",20:"Mango",30:"Kiwi",40:"Sberry"}
>>> print(d1,type(d1))------------{10: 'Apple', 20: 'Mango', 30: 'Kiwi', 40: 'Sberry'} <class 'dict'>
>>> len(d1)----------4
>>> d2={"Python":1,"C":2,"Java":3,"C++":4}
>>> print(d2,type(d2))----------{'Python': 1, 'C': 2, 'Java': 3, 'C++': 4} <class 'dict'>
>>> len(d2)-------------------------4
>>> d3={100:1.2,200:1.3,300:1.2,400:1.3}
>>> print(d3,type(d3))---------{100: 1.2, 200: 1.3, 300: 1.2, 400: 1.3} <class 'dict'>
-------------------------------------------------
>>> d1={10:1.2,10:2.3,10:4.5,10:0.2}
>>> print(d1)------------{10: 0.2}
>>> d1={10: 1.2, 20: 2.3, 10: 1.9, 80 : 2.9}
>>> print(d1)--------{10: 1.9, 20: 2.3, 80: 2.9}
--------------------------------------------------
>>> d1={10:"Apple",20:"Mango",30:"Kiwi",40:"Sberry"}
>>> print(d1,type(d1))-----------{10: 'Apple', 20: 'Mango', 30: 'Kiwi', 40: 'Sberry'} <class 'dict'>
>>> d1[0]---------KeyError: 0
>>> d1[10]--------'Apple'
>>> d1[20]--------'Mango'
>>> d1[30]--------'Kiwi'
127
>>> d1[40]---------'Sberry'
>>> d1[50]--------KeyError: 50
-----------------------------------------------
>>> d1={10:"Apple",20:"Mango",30:"Kiwi",40:"Sberry"}
>>> print(d1,type(d1),id(d1))-----{10: 'Apple', 20: 'Mango', 30: 'Kiwi', 40: 'Sberry'} <class 'dict'> 1978790674944
>>> d1[10]="Guava"
>>> print(d1,type(d1),id(d1))------{10: 'Guava', 20: 'Mango', 30: 'Kiwi', 40: 'Sberry'} <class 'dict'>
1978790674944
----------------------------------------------------------
>>> d1={}
>>> print(d1,type(d1))-----------{} <class 'dict'>
>>> len(d1)------------------------0
OR
>>> d2=dict()
>>> print(d2,type(d2))---------{} <class 'dict'>
>>> len(d2)-----------------------0
----------------------------------------------------------
>>> d1={}
>>> print(d1,type(d1),id(d1))-------------{} <class 'dict'> 1978790785984
>>> len(d1)--------------------0
>>> d1[100]=1.2 # Inserted Entry
>>> d1[200]=2.2 # Inserted Entry
>>> d1[300]=1.2 # Inserted Entry
>>> d1[400]=4.2 # Inserted Entry
>>> print(d1,type(d1),id(d1))----{100: 1.2, 200: 2.2, 300: 1.2, 400: 4.2} <class 'dict'> 1978790785984
>>> len(d1)-------------------4
>>> d1[500]=5.5 # Inserted Entry
>>> print(d1,type(d1),id(d1))-----{100: 1.2, 200: 2.2, 300: 1.2, 400: 4.2, 500: 5.5} <class 'dict'> 1978790785984
>>> d1[300]=0.2 # Modified Entry bcoz the key 300 already exist in d1
>>> print(d1,type(d1),id(d1))---{100: 1.2, 200: 2.2, 300: 0.2, 400: 4.2, 500: 5.5} <class 'dict'> 1978790785984

128
================================================
Pre-Defined Functions in dict
================================================
=>We know that on dict object, we learned How to Insert the (Key,value) and How Modify the value of Value
by passing Value of Key.Along with these Operations, we can also Perform different Operations by using Pre-
defined Function of dict object.
****************************************************************************************
1) clear()
****************************************************************************************
=>Syntax: dictobj.clear()
=>This Function is used for Removing all the (Key,Value) from dict object
=>When we call this Function w.r.t empty dict then we get None as Result
-----------------
Examples
-----------------
>>> d1={10:1.2,20:3.4,30:1.2,40:4.5,50:3.4}
>>> print(d1,type(d1),id(d1))-------{10: 1.2, 20: 3.4, 30: 1.2, 40: 4.5, 50: 3.4} <class 'dict'> 3078526298944
>>> len(d1)---------------------------5
>>> d1.clear()
>>> print(d1,type(d1),id(d1))--------{} <class 'dict'> 3078526298944
>>> len(d1)----------------------0
>>> print(d1.clear())----------None
>>> print({}.clear())-----------None
>>>print(dict().clear())—None
****************************************************************************************
2) pop()
********************************************************************************
Syntax: dictobj.pop(Key)
=>This Function is used for Removing (Key,Value) from Non-empty Dict Object
=>If the Value of Key does not Exist then we get KeyError
--------------------
Examples

129
>>> d1={10:1.2,20:3.4,30:1.2,40:4.5,50:3.4}
>>> print(d1,type(d1),id(d1))-----------{10: 1.2, 20: 3.4, 30: 1.2, 40: 4.5, 50: 3.4} <class 'dict'> 3078526259136
>>> d1.pop(30)--------------1.2
>>> print(d1,type(d1),id(d1))--------{10: 1.2, 20: 3.4, 40: 4.5, 50: 3.4} <class 'dict'> 3078526259136
>>> d1.pop(20)------------3.4
>>> print(d1,type(d1),id(d1))-----{10: 1.2, 40: 4.5, 50: 3.4} <class 'dict'> 3078526259136
>>> d1.pop(50)------------3.4
>>> print(d1,type(d1),id(d1))-------{10: 1.2, 40: 4.5} <class 'dict'> 3078526259136
>>> d1.pop(120)-----------------------KeyError: 120
>>> {}.pop(10)------------------------KeyError: 10
>>> dict().pop(20)-------------------KeyError: 20
**********************************************************************************
3) popitem()
******************************************************************************************
Syntax: dictobj.popitem()
=>This Function is used for Removing Last (Key,value) from Non-empty dict object
=>When we call this function on empty dict object then we get KeyError.
-----------------
Examples
-----------------
>>> d1={10:1.2,20:3.4,30:1.2,40:4.5,50:3.4}
>>> print(d1,type(d1),id(d1))-----------{10: 1.2, 20: 3.4, 30: 1.2, 40: 4.5, 50: 3.4} <class 'dict'> 3078526259392
>>> d1.popitem()-----------------(50, 3.4)
>>> print(d1,type(d1),id(d1))-----------{10: 1.2, 20: 3.4, 30: 1.2, 40: 4.5} <class 'dict'> 3078526259392
>>> d1.popitem()--------------(40, 4.5)
>>> print(d1,type(d1),id(d1))---{10: 1.2, 20: 3.4, 30: 1.2} <class 'dict'> 3078526259392
>>> d1.popitem()---------(30, 1.2)
>>> print(d1,type(d1),id(d1))---------{10: 1.2, 20: 3.4} <class 'dict'> 3078526259392
>>> d1.popitem()-------------(20, 3.4)
>>> print(d1,type(d1),id(d1))------{10: 1.2} <class 'dict'> 3078526259392
>>> d1.popitem()---------------(10, 1.2)
>>> print(d1,type(d1),id(d1))------------{} <class 'dict'> 3078526259392
>>> d1.popitem()--------------KeyError: 'popitem(): dictionary is empty'

130
>>> {}.popitem()-----------------KeyError: 'popitem(): dictionary is empty'
>>> dict().popitem()------------KeyError: 'popitem(): dictionary is empty'
*****************************************************************************************
4) copy()
***************************************************************************************
Syntax: dictobj2=dictobj1.copy()
=>This Function is used for Copying the content of One Dict object to another dict object(Implementation of
Shallow Copy)
---------------------
Examples
---------------------
>>> d1={10:1.2,20:3.4,30:1.2}
>>> print(d1,type(d1),id(d1))---------------{10: 1.2, 20: 3.4, 30: 1.2} <class 'dict'> 3078527577088
>>> d2=d1.copy() # Shallow Copy
>>> print(d2,type(d2),id(d2))--------------{10: 1.2, 20: 3.4, 30: 1.2} <class 'dict'> 3078526259392
>>> d1[40]=4.5
>>> d2[25]=1.2
>>> print(d1,type(d1),id(d1))-----{10: 1.2, 20: 3.4, 30: 1.2, 40: 4.5} <class 'dict'> 3078527577088
>>> print(d2,type(d2),id(d2))-----{10: 1.2, 20: 3.4, 30: 1.2, 25: 1.2} <class 'dict'> 3078526259392
***************************************************************************************
5) get()--Most Imp
***************************************************************************************
=>Syntax: Varname=dictobj.get(Key)
=>This Function is used for Obtaining Value of Value by passing the value of Key
=>If the Value of Key does not exist then we get None as Result
OR
=>Syntax: dictobj[Key]
=>This Syntax also gives Value of Value by passing Value of Key
=>If the Value of Key does not exist then we get KeyError
----------------------------
Examples
----------------------------
>>> d1={10:1.2,20:3.4,30:1.2,40:4.5,50:3.4}
131
>>> print(d1,type(d1))-----------{10: 1.2, 20: 3.4, 30: 1.2, 40: 4.5, 50: 3.4} <class 'dict'>
>>> val=d1.get(10)
>>> print(val)--------1.2
>>> val=d1.get(20)
>>> print(val)--------3.4
>>> val=d1.get(100)
>>> print(val)---------None
>>> #-----------------OR----------------
>>> d1={10:1.2,20:3.4,30:1.2,40:4.5,50:3.4}
>>> print(d1,type(d1))-----------{10: 1.2, 20: 3.4, 30: 1.2, 40: 4.5, 50: 3.4} <class 'dict'>
>>> d1[10]------------------1.2
>>> d1[20]------------------3.4
>>> d1[100]----------------KeyError: 100
******************************************************************************************
6) keys()
******************************************************************************************
Syntax: varname=dictobj.keys()
=>This Function is used for Obtainng Values of Key and placed in varname and whose type <class,'dict_keys'>
-------------------
Examples
-------------------
>>> d1={10:"Python",20:"Django",30:"C++",40:"C"}
>>> print(d1,type(d1))-----------{10: 'Python', 20: 'Django', 30: 'C++', 40: 'C'} <class 'dict'>
>>> 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():

132
... print(k)
...
10
20
30
40
*****************************************************************************************
7) values()
***********************************************************************************
Syntax: varname=dictobj.values()
=>This Function is used for Obtainng Values of Value and placed in varname and whose type
<class,'dict_values'>
----------------
Examples
----------------
>>> d1={10:"Python",20:"Django",30:"C++",40:"C"}
>>> print(d1,type(d1))----------{10: 'Python', 20: 'Django', 30: 'C++', 40: 'C'} <class 'dict'>
>>> vs=d1.values()
>>> print(vs,type(vs))---------dict_values(['Python', 'Django', 'C++', 'C']) <class 'dict_values'>
>>> for v in vs:
... print(v)
...
Python
Django
C++
C
>>> for v in d1.values():
... print(v)
...
Python
Django
C++
C

133
******************************************************************************************
8) items()
**************************************************************************************
Syntax: varname=dictobj.items()
=>This Function is used for Obtainng (Key,value) from dict object and placed in varname and whose type
<class,'dict_items'>
-------------------------
Examples
-------------------------
>>> d1={10:"Python",20:"Django",30:"C++",40:"C"}
>>> print(d1,type(d1))--------{10: 'Python', 20: 'Django', 30: 'C++', 40: 'C'} <class 'dict'>
>>> dit=d1.items()
>>> print(dit,type(dit))---dict_items([(10, 'Python'), (20, 'Django'), (30, 'C++'), (40, 'C')]) <class 'dict_items'>
>>> for its in dit:
... print(its,type(its))
...
(10, 'Python') <class 'tuple'>
(20, 'Django') <class 'tuple'>
(30, 'C++') <class 'tuple'>
(40, 'C') <class 'tuple'>
>>> for kv in d1.items():
... print(kv,type(kv))
...
(10, 'Python') <class 'tuple'>
(20, 'Django') <class 'tuple'>
(30, 'C++') <class 'tuple'>
(40, 'C') <class 'tuple'>
>>>
>>> for k,v in d1.items():
... print(k,"--->",v)
...
10 ---> Python
20 ---> Django

134
30 ---> C++
40 --->

===========================================================================
Combination of dict with dict,set,tuple and list
===========================================================================
=============================================
Case1: dict in dict --Nested Dict Possible to Define
=============================================
Examples
------------------
>>>
d1={"sno":10,"sname":"RS","IntMarks":{"cm":17,"cpp":16,"os":19},"ExtMarks":{"cm":78,"cpp":77,"os":79},
"cname":"CUCET"}
>>> print(d1,type(d1))
{'sno': 10, 'sname': 'RS', 'IntMarks': {'cm': 17, 'cpp': 16, 'os': 19}, 'ExtMarks': {'cm': 78, 'cpp': 77, 'os': 79}, 'cname':
'CUCET'} <class 'dict'>
>>> for its in d1.items():
... print(its)
...
('sno', 10)
('sname', 'RS')
('IntMarks', {'cm': 17, 'cpp': 16, 'os': 19})
('ExtMarks', {'cm': 78, 'cpp': 77, 'os': 79})
('cname', 'CUCET')
>>> for k,v in d1.items():
... print(k,"--->",v)
...
sno ---> 10
sname ---> RS
IntMarks ---> {'cm': 17, 'cpp': 16, 'os': 19}
ExtMarks ---> {'cm': 78, 'cpp': 77, 'os': 79}
cname ---> CUCET
>>> for k,v in d1.items():
135
... print(k,"--->",v,"-->",type(v),type(d1))
...
sno ---> 10 --> <class 'int'> <class 'dict'>
sname ---> RS --> <class 'str'> <class 'dict'>
IntMarks ---> {'cm': 17, 'cpp': 16, 'os': 19} --> <class 'dict'> <class 'dict'>
ExtMarks ---> {'cm': 78, 'cpp': 77, 'os': 79} --> <class 'dict'> <class 'dict'>
cname ---> CUCET --> <class 'str'> <class 'dict'>
>>> d1["IntMarks"]------------------{'cm': 17, 'cpp': 16, 'os': 19}
>>> d1["IntMarks"]["DBMS"]=16
>>> d1["ExtMarks"]["DBMS"]=74
>>> print(d1,type(d1))
{'sno': 10, 'sname': 'RS', 'IntMarks': {'cm': 17, 'cpp': 16, 'os': 19, 'DBMS': 16}, 'ExtMarks':
{'cm': 78, 'cpp': 77, 'os': 79, 'DBMS': 74}, 'cname': 'CUCET'} <class 'dict'>
>>> d1["IntMarks"].pop("cm")-------17
>>> d1["ExtMarks"].pop("os")------79
>>> print(d1,type(d1))
{'sno': 10, 'sname': 'RS', 'IntMarks': {'cpp': 16, 'os': 19, 'DBMS': 16}, 'ExtMarks': {'cm': 78,
'cpp': 77, 'DBMS': 74}, 'cname': 'CUCET'} <class 'dict'>
-------------------
>>>
d1={"sno":100,"name":"RS","IntMarks":{"cm":17,"c++":16},"ExtMarks":{"cm":70,"c++":67},"cname":"OU"}
>>> print(d1,type(d1))
{'sno': 100, 'name': 'RS', 'IntMarks': {'cm': 17, 'c++': 16}, 'ExtMarks': {'cm': 70, 'c++': 67}, 'cname': 'OU'} <class
'dict'>
>>> for k in d1.keys():
... print(k)
...
sno
name
IntMarks
ExtMarks
cname
>>> for v in d1.values():

136
... print(v)
...
100
RS
{'cm': 17, 'c++': 16}
{'cm': 70, 'c++': 67}
OU
>>> for it in d1.items():
... print(it)
...
('sno', 100)
('name', 'RS')
('IntMarks', {'cm': 17, 'c++': 16})
('ExtMarks', {'cm': 70, 'c++': 67})
('cname', 'OU')
>>> for gudu,sahu in d1.items():
... print(gudu,"--->",sahu)
...
sno ---> 100
name ---> RS
IntMarks ---> {'cm': 17, 'c++': 16}
ExtMarks ---> {'cm': 70, 'c++': 67}
cname ---> OU
>>> for gudu,sahu in d1.items():
... print(gudu,"--->",sahu,"--->",type(sahu),"--->",type(d1))
...
sno ---> 100 ---> <class 'int'> ---> <class 'dict'>
name ---> RS ---> <class 'str'> ---> <class 'dict'>
IntMarks ---> {'cm': 17, 'c++': 16} ---> <class 'dict'> ---> <class 'dict'>
ExtMarks ---> {'cm': 70, 'c++': 67} ---> <class 'dict'> ---> <class 'dict'>
cname ---> OU ---> <class 'str'> ---> <class 'dict'>
>>> print(d1)
{'sno': 100, 'name': 'RS', 'IntMarks': {'cm': 17, 'c++': 16}, 'ExtMarks': {'cm': 70, 'c++': 67}, 'cname': 'OU'}

137
>>> d1.get("IntMarks")
{'cm': 17, 'c++': 16}
>>> d1.get("ExtMarks")
{'cm': 70, 'c++': 67}
>>> for it in d1.get("IntMarks").items():
... print(it)
...
('cm', 17)
('c++', 16)
>>> for k,v in d1.get("IntMarks").items():
... print(k,"--->",v)
...
cm ---> 17
c++ ---> 16
>>> for k,v in d1.get("ExtMarks").items():
... print(k,"--->",v)
...
cm ---> 70
c++ ---> 67
>>> print(d1)
{'sno': 100, 'name': 'RS', 'IntMarks': {'cm': 17, 'c++': 16}, 'ExtMarks': {'cm': 70, 'c++': 67}, 'cname': 'OU'}
>>> for k,v in d1["IntMarks"].items():
... print(k,"--->",v)
...
cm ---> 17
c++ ---> 16
>>> for k,v in d1["ExtMarks"].items():
... print(k,"--->",v)
...
cm ---> 70
c++ ---> 67
>>>
>>> print(d1)

138
{'sno': 100, 'name': 'RS', 'IntMarks': {'cm': 17, 'c++': 16}, 'ExtMarks': {'cm': 70, 'c++': 67}, 'cname': 'OU'}
>>> d1["IntMarks"]["cm"]
17
>>> d1["IntMarks"]["cm"]=18
>>> print(d1)
{'sno': 100, 'name': 'RS', 'IntMarks': {'cm': 18, 'c++': 16}, 'ExtMarks': {'cm': 70, 'c++': 67}, 'cname': 'OU'}
>>> d1["ExtMarks"]["cm"]=77
>>> print(d1)
{'sno': 100, 'name': 'RS', 'IntMarks': {'cm': 18, 'c++': 16}, 'ExtMarks': {'cm': 77, 'c++': 67}, 'cname': 'OU'}
>>> d1["ExtMarks"]["cm"]=d1["ExtMarks"].get("cm")+2
>>> print(d1)
{'sno': 100, 'name': 'RS', 'IntMarks': {'cm': 18, 'c++': 16}, 'ExtMarks': {'cm': 79, 'c++': 67}, 'cname': 'OU'}
>>> d1["ExtMarks"]["c++"]=d1["ExtMarks"]["c++"]+2
>>>
>>> print(d1)
{'sno': 100, 'name': 'RS', 'IntMarks': {'cm': 18, 'c++': 16}, 'ExtMarks': {'cm': 79, 'c++': 69}, 'cname': 'OU'}
>>> d1["IntMarks"].pop("c++")
16
>>> print(d1)
{'sno': 100, 'name': 'RS', 'IntMarks': {'cm': 18}, 'ExtMarks': {'cm': 79, 'c++': 69}, 'cname': 'OU'}
>>> d1.pop("IntMarks")
{'cm': 18}
>>> print(d1)
{'sno': 100, 'name': 'RS', 'ExtMarks': {'cm': 79, 'c++': 69}, 'cname': 'OU'}
>>> d1["IntMarks"]={"Java":15,"Python":16}
>>> print(d1)
{'sno': 100, 'name': 'RS', 'ExtMarks': {'cm': 79, 'c++': 69}, 'cname': 'OU', 'IntMarks': {'Java': 15, 'Python': 16}}
>>> d1["ExtMarks"]["os"]=80
>>> print(d1)
{'sno': 100, 'name': 'RS', 'ExtMarks': {'cm': 79, 'c++': 69, 'os': 80}, 'cname': 'OU', 'IntMarks': {'Java': 15, 'Python':
16}}
>>> d1["ExtMarks"]["Bonus"]={"CB":1,"CPPB":2}
>>> print(d1)

139
{'sno': 100, 'name': 'RS', 'ExtMarks': {'cm': 79, 'c++': 69, 'os': 80, 'Bonus': {'CB': 1, 'CPPB': 2}}, 'cname': 'OU',
'IntMarks': {'Java': 15, 'Python': 16}}
>>> for k,v in d1["ExtMarks"]["Bonus"].items():
... print(k,"--->",v)
...
CB ---> 1
CPPB ---> 2
>>> d1.get("ExtMarks").pop("Bonus")
{'CB': 1, 'CPPB': 2}
>>> print(d1)
{'sno': 100, 'name': 'RS', 'ExtMarks': {'cm': 79, 'c++': 69, 'os': 80}, 'cname': 'OU', 'IntMarks': {'Java': 15, 'Python':
16}}
=========================
Case2: set in dict--Possible
=========================
>>> d1={"sno":10,"sname":"RS","IntMarks":{17,19,16},"ExtMarks":{67,77,78},"cname":"CUCET"}
>>> print(d1,type(d1))---{'sno': 10, 'sname': 'RS', 'IntMarks': {16, 17, 19}, 'ExtMarks': {67, 77, 78}, 'cname':
'CUCET'} <class 'dict'>
>>> for k,v in d1.items():
... print(k,"--->",v,"--->",type(v),type(d1))
...
sno ---> 10 ---> <class 'int'> <class 'dict'>
sname ---> RS ---> <class 'str'> <class 'dict'>
IntMarks ---> {16, 17, 19} ---> <class 'set'> <class 'dict'>
ExtMarks ---> {67, 77, 78} ---> <class 'set'> <class 'dict'>
cname ---> CUCET ---> <class 'str'> <class 'dict'>
>>> d1["IntMarks"]-------------{16, 17, 19}
>>> d1["IntMarks"].add(15)
>>> d1["ExtMarks"].add(64)
>>> print(d1,type(d1))----{'sno': 10, 'sname': 'RS', 'IntMarks': {16, 17, 19, 15}, 'ExtMarks': {64, 67, 77, 78},
'cname': 'CUCET'} <class 'dict'>
>>> d1.pop("IntMarks")-------{16, 17, 19, 15}

140
>>> print(d1,type(d1))--------{'sno': 10, 'sname': 'RS', 'ExtMarks': {64, 67, 77, 78}, 'cname': 'CUCET'} <class
'dict'>
>>> d1["ExtMarks"].clear()------->>> print(d1,type(d1))
{'sno': 10, 'sname': 'RS', 'ExtMarks': set(), 'cname': 'CUCET'} <class 'dict'>
>>> d1.pop("ExtMarks")---------set()
>>> print(d1,type(d1))---{'sno': 10, 'sname': 'RS', 'cname': 'CUCET'} <class 'dict'>
>>> d1["IntMarks"]={17,16,15}
>>> print(d1,type(d1))-------{'sno': 10, 'sname': 'RS', 'cname': 'CUCET', 'IntMarks': {16, 17, 15}} <class 'dict'>
=========================
Case3: tuple in dict--Possible
=========================
>>> d1={"sno":10,"sname":"RS","IntMarks":(17,19,16),"ExtMarks":(67,77,78),"cname":"CUCET"}
>>> print(d1,type(d1))----{'sno': 10, 'sname': 'RS', 'IntMarks': (17, 19, 16), 'ExtMarks': (67, 77, 78), 'cname':
'CUCET'} <class 'dict'>
>>> for k,v in d1.items():
... print(k,"--->",v,"--->",type(v),type(d1))
...
sno ---> 10 ---> <class 'int'> <class 'dict'>
sname ---> RS ---> <class 'str'> <class 'dict'>
IntMarks ---> (17, 19, 16) ---> <class 'tuple'> <class 'dict'>
ExtMarks ---> (67, 77, 78) ---> <class 'tuple'> <class 'dict'>
cname ---> CUCET ---> <class 'str'> <class 'dict'>
>>> d1["IntMarks"]-----------(17, 19, 16)
>>> d1["IntMarks"][::2]------(17, 16)
>>> d1["ExtMarks"]----------(67, 77, 78)
>>> d1["ExtMarks"]=tuple(sorted(d1["ExtMarks"])[::-1])
>>> print(d1,type(d1))----{'sno': 10, 'sname': 'RS', 'IntMarks': (17, 19, 16), 'ExtMarks': (78, 77, 67), 'cname':
'CUCET'} <class 'dict'>
==========================
Case4: list in dict--Possible
==========================
>>> d1={"sno":10,"sname":"RS","IntMarks":[17,19,16],"ExtMarks":[67,77,78],"cname":"CUCET"}

141
>>> print(d1,type(d1))---{'sno': 10, 'sname': 'RS', 'IntMarks': [17, 19, 16], 'ExtMarks': [67, 77, 78], 'cname':
'CUCET'} <class 'dict'>
>>> for k,v in d1.items():
... print(k,"--->",v,"--->",type(v),type(d1))
...
sno ---> 10 ---> <class 'int'> <class 'dict'>
sname ---> RS ---> <class 'str'> <class 'dict'>
IntMarks ---> [17, 19, 16] ---> <class 'list'> <class 'dict'>
ExtMarks ---> [67, 77, 78] ---> <class 'list'> <class 'dict'>
cname ---> CUCET ---> <class 'str'> <class 'dict'>
>>> d1["IntMarks"].insert(1,15)
>>> d1["ExtMarks"].insert(-1,55)
>>> print(d1,type(d1))---{'sno': 10, 'sname': 'RS', 'IntMarks': [17, 15, 19, 16], 'ExtMarks': [67, 77, 55, 78], 'cname':
'CUCET'} <class 'dict'>
>>> d1["IntMarks"].sort()
>>> d1["ExtMarks"].sort(reverse=True)
>>> print(d1,type(d1))----{'sno': 10, 'sname': 'RS', 'IntMarks': [15, 16, 17, 19], 'ExtMarks': [78, 77, 67, 55],
'cname': 'CUCET'} <class 'dict'>
>>> d1["ExtMarks"].insert(-1,[1.2,2.3])
>>> print(d1,type(d1))--{'sno': 10, 'sname': 'RS', 'IntMarks': [15, 16, 17, 19], 'ExtMarks': [78, 77, 67, [1.2, 2.3],
55], 'cname': 'CUCET'} <class 'dict'>
>>> d1["IntMarks"].insert(2,(1.2,2.3))
>>> print(d1,type(d1))---{'sno': 10, 'sname': 'RS', 'IntMarks': [15, 16, (1.2, 2.3), 17, 19], 'ExtMarks': [78, 77, 67,
[1.2, 2.3], 55], 'cname': 'CUCET'} <class 'dict'>
==============================
Case5: dict in set--------Not Possible
==============================
>>> s1={10,"RS",{"C":15,"CPP":14,"OS":17},"OUCET"}----------TypeError: unhashable type: 'dict'
========================
Case6: dict in tuple--Possible
=========================
>>> tpl=(10,"RS",{"C":15,"CPP":14,"OS":17},"OUCET")
>>> print(tpl,type(tpl))-----(10, 'RS', {'C': 15, 'CPP': 14, 'OS': 17}, 'OUCET') <class 'tuple'>
142
>>> for val in tpl:
... print(val,"--->",type(val),type(tpl))
...
10 ---> <class 'int'> <class 'tuple'>
RS ---> <class 'str'> <class 'tuple'>
{'C': 15, 'CPP': 14, 'OS': 17} ---> <class 'dict'> <class 'tuple'>
OUCET ---> <class 'str'> <class 'tuple'>
>>> tpl[2]["DBMS"]=16
>>> print(tpl,type(tpl))-----(10, 'RS', {'C': 15, 'CPP': 14, 'OS': 17, 'DBMS': 16}, 'OUCET') <class 'tuple'>
>>> for k,v in tpl[2].items():
... print(k,"-->",v)
...
C --> 15
CPP --> 14
OS --> 17
DBMS --> 16
>>> del tpl[2]-----------TypeError: 'tuple' object doesn't support item deletion
>>> tpl[2].pop("OS")------17
>>> print(tpl,type(tpl))----(10, 'RS', {'C': 15, 'CPP': 14, 'DBMS': 16}, 'OUCET') <class 'tuple'>
=====================
Case7: dict in list----Possible
======================
>>> lst=[10,"RS",{"C":15,"CPP":14,"OS":17},"OUCET"]
>>> print(lst,type(lst))-------------[10, 'RS', {'C': 15, 'CPP': 14, 'OS': 17}, 'OUCET'] <class 'list'>
>>> for val in lst:
... print(val,"--->",type(val),type(lst))
...
10 ---> <class 'int'> <class 'list'>
RS ---> <class 'str'> <class 'list'>
{'C': 15, 'CPP': 14, 'OS': 17} ---> <class 'dict'> <class 'list'>
OUCET ---> <class 'str'> <class 'list'>
>>> lst.pop(2)---------{'C': 15, 'CPP': 14, 'OS': 17}
>>> print(lst,type(lst))------[10, 'RS', 'OUCET'] <class 'list'>
143
>>> lst.insert(-1,{"C":15,"CPP":14})
>>> print(lst,type(lst))----[10, 'RS', {'C': 15, 'CPP': 14}, 'OUCET'] <class 'list'>
>>> lst[2]["OS"]=15
>>> print(lst,type(lst))-----[10, 'RS', {'C': 15, 'CPP': 14, 'OS': 15}, 'OUCET'] <class 'list'>

=======================================================
NoneType Category Data Type
=======================================================
=>" NoneType" is one of the pre-defined class
=>None is the Keyword and Treated as Value of NoneType Data Type
=>None is not False, Space, 0 and None is Nothing
=>We can't create an object of NoneType bcoz It contains Single Value
--------------------------------------------------------
Examples
--------------------------------------------------------
>>> a=None
>>> print(a,type(a))--------------None <class 'NoneType'>
>>> None==0----------------------False
>>> None==""--------------------False
>>> None==False----------------False
>>> None==None----------------True
>>> n=NoneType()------------------------NameError: name 'NoneType' is not defined
==============================================================
Number of Approaches to Develop Programs in Python
==============================================================
Definition of Program
-------------------------------
=>Set of Optmized Instructions is called Program.
=>Optmized Instructions of Program takes Less Memory Space(Space Complexity) and Less Execution(Time
Complexcity).
------------------------------------------
Need of Writing the Program
------------------------------------------

144
=>The Need of writing the Program is that To Implement Certain Task OR To develop any Real Time
Applications
=>Programtaically, In Python, we define OR develop set of Optimized Instructions and Saved on Some Name
with an extension called .py ( Called File Name--->FileName.py)
----------------------------------------------
=>In Python Programming, we have Two Approaches to develop the Program. They are
1. By using Interactive Approach
2. By Using Batch Mode Approach
------------------------------------------------
1. By using Interactive Approach
-------------------------------------------------
=>In Interactive Approach, Python Programmer can Issue One Instruction at a time and gets an output at a time.
=> Interactive Approach is useful to test One Instruction at a time But Not Useful to develop Big
Applications/Programs bcoz This Environment never allows us to Save the Instructions and More Over Never
allows us to re-use those Instructions in other part of Program.
=>In Order to write Programs in real Time, we always go for Batch Mode Approach.
--------------------------
Example Software:
--------------------------
a. Python Command
b. Python IDLE Shell
------------------------------------------------
2. By Using Batch Mode Approach
------------------------------------------------
=>In Batch Mode Approach, we define set of Optmized Instructions and Saved on Some File Name with an
extension called .py (FileName.py).
=>To develop any real time application, we always go for Batch Mode.
------------------------------
Examples Softwares:
------------------------------
a. Python IDLE Shell
-----------------------------
By using IDEs(Integrated Development Environment)
145
-----------------------------
PyCharm
Jupiter Note Book
Spider
VS Code
Google Clab.....etc
=>To Run the python Program from Windows Command Prompt, we use the Following Syntax
=>Syntax: python FileName.py
OR
py FileName.py
Here "python" and "py" are tools used for Running the python Program from Windows Command Prompt.
----------------
Examples:
---------------
E:\KVR-PYTHON-4PM\BATCH MODE>python SumOpEx3.py
Enter First Value:3
Enter Second Value:6.7
==============================
Val of a= 3.0
Val of b= 6.7
Sum= 9.7
==============================
OR
E:\KVR-PYTHON-4PM\BATCH MODE>py SumOpEx3.py
Enter First Value:3
Enter Second Value:6.7
==============================
Val of a= 3.0
Val of b= 6.7
Sum= 9.7
==============================
#Program for adding of Two Numbers
a=10
146
b=20
c=a+b
print(a)
print(b)
print(c)
#Program for adding 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 adding of Two Numbers
a=float(input("Enter First Value:"))
b=float(input("Enter Second Value:"))
c=a+b
print("="*30)
print("Val of a=",a)
print("Val of b=",b)
print("Sum=",c)
print("="*30)
======================================================
Display 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 other words, print() is a pre-defined Function used for Display the Result of Python Program on the Console.
=>print() can be used with the following Syntaxes
***********************************************
Syntax-1: print(Val1)
print(Val1,Val2,.....,Val-n)
***********************************************
147
=>This Syntax displays either Single Value or Multiple Values.
---------------
Examples
---------------
>>> a=10
>>> print(a)----------10
>>> a=10
>>> b=20
>>> c=a+b
>>> print(a,b,c)------10 20 30
*****************************************
Syntax-2: print(Msg1)
print(Msg1,Msg2,....,Msg-n)
print(Msg1+Msg2+....+Msg-n)
******************************************
=>Here Msg1,Msg2,....,Msg-n are called Messages of type <class,'str'>
=>Here This Syntax display String Messages on the Console
------------------
Examples
------------------
>>> print("Hello Python")------------Hello Python
>>> print('Hello Python')-------------Hello Python
>>> print('''Hello Python''')----------Hello Python
>>> print("""Hello Python""")------Hello Python
-------------
>>> print("Hello","Python")----Hello Python
>>> print('Hello',"Python")----Hello Python
-------------
>>> print("hello"+"python")------hellopython
>>> print("Hello"+" "+"Python")---------Hello Python
-----------------
>>> print("Python"+3.12)-----------TypeError: can only concatenate str (not "float") to str
>>> print("Python"+str(3.12))--------Python3.12
148
>>> print("Python"+"3.12")-----------Python3.12
--------------------
>>> print("Python"+str(2+3))---------Python5
>>> print("Python"+str("2+3"))------Python2+3
****************************************************
Syntax-3: print(Message Cum Value)
print(Value Cum Message)
************************************************
=>This Syntax displays Message Cum Values OR Values Cum Messages.
-------------------
Examples
-------------------
>>> print("Val of a=",a)----------Val of a= 10
>>> print(a,"is the val of a")----10 is the val of a
----------------
>>> a=10
>>> print("Val of a="+str(a))-----Val of a=10
>>> print(str(a)+" is the val of a")---10 is the val of a
----------------------
>>> a=10
>>> b=20
>>> c=a+b
>>> print("sum=",c)--------sum= 30
>>> print("sum="+str(c))-----sum=30
>>> print(c," is the sum")---30 is the sum
>>> print(str(c)+" is the sum")---30 is the sum
>>> print("Sum of",a," and ",b,"=",c)----Sum of 10 and 20 = 30
>>> print("sum of "+str(a)+" and "+str(b)+"="+str(c))---sum of 10 and 20=30
---------------
>>> a=10
>>> b=20
>>> c=30
>>> d=a+b+c
149
>>>> print("Sum of",a,",",b,"and",c,"=",d)---Sum of 10 , 20 and 30 = 60
>>> print("Sum of "+str(a)+","+str(b)+" and "+str(c)+"="+str(d))---Sum of 10,20 and 30=60
**********************************************
Syntax-4: print(Message Cum Values with format())
************************************************
=>This Function display the Messages cum values with format()
-------------------
Examples
-------------------
>>> print("Val of a={}".format(a))-------Val of a=10
>>> print("{} is the value of a".format(a))-----10 is the value of a
--------------------
>>> a=10
>>> b=20
>>> c=a+b
>>> print("Sum of {} and {}={}".format(a,b,c))----Sum of 10 and 20=30
>>> print("Sum(",a,",",b,")=",c)----------Sum( 10 , 20 )= 30
-----------------
>>> print("sum({},{})={}".format(a,b,c))--------sum(10,20)=30
>>> print("{}+{}={}".format(a,b,c))--------------10+20=30
-------------------------------
>>> sno=10
>>> sname="Rossum"
>>> print("My Number is {} and Name is {}".format(sno,sname))----My Number is 10 and Name is Rossum
--------------------
>>> sno=10
>>> sname="Rossum"
>>> print("My Number is {} and Name is '{}' ".format(sno,sname))----My Number is 10 and Name is 'Rossum'
****************************************************
Syntax-5: print(Message Cum Values with format Specifiers )
***************************************************
=>In Python Programming, we have the following Format Specifiers
=>Here %d Represents int Data
150
=>Here %f Represents float Data
=>Here %s Represents str Data
------------------------------
Examples
------------------------------
>>> a=10
>>> b=2.3
>>> c=a+b
>>> print("Sum of %d and %f =%f" %(a,b,c))--------Sum of 10 and 2.300000 =12.300000
>>> print("Sum of %d and %0.2f =%0.2f" %(a,b,c))---Sum of 10 and 2.30 =12.30
---------------------------------
>>> sno=10
>>> sname="Rs"
>>> marks=975.67
>>> print("My Number is %d and Name is '%s' and Marks is %f" %(sno,sname,marks))
My Number is 10 and Name is 'Rs' and Marks
is 975.670000
>>> print("My Number is %d and Name is '%s' and Marks is %0.2f" %(sno,sname,marks))
My Number is 10 and Name is 'Rs' and Marks
is 975.67
-----------------------
>>> print("Content of lst=%s" %str(lst))---------Content of lst=[100, 'RS', 23.45]
******************************************
Syntax-6: print(value,end=" ")
******************************************
=>This syntax display the the result of Python program in same line
--------------
Examples
--------------
>>> for val in range(10,21):
... print(val,end=" ")-----10 11 12 13 14 15 16 17 18 19 20
>>> for val in range(10,21):
... print(val,end="-->")--- 10-->11-->12-->13-->14-->15-->16-->17-->18-->19-->20-->
151
======================================================
Reading the Data OR Input Dynamically From Key Board
======================================================
=>To Read the Data from KeyBoard, we have 2 Pre-Defined Functions. They are
1. input()
2. input(Message)
*************
1. input()
*************
=>Syntax: varname=input()
=>here input() is used for Reading Any type of Value from Key Board and Stored in LHS Variable in the form
of str.
=>Here str type data can be converted into any type of Data based Type Conversion Functions.
*******************
2. input(Message)
*****************
=>Syntax: varname=input(Message)
=>Here Message Represents User-Prompting Message and It is str type.
=>here input(Message) is used for Reading Any type of Value from Key Board and Stored in LHS Variable in
the form of str and Additionally This function also Gives User-Prompting Message.
=>Here str type data can be converted into any type of Data based Type Conversion Functions.
#DataReadEx1.py
print("Enter Any Value") # User-Prompting Message
x=input()
print(x,type(x))
#DataRead2.py
x=input("Enter Any Value:")
print(x,type(x))
#Program for Multipying Two Numbers
#DataRead3.py
print("Enter First Value:")
x=input()

152
print("Enter Second Value:")
y=input()
#Convert str int into float or int type
a=float(x)
b=float(y)
c=a*b
print("First Value={}".format(a))
print("Second Value={}".format(b))
print("Mul({},{})={}".format(a,b,c))
#Program for Multipying Two Numbers
#DataRead4.py
print("Enter Two Values:")
#Reading the Data from KBD and Convert
a=float(input())
b=float(input())
c=a*b
print("First Value={}".format(a))
print("Second Value={}".format(b))
print("Mul({},{})={}".format(a,b,c))
#Program for Multipying Two Numbers
#DataRead4.py
print("Enter Two Values:")
#Reading the Data from KBD and Convert
a=float(input())
b=float(input())
print("First Value={}".format(a))
print("Second Value={}".format(b))
print("Mul({},{})={}".format(a,b,a*b))
#Program for Multipying Two Numbers
#DataRead6.py
a=input("Enter First Value:")
b=input("Enter Second Value:")

153
x=float(a)
y=float(b)
z=x*y
print("Mul({},{})={}".format(x,y,z))
#Program for Multipying Two Numbers
#DataRead7.py
print("Mul={}".format(float(input("Enter First Value:"))*float(input("Enter Second Value:"))))
#Program for Multipying Two Numbers
#DataRead8.py
x=float(input("Enter First Value:"))
y=float(input("Enter Second Value:"))
z=x*y
print("Mul({},{})={}".format(x,y,z))
print("==========OR=====================")
print("Mul({},{})={}".format(x,y,x*y))
#Program for Calculating Area of Circle
r=float(input("Enter Radius:"))
area=3.14*r*r
print("Radius={}".format(r))
print("Area of Circle={}".format(area))
print("----------OR------------------")
print("Area of Circle=%0.3f" %area)
print("----------OR------------------")
print("Area of Circle={}".format(round(area,3)))
#Program for Calculating Area and Circumfrence of Rect
length=float(input("Enter Length:"))
breadth=float(input("Enter Breadth:"))
#Cal Area
ar=length*breadth
#cal Circumfrence
cr=2*(length+breadth)
print("="*50)

154
print("Length={}".format(length))
print("Breadth={}".format(breadth))
print("Area of Rect={}".format(ar))
print("Circumfrence of Rect={}".format(cr))
print("*"*50)
==========================================================
Operators and Expressions in Python
==========================================================
=>An Operator is a Symbol which will perform an Operation on Data OR Values OR Objects.
=>If Two or More Objects OR Variables OR Values Connected with an Operator then It is called Expression.
=>In Other words, An Expression is a Collection of Objects OR Variables OR Values Connected with
Operator(s).
=>In Python Programming, we have 7 Types of Operators. They are
1. Arithmetic Operators.
2. Assigment Operator
3. Relational Operators
4. Logical Operators
5. Bitwise Operators------Most Imp
6. Membership Operators
i) in
ii) not in
7. Identity Operators
i) is
ii) is not
---------------------------------------------------------------------------------------------------------------------------------------
NOTE-1: Python Programming does not Support Unary Operators ( ++ ) and (- -)
NOTE-2: Python Programming does not Support Ternary Operator of C,C++,Java ( ? : )
---------------------------------------------------------------------------------------------------------------------------------------
NOTE-3: Python Programming Supports Short Hand Operators
NOTE-4: Python Programming is Having Its Own Ternary Operator ( if..else Operator)

155
============================================================
1. Arithmetic Operators
============================================================
=>The purpose of Arithmetic Operators is that "To perform Arithmetic Operations such as Addition,
substraction,Multiplication..etc".
=>If two or More Objects or Values Connected with Arithmetic Operators then It is Called Arithmetic
Expression.
=>In Python Programming, we have 7 Types of Arithmetic Operators. They are given in the following Table.
******************************************************************************************
SLNO SYMBOL MEANING EXAMPLE : a=10 b=3
******************************************************************************************
1. + Addition print(a+b)------>13 here
a+b is called Arithmetic Expression

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

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

4. / Division print(a/b)-----
>3.3333333333333335
(Float Quotiet)

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


(Integer Quotiet)

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


( Remainder )

7. ** Exponentiation print(a**b)----->1000.0

(Power of Operator)

NOTE:
----------
>>> 10/3----------------------3.3333333333333335
>>>10//3-----------------------3
-----------------------------------------------
>>> 10.0/3.0---------------3.3333333333333335
>>> 10.0//3.0--------------3.0
----------------------------------------------
>>> 10.0/3-------------3.3333333333333335
>>> 10.0//3-------------3.0
----------------------------------------------
>>> 10/3.0------------------3.3333333333333335
>>> 10//3.0-----------------3.0
=============================================================================
156
#ArithmeticOperatorEx1.py
a=int(input("Enter Value of a:"))
b=int(input("Enter Value of b:"))
print("*"*50)
print("\t\tResults of Arithmetic Operators")
print("*"*50)
print("\t\tSum({},{})={}".format(a,b,a+b))
print("\t\tSub({},{})={}".format(a,b,a-b))
print("\t\tMul({},{})={}".format(a,b,a*b))
print("\t\tDiv({},{})={}".format(a,b,a/b))
print("\t\tFloor Div({},{})={}".format(a,b,a//b))
print("\t\tModDiv({},{})={}".format(a,b,a%b))
print("\t\tpower({},{})={}".format(a,b,a**b))
print("*"*50)
#Here a+b , a-b, a*b, a/b , a//b, a%b , a**b are called Arithmetic Expressions.
#Program for Demonstrating Square Root of given Number without using sqrt() of math
module
#ArithmeticOperatorEx2.py
n=float(input("Enter a Number for cal Square Root of a Number:"))
res=n**0.5 # OR res=n**(1/2)
print("sqrt({})={}".format(n,res))

#Program for Demonstrating Cube Root of given Number without using sqrt() of math
module
#ArithmeticOperatorEx3.py
n=float(input("Enter a Number for cal Square Root of a Number:"))
res=n**(1/3)
print("cube({})={}".format(n,round(res)))

157
==================================================
2. Assignment 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

158
>>> 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
------------------------------------------
>>> a,b=10,20
>>> print(a,b)-------------------10 20
>>> a,b=b,a # Swapping Logic
>>> print(a,b)-----------20 10
==================================================
3. Relational Operators
==================================================
=>The purpose of Relational Operators is that " To Compare Two Values".
=>If Two Objects Connected with Relational Operators then It is Called Relational Expression.
=>The Result of Relational Expression is either True OR False (Bool Values)
=>The Relational Expression is called Test Condition(Simple Test Condition).
=>In Python Programming, we have 6 Types of Relational Operators. They are given in the following Table
---------------------------------------------------------------------------------------------------------------------------------------
SLNO SYMBOL MEANING EXAMPLE
---------------------------------------------------------------------------------------------------------------------------------------
1. > Greater Than print(10>2)------True
print(10>40)-----False

2. < Less Than print(10<5)------False


print(10<20)-----True

3. == Equality print(10==10)----True
(Double Equal to) print(10==20)----False

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


print(10!=20)-----True

5. >= Greater than print(10>=5)------True


159
or equal to print(10>=20)-----False

6. <= Less than print(10<=5)-------False


or equal to print(10<=40)-----True
------------------------------------------------------------------------------------------------------------------------------
Note-1: Complex Data Type Values Can't be Compared with Relational Operators bcoz complex number is the
composition of Numerical values with special symbol 'j'
Note-2:
------------
>>> "india"=="INDIA"------------False
>>> "abc">"acb"------------------False
>>> "abc">="acb"----------------False
>>> "acb">="abc"----------------True
>>> "india">="indai"------------True
>>> "just"<="jsut"---------------False
>>> "this">="thsi"---------------False
>>> "wrong"<="wrogn"--------False
----------------------------------------------
NOTE: To find Unicode value of any Symbol or Alphabet, we use ord()
Syntax: ord("Symbol / Alphabet")
>>> ord('p')----------112
>>> ord('P')-----------80
>>> ord('a')-----------97
>>> ord('A')-----------65
>>> ord("#")----------35
>>> ord("$")--------36
>>> "#">"$"--------False
------------------------------------
NOTE: chr() is used for Obtaining Char Value for Numerical Integer Values
Syntax: chr(Integer Value)
-------------------
Examples
-------------------

160
>>> chr(112)----------'p'
>>> chr(65)------------'A'
>>> chr(97)-----------'a'
>>> chr(36)----------'$'
>>> chr(35)----------'#'
===============================================================================
>>> for val in range(65,91):
Print(val,”-->”,chr(val))
65→A to 90→Z
>>>
>>>
>>> for val in range(97,123):
... print(val,"-->",chr(val))
97 --> a to 122-- >z
#RelationalOperatorsEx.py
a=int(input("Enter First Value:"))
b=int(input("Enter Second Value:"))
print("*"*50)
print("Result of Relational Expression")
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("*"*50)
#Program for Swpapping / interchanging of Two Values
#AssigmentOpEx1.py--Logic-1
a=input("Enter Value of a:")
b=input("Enter Value of b:")
print("*"*50)
print("\tOriginal Value of a:{}".format(a))

161
print("\tOriginal Value of b:{}".format(b))
print("*"*50)
#Swapping Logic
a,b,=b,a # OR b,a=a,b
print("\tSwapped Value of a:{}".format(a))
print("\tSwapped Value of b:{}".format(b))
print("*"*50)
#Program for Swpapping / interchanging of Two Values
#AssigmentOpEx2.py--Logic-2
a,b=input("Enter Value of a:"),input("Enter Value of b:")
print("*"*50)
print("\tOriginal Value of a:{}".format(a))
print("\tOriginal Value of b:{}".format(b))
print("*"*50)
#Swapping Logic
x=a # Here x is called Temp Variable
a=b
b=x
print("\tSwapped Value of a:{}".format(a))
print("\tSwapped Value of b:{}".format(b))
print("*"*50)
#Program for Swapping / interchanging of Two Integer Values
#AssigmentOpEx3.py--Logic-3
a,b=int(input("Enter Integer Value for a:")),int(input("Enter Integer Value for b:"))
print("*"*50)
print("\tOriginal Value of a:{}".format(a))
print("\tOriginal Value of b:{}".format(b))
print("*"*50)
#Swapping Logic
a=a+b
b=a-b
a=a-b
print("\tSwapped Value of a:{}".format(a))
162
print("\tSwapped Value of b:{}".format(b))
print("*"*50)
#Program for Swapping / interchanging of Two Integer Values
#AssigmentOpEx4.py--Logic-4
a,b=int(input("Enter Integer Value for a:")),int(input("Enter Integer Value for b:"))
print("*"*50)
print("\tOriginal Value of a:{}".format(a))
print("\tOriginal Value of b:{}".format(b))
print("*"*50)
#Swapping Logic
a=a*b
b=a//b
a=a//b
print("\tSwapped Value of a:{}".format(a))
print("\tSwapped Value of b:{}".format(b))
print("*"*50)
============================================================
4. Logical Operators
============================================================
=>The purpose of Logical Operators is that "To combine Two OR More Relational Expressions".
=>If Two OR More Relational Expressions Connected with Logical Operators then It is Called Logical
Expression.
=>The Result of Logical Expression is either True or False.
=>The Logical Expression is called Compund Test Condition (Multiple Relational Expressions)
=>In Python Programming, we have 3 Types of Logical Operators. They are Given in the following Table
--------------------------------------------------------------------------------------------------------------------------------------
SLNO SYMBOL MEANING
--------------------------------------------------------------------------------------------------------------------------------------
1. and Physical ANDing
2. or Physical ORing
3. not ----------------------------
--------------------------------------------------------------------------------------------------------------------------------------

163
1. and Operators
******************************************************************************************
=>The functionality of "and" Operator is described in the following Truth table
----------- -----------------------------------------------------------------------------------------------------------------
RelExpr1 RelExpr2 RelExpr1 and RelExpr2
----------------------------------------------------------------------------------------------------------------------
False True False
True False False
False False False
True True True
----------------------------------------------------------------------------------------------------------------
Example1
---------------
>>> False and True-------------False
>>> True and False-------------False
>>> False and False-----------False
>>> True and True--------------True
----------------
Example2
----------------
>>> 10>2 and 10>30----------False----Full Length Evaluation
>>> 10>20 and 20>10--------False----Short Circuit Evaluation
>>> 10>20 and 20>30 and 10>4----False-------Short Circuit Evaluation
>>> 10>2 and 30>20 and 10>2-------True----Full Length Evaluation
-----------------------------------------------------------------
Short Circuit Evaluation of "and" Operator
-----------------------------------------------------------------
If Two or More Relational Expressions Connected with "and" Operator and If the Result of First Relational
Expression is False then PVM will not evaluate Second and Sub-Sequenent Relational Expressions and Total
Result of Entire Expressions ( Logical Expression) is False. This Process of Evaluation is called Short Circuit
Evalution.

164
===============================================================================
2. or Operator
*****************************************************************************************
=>The functionality of "or" Operator is described in the following Truth table
--------------------------------------------------------------------------------------------------------------------------------
RelExpr1 RelExpr2 RelExpr1 or RelExpr2
---------------------------------------------------------------------------------------------------------------------------------
False True True
True False True
False False False
True True True
----------------------------------------------------------------------------------------------------------------------------------
Example-1
-------------------
>>> False or True---------True
>>> True or False---------True
>>> False or False--------False
>>> True or True-----------True
------------------------------
Example-2
------------------------------
>>> 10>2 or 20>3---------True--------Short Circuit Evaluation
>>> 10>20 or 20>30-------False-----Full Length Evaluation
>>> 10>2 or 20>10 or 20>30-----True---Short Circuit Evaluation
>>> 100>20 or 200>300 or 400>500------True----Short Circuit Evaluation
-----------------------------------------------------------------
Short Circuit Evaluation of "or" Operator
-----------------------------------------------------------------
=>If Two or More Relational Expressions Connected with "or" Operator and If the Result of First Relational
Expression is True then PVM will not evaluate Second and Sub-Sequenent Relational Expressions and Total
Result of Entire Expressions ( Logical Expression) is True. This Process of Evaluation is called Short Circuit
Evalution.

165
3. not Operator
**********************************************************************************
=>The functionality of "not" Operator is described in the following Truth table
-------------------------------------------------------------------------------------
RelExpr1 not RelExpr1
-------------------------------------------------------------------------------------
False True
True False
-------------------------------------------------------------------------------------
Example-1
----------------
>>> not True-------False
>>> not False-----True
-------------------------------------------------------------------
Example-2--Special Points of "not" Operator
-------------------------------------------------------------------
>>> not 123---------False
>>> not -345--------False
>>> not 0--------------True
>>> not "Python"----False
>>> not "not"---------False
>>> not "false"------False
>>> not ""------------True
>>> not "10-10"-----False
>>> not (10-10)-----True
Special Points on "and" Operator
------------------------------------------------------------------------------------------------------------------------------------
>>> 100 and 200-----------200
>>> 100 and 0--------------0
>>> -24 and -34------------ -34
>>> 100 and 10 and 1----- 1
>>> 100 and 0 and 200----- 0

166
>>> 100 and True and -25--------25
>>> "Python" and "java" and "HTML"------'HTML'
>>> True and True and "Python"-------------'Python'
-------------------------------------------------------------------------
Special Points on "or" Operator
-------------------------------------------------------------------------
>>> 100 or 200--------------100
>>> 100 or 0-----------------100
>>> 0 or 100-----------------100
>>> 0 or True or 200------True
>>> 100 or 200 or 0-------100
>>> "Python" or "Java" or "C" or "HTML"-----'Python'
------------------------------------------------------------------------
Special Points on "and" and 'or' Operators
-------------------------------------------------------------------------
>>> 100 or 200 and 300 or 400------------100
>>> 10 and 20 or 40 and 50 or 40 and 80-----20
>>> "java" and "Python" and "HTML" or "Django" and 20---'HTML'
>>> 0 and 30 or -123 and 0 and "Python" or True-----True

========================================================
5. Bitwise Operators------Most Imp
========================================================
=>The Bitwise Operators are used performing Operations on Integer Data in the form of Bit by Bit.
=>Bitwise Operators are Applicable on Integer Values only But Not applicable on Floating Point Values bcoz
Floating Point Values does not contain Certainity where as Integer Data Contains Certainity.
=>The Execution Process of Bitwise Operators is shown bellow
a) Bitwise Operators Converts the Integer Data into Binary Bits
b) Bitwise Operators applied on Binary Bits and Peforms Operation depends on Type of Bitwise Operator.
c) Finally the Result of Bitwise Operators displays the Python Execution Environment in the form Decimal
Number System.
=>Since Bitwise Operators peforms the Operations on Binary Bits in the form of Bit by Bit and hence They
named as Bitwise Operators.
=>In Python Programming, we have 6 Types of Bitwise Operators. They are Given in the following Table.
167
------------------------------------------------------------------------------------------------------------------------------------
SLNO SYMBOL MEANING
--------------------------------------------------------------------------------------------------------------------------------------
1. << Bitwise Left Shift Operator
2. >> Bitwise Right Shift Operator
3. & Bitwise AND Operator
4. | Bitwise OR Operator
5. ~ Bitwise Complement Operator (Tilde)
6. ^ Bitwise XOR Operator
=======================================================
1. Bitwise Left Shift Operator ( << )
=======================================================
Syntax: varname = Given Number << No. of Bits
--------------------
Explanation:
--------------------
The Execution Process of Bitwise LeftShift Operator ( << ) is that "It Moves Number of Bits Towards Left Side
By Adding Number of Zeros (Number of Zeros=Depending No. Of bits we Flipped-off) at Right Side.

-------------------------------
Examples
-------------------------------

168
>>> a=10
>>> b=a<<3
>>> print(b)------------80
>>> print(4<<3)-------32
>>> print(9<<2)-------36
>>> print(10<<0)-----10
>>> print(10.3<<2)-----------TypeError: unsupported operand type(s) for <<: 'float' and 'int'
==================================================
2. Bitwise RightShift Operator ( >> )
==================================================
Syntax: varname=Given Data >> No. of Bits
--------------------
Explanation:
--------------------
The Execution Process of Bitwise Right Shift Operator ( >> ) is that "It Moves Number of Bits Towards Right
Side By Adding Number of Zeros (Number of Zeros=Depending No. Of bits we Flipped-off) at Left Side.

-------------------------------
Examples
-------------------------------
>>> a=10

169
>>> b=a>>3
>>> print(b)---------1
>>> print(16>>2)---4
>>> print(32>>3)---4
>>> print(32>>2)---8
>>> print(32>>0)---32
>>> print(80.5<<4)----------TypeError: unsupported operand type(s) for <<: 'float' and 'in’
==================================================
Bitwise AND Operator (&)
==================================================
=>Syntax: Value1 & Value2
=>The Functionality of Bitwise AND Operator (&) is described with following truth table.
---------------------------------------------------------------------------------------------
Value1 Value2 Value1 & Value2
--------------------------------------------------------------------------------------------
0 1 0
1 0 0
0 0 0
1 1 1
----------------------------------------------------------------------------------------------
-----------------------
Example-1
------------------------
>>> 0 & 1----------------0
>>> 1 & 0----------------0
>>> 0 & 0----------------0
>>> 1 & 1----------------1
-----------------------------
Example-2
-----------------------------
>>>a=10------------- 0000 1010
>>>b=4--------------- 0000 0100
-------------------------
170
>>>c=a&b---------- 0000 0000
-------------------------------------------------
>>>print(c)---------0
>>> 10 and 4----------4
>>> 4 and 10----------10
>>> True and True-----True
>>> True & True-------True
>>> 10.2 & 2-------------TypeError: unsupported operand type(s) for &: 'float' and 'int'
>>> 10.2 and 2---------2
>>> "Apple" and "mango"----------'mango'
>>> "Apple" & "mango"-------------TypeError: unsupported operand type(s) for &: 'str' and 'str'
>>> print(5&4)-------------------4
>>> print(4&5)-------------------4
>>> 5 and 4-----------------------4
>>> 4 and 5-----------------------5
---------------------------------------------------------
Example-3
---------------------------------------------------------
>>> s1={10,20,30}
>>> s2={15,20,35}
>>> s3=s1.intersection(s2)
>>> print(s3,type(s3))--------------{20} <class 'set'>
------------------OR------------------------
>>> s1={10,20,30}
>>> s2={15,20,35}
>>> s3=s1&s2 # Bitwise & (AND) Operator
>>> print(s3,type(s3))---------{20} <class 'set'>
>>> s1 and s2-------------------{35, 20, 15}
-------------------------------------
>>> s1={"Apple","mango","Kiwi"}
>>> s2={"Guava","Orango","mango"}
>>> s3=s1.intersection(s2)
>>> print(s3,type(s3))---------------{'mango'} <class 'set'>

171
-----------------------------------
>>> s1={"Apple","mango","Kiwi"}
>>> s2={"Guava","Orango","mango"}
>>> s3=s1&s2
>>> print(s3,type(s3))-------------------{'mango'} <class 'set'>
------------------------------------------
>>> s1={1.2,2.3,4.5}
>>> s2={2.3,3.3,4.4}
>>> s3=s1.intersection(s2)
>>> print(s3,type(s3))---------{2.3} <class 'set'>
>>> s1={1.2,2.3,4.5}
>>> s2={2.3,3.3,4.4}
>>> s3=s1&s2----
>>> print(s3,type(s3))-----------{2.3} <class 'set'>
>>> 2.5&3.4-------------------------TypeError: unsupported operand type(s) for &: 'float' and 'float'
-----------------------------------------
>>> lst=[10,20,30,40]
>>> tpl=(10,15,25,56)
>>> lst&tpl---------------TypeError: unsupported operand type(s) for &: 'list' and 'tuple'
==================================================
Bitwise OR Operator ( | )
==================================================
=>Syntax: Value1 | Value2
=>The Functionality of Bitwise OR Operator ( | ) is described with following truth table.
----------------------------------------------------------------
Value1 Value2 Value1 | Value2
----------------------------------------------------------------
0 1 1
1 0 1
0 0 0
1 1 1
----------------------------------------------------------------
-----------------------
172
Example-1
------------------------
>>> 0 | 1----------------1
>>> 1 | 0----------------1
>>> 0 | 0----------------0
>>> 1 | 1----------------1
-----------------------------
Example-2
-----------------------------
a=10---------------->0000 1010
b=4----------------->0000 0100
------------------------------------------
c=a|b--------------->0000 1110
print(c)------------->14
------------------------------------------
>>> a=10
>>> b=10
>>> print(a|b)------10
------------------------------------------
Example-3
------------------------------------------
>>> s1={10,20,30}
>>> s2={15,10,25}
>>> s3=s1.union(s2)
>>> print(s3,type(s3))--------{20, 25, 10, 30, 15} <class 'set'>
------------------OR---------------
>>> s1={10,20,30}
>>> s2={15,10,25}
>>> s3=s1|s2
>>> print(s3,type(s3))----------{20, 25, 10, 30, 15} <class 'set'>
>>> s1={1.2,2.3,4.5}
>>> s2={1.2,2.3,4.6}
>>> s3=s1|s2
173
>>> print(s3,type(s3))----------{1.2, 2.3, 4.5, 4.6} <class 'set'>
>>> 1.2|2.3--------------------------TypeError: unsupported operand type(s) for |: 'float' and 'float'
----------------------------------------
>>> s1={"Python","Django"}
>>> s2={"C","HTML","C++"}
>>> s3=s1|s2
>>> print(s3,type(s3))-----------{'C++', 'HTML', 'C', 'Python', 'Django'} <class 'set'>
>>> "Python"|"Java"-------------TypeError: unsupported operand type(s) for |: 'str' and 'str'
================================================================
5. Bitwise Complement Operator ( ~ )
================================================================
=>Syntax: varname= ~Given Number
=>The execution process of Bitwise Complement Operator ( ~ ) is that " It Inverts the given bits".
=>Inverting the bits is nothing but 1 becomes 0 and 0 becomes 1
=>The formula for Bitwise Complement Operator ( ~ ) is given bellow
~Given Number = - ( Given Number + 1)
--------------------------------------------------------------------------------------------------------------------------------------
Example1:
--------------------
>>> a=10
>>> print(~a)-------------- -11
>>> a=100
>>> print(~a)----------------- -101
-----------------
>>> a=-123
>>> print(~a)----------------- 122
=======================================================================
Q) Prove that ~10 is -11
=======================================================================
Proof : Given ~10 = -11
Here -11 is the Opposite counter part of 11
=>Given Number 10 and Whose Binary Part is 1010
=> ~10 ----------------- ~(1010) = 0101 (Which is the Binary form of -11 which is the 2's complement of 11)
174
NOTE: All the Negative Numbers are 2's Complement of Their +Ve Numbers
[Example: 10 whose Counter part is -10--which is 2 's complement of 10]
------------------------------------
=>Here -11 is the Opposite counter part of 11 (2's complement of 11 )
=>All Negative Number stored in Main Memory in the form 2's Complement (2's complement= 1's
complement+1)
-------------------------------------------------------
=>Here we Take 11 and whose Binary form is 1 0 1 1
(1's Complement of any Number= 1 becomes 0 and 0 becomes 1)
=>1's Complement of 11 is----------------------------0 1 0 0
=>2's Complement of 11 is----------------------------1's Complement of 11 + 1
=>0100
=>0001 Binary Addition Rules (0+0=0, 1+0=1, 0+1=1 , 1+1= 0 with carry 1 )
----------------
0101----which is 2's Complement of 11 --result is -11
------------------
==============================================================================
Q) Prove that ~16 is -17
==========================================================================
Proof : Given ~16 = -17
Here -17 is the Opposite counter part of 17
=>Given Number 16 and Whose Binary Part is 0001 0000
=> ~16 ----------------- ~(0001 0000) = 1110 1111 (Which is the Binary form of -17)
---------------------------------------------------------
=>Here -17 is the Opposite counter part of 17
=>All Negative Number stored in Main Memory in the form 2's Complement (2's complement= 1's
complement+1)
-------------------------------------------------------
=>Here we Take 17 and whose Binary form is 0001 0001
(1's Complement of any Number= 1 becomes 0 and 0 becomes 1)
=>1's Complement of 17 is----------------------------1110 1110
=>2's Complement of 17 is----------------------------1's Complement of 17 + 1
=> 1110 1110

175
0000 0001 Binary Addition Rules ( (0+0=0,1+0=1, 0+1=1,1+1= 0 with carry 1 )
------------------
1110 1111 (Which is the Binary form of -17)
========================================================================
Q) Prove that ~15 is -16
==============================================================================
Proof : Given ~15 = -16
Here -16 is the Opposite counter part of 16
=>Given Number 15 and Whose Binary Part is 0000 1111
=> ~15 ----------------- ~(0000 1111) = 1111 0000 (Which is the Binary form of -16)
---------------------------------------------------------
=>Here -16 is the Opposite counter part of 16
=>All Negative Number stored in Main Memory in the form 2's Complement (2's complement= 1's
complement+1)
-------------------------------------------------------
=>Here we Take 16 and whose Binary form is 0001 0000
(1's Complement of any Number= 1 becomes 0 and 0 becomes 1)
=>1's Complement of 16 is----------------------------1110 1111
=>2's Complement of 16 is----------------------------1's Complement of 16 + 1
=> 1110 1111
0000 0001 Binary Addition ( (0+0=0, 1+0=1, 0+1=1 , 1+1= 0 with carry 1 )
------------------
1111 0000 (Which is the Binary form of -16)
==============================================================
Bitwise XOR Operator ( ^ )
==============================================================
=>Syntax: Varname= Value1 ^ Value2
=>The Functionality of Bitwise XOR Operator ( ^ ) is expressed with the following Truth Table
------------------------------------------------------------------------------------
Value1 Value2 Value1^Value2
-------------------------------------------------------------------------------------
1 0 1
0 1 1
176
1 1 0
0 0 0
-----------------------------------------------------------------------------------------------
Examples1
----------------------
>>> 1^0----------------1
>>> 0^1----------------1
>>> 1^1----------------0
>>> 0^0----------------0
---------------------------------
Examples2
---------------------------------
>>> print(2^3)--------1
>>> print(10^15)-----5
---------------------------------
Special Points
---------------------------------
>>> s1={10,20,30}
>>> s2={15,20,25}
>>> s3=s1.symmetric_difference(s2)
>>> print(s3,type(s3))----------------{10, 15, 25, 30} <class 'set'>
--------------
>>> s1={10,20,30}
>>> s2={15,20,25}
>>> s3=s1^s2 # Bitwise XOR Operator (^)
>>> print(s3,type(s3))------------{10, 15, 25, 30} <class 'set'>
>>> s1={"apple","mango","kiwi"}
>>> s2={"Sberry","mango","guava"}
>>> s3=s1^s2 # Bitwise XOR Operator (^)
>>> print(s3,type(s3))--------{'guava', 'apple', 'kiwi', 'Sberry'} <class 'set'>
>>> {1.2,2.3,3.4}^{1.2,2.3,4.5}--------{3.4, 4.5}
----------------------
>>> 1.2^2.3-----------------------TypeError: unsupported operand type(s) for ^: 'float' and 'float'
177
>>> "apple"^1.2----------------TypeError: unsupported operand type(s) for ^: 'str' and 'float'
---------------------------------------------------
Imp Logic----Swapping of Two Integer values
---------------------------------------------------
>>> a=3
>>> b=4
>>> print(a,b)---------3 4
>>> a=a^b
>>> b=a^b
>>> a=a^b
>>> print(a,b)--------4 3
==================================================
Membership Operators
==================================================
=>The purpose of Membership Operators is that "To Check the existence the Specified Value in Iterable Object".
=>An Iterable Object is One, which contains More than One Value--such as sequence
type(str,bytes,bytearray,range), list type (list,tuple) , set type(set,frozenset) and dict type.
=>A Non-Iterable Object is One which contains Only One Value such as int,float,bool and complex and None
=>In Python Programming, we have 2 Membership Operators. They are
1. in
2. not in
---------------------------------------------------------------------------------------------------------------------------------------
1) in Operator
---------------------------------------------------------------------------------------------------------------------------------------
Syntax: Value in Iterable-Object
=>Here "in" Operator Returns True provided "Value" Present in Iterable-Object.
=>Here "in" Operator Returns False provided "Value" Not Present in Iterable-Object.
---------------------------------------------------------------------------------------------------------------------------------------
2) not in Operator
---------------------------------------------------------------------------------------------------------------------------------------
Syntax: Value not in Iterable-Object
=>Here "not in" Operator Returns True provided "Value" Not Present in Iterable-Object.
=>Here "not in" Operator Returns False provided "Value" Present in Iterable-Object.
178
---------------------------------------------------------------------------------------------------------------------------------------
Examples
--------------------------------------------------------------------------------------------------------------------------------------
>>> s="PYTHON"
>>> "P" in s---------------------True
>>> "K" in s--------------------False
>>> "p" not in s---------------True
>>> "P" not in s----------------False
-----------------------------
>>> s="PYTHON"
>>> print(s)-----------------PYTHON
>>> "PYT" in s-------------True
>>> "PYT" not in s--------False
>>> "HON" not in s-------False
>>> "NOH" not in s-------True
>>> "NOH" not in s[::-1]---False
>>> "NOH" in s[::-1]--------True
>>> "PTO" in s---------------False
>>> "PTO" in s[::2]---------True
------------------------------------------------------------
>>> lst=[10,"Rossum",23.45,2+3j]
>>> print(lst)-------------------[10, 'Rossum', 23.45, (2+3j)]
>>> 10 in lst---------------------True
>>> "Rossum" in lst----------True
>>> 23.45 not in lst-----------False
>>> "Ros" in lst---------------False
>>> "Ros" in lst[1]-----------True
>>> "Rsu" in lst[1][::2]------True
>>> "Rsu"[::-1] in lst[1][::2][::-1]----True
---------------------------------------------------------------------------
>>> lst=[10,"Rossum",23.45,2+3j]
>>> print(lst)--------------------------[10, 'Rossum', 23.45, (2+3j)]
>>> 2+3j in lst[-1]---------------------TypeError: argument of type 'complex' is not iterable

179
>>> 2+3j in lst[-1].real----------------TypeError: argument of type 'float' is not iterable
---------------------------------------------------------------------------
>>> lst=[10,"Rossum",23.45,2+3j]
>>> "mus" not in lst[-3]--------------True
>>> "mus"[::-1] not in lst[-3]-------False
>>> "mus"[::-1] not in lst[-3][:-1]---True
---------------------------------------------------------------------------------------------------------------------------------------
>>> d={10:"Apple",20:"Mango",30:"Sberry"}
>>> print(d)------------------{10: 'Apple', 20: 'Mango', 30: 'Sberry'}
>>> "Apple" not in d----------True
>>> 10 in d-----------------------True
>>> "Apple" in d[10]----------True
>>> "App" in d[10][::-1]------False
>>> "App"[::-1] not in d[10][::-1]----False
>>> "Apple" in d.values()-------------True
>>> 10 in d.values()---------------------False
---------------------------------------------------------------------------------------------------------------------------------------
>>> 12 in 123---------------------TypeError: argument of type 'int' is not iterable
>>> 12 in "123"------------------TypeError: 'in <string>' requires string as left operand, not int
>>> "12" in "123"---------------True
>>> "13" not in "123"----------True
>>> "13" not in "123"[::2]-----False
>>> "13" in "123"[::2]----------True
=========================================================
7. Identity Operators (Applicable on Python Command Only)
=========================================================
=>The purpose of Identity Operators is that "To compare the Memory Address of Two Objects".
=>In Python Programming, we have 2 Identity Operators. They are
1. is Operator
2. is not Operator
1. is Operator
-------------------------------------
Syntax: Object1 is Object2
180
=>Here "is" Operator Returns True Provided the Memory Address of Object1 and Object2 are Same.
=>Here "is" Operator Returns False Provided the Memory Address of Object1 and Object2 are Different.
-----------------------------------------------------------------------------------------------------
2. is not Operator
-----------------------------------------------------------------------------------------------------
Syntax: Object1 is not Object2
=>Here "is not" Operator Returns True Provided the Memory Address of Object1 and Object2 are Different.
=>Here "is not" Operator Returns False Provided the Memory Address of Object1 and Object2 are Same.
------------------------------------------------------------------------------------------------------------------------------------
Examples:
---------------------------------------------------------------------------------------------------------------------------
NOTE1: All Deep Copy Objects with "is" Operator returns True
NOTE2: All Deep Copy Objects with "is not" Operator returns False
NOTE3: All Shallow Copy Objects with "is" Operator returns False
NOTE4: All Shallow Copy Objects with "is not" Operator returns True
-----------
>>> lst1=[10,"RS"]
>>> lst2=lst1 # Deep Copy
>>> print(lst1,id(lst1))---------------[10, 'RS'] 2153932973440
>>> print(lst2,id(lst2))---------------[10, 'RS'] 2153932973440
>>> lst1 is lst2-------------------------True
>>> lst1 is not lst2--------------------False

>>> lst1=[10,"RS"]
>>> lst2=lst1.copy() # Shallow Copy
>>> print(lst1,id(lst1))-----------[10, 'RS'] 2153931658112
>>> print(lst2,id(lst2))-----------[10, 'RS'] 2153931508480
>>> lst1 is lst2--------------------False
>>> lst1 is not lst2---------------True
---------------------------------------------------------------------------------------------------------------------------------
Examples
--------------------------------------------------------------------------------------------------------------------------------------
>>> a=None

181
>>> b=None
>>> print(a,id(a))-------------None 140718855683792
>>> print(b,id(b))------------None 140718855683792
>>> a is b---------------------True
>>> a is not b---------------False
---------------------------------------
>>> d1={10:"Apple",20:"Mango"}
>>> d2={10:"Apple",20:"Mango"}
>>> print(d1,id(d1))-----------{10: 'Apple', 20: 'Mango'} 2153931585920
>>> print(d2,id(d2))-----------{10: 'Apple', 20: 'Mango'} 2153932971072
>>> d1 is d2------------------False
>>> d1 is not d2-------------True
-------------------------------------------------
>>> s1={10,20,30,40}
>>> s2={10,20,30,40}
>>> print(s1,id(s1))--------------{40, 10, 20, 30} 2153931553728
>>> print(s2,id(s2))--------------{40, 10, 20, 30} 2153931547232
>>> s1 is s2------------------------False
>>> s1 is not s2-------------------True
>>> fs1=frozenset(s1)
>>> fs2=frozenset(s2)
>>> print(fs1,id(fs1))-----------frozenset({40, 10, 20, 30}) 2153931553952
>>> print(fs2,id(fs2))-----------frozenset({40, 10, 20, 30}) 2153932207744
>>> fs1 is fs2--------------------False
>>> fs1 is not fs2---------------True
-------------------------------------------------------------------------------------------------------------------------------------
>>> t1=(10,20,30,40)
>>> t2=(10,20,30,40)
>>> print(t1,id(t1))--------------(10, 20, 30, 40) 2153931710736
>>> print(t2,id(t2))---------------(10, 20, 30, 40) 2153931711536
>>> t1 is t2--------------------False
>>> t1 is not t2--------------True
>>> lst1=[10,20,30,1.2]

182
>>> lst2=[10,20,30,1.2]
>>> print(lst1, id(lst1))----------[10, 20, 30, 1.2] 2153932973440
>>> print(lst2, id(lst2))---------[10, 20, 30, 1.2] 2153931658112
>>> lst1 is lst2-------------------False
>>> lst1 is not lst2--------------True
---------------------------------------------------------------------------------------------------------------------------------------
>>> r1=range(10,20)
>>> r2=range(10,20)
>>> print(r1,id(r1))-------------range(10, 20) 2153933009136
>>> print(r2,id(r2))-------------range(10, 20) 2153933008032
>>> r1 is r2------------------False
>>> r1 is not r2-------------True
------------------------
>>> ba1=bytearray([10,20,30])
>>> ba2=bytearray([10,20,30])
>>> print(ba1,id(ba1))------------bytearray(b'\n\x14\x1e') 2153931656816
>>> print(ba2,id(ba2))------------bytearray(b'\n\x14\x1e') 2153931506096
>>> ba1 is ba2--------------------False
>>> ba1 is not ba2---------------True
>>> ba1=bytes([10,20,30])
>>> ba2=bytes([10,20,30])
>>> print(ba1,id(ba1))------------b'\n\x14\x1e' 2153933008128
>>> print(ba2,id(ba2))------------b'\n\x14\x1e' 2153933009520
>>> ba1 is ba2---------------------False
>>> ba1 is not ba2---------------True
------------------------
If String Objects Contains Data with Same Meaning,Same Case and Same Order then Both String Obejcts
contains Same Address otherwise Contains Different Address.
-----------------
>>> s1="Rossum"
>>> s2="Rossum"
>>> print(s1,id(s1))-------------Rossum 2153931722208
>>> print(s2,id(s2))-------------Rossum 2153931722208

183
>>> s1 is s2----------------------True
>>> s1 is not s2----------------False
>>> s1="INDIA"
>>> s2="INDIA"
>>> s1 is s2----------------------True
>>> s1 is not s2----------------False
>>> s1="INDIA"
>>> s2="INDAI"
>>> print(s1,id(s1))------------INDIA 2153933008512
>>> print(s2,id(s2))------------INDAI 2153933009616
>>> s1 is s2----------------------False
>>> s1 is not s2-----------------True
---------------------------------------------------------------------------------------------------------------------------------------
>>> a=2+3j
>>> b=2+3j
>>> print(a,id(a))------------(2+3j) 2153931621264
>>> print(b,id(b))------------(2+3j) 2153931635728
>>> a is b----------------------False
>>> a is not b----------------True
---------------------
>>> a=True
>>> b=True
>>> print(a,id(a))---------------True 140718855683728
>>> print(b,id(b))--------------True 140718855683728
>>> a is b------------------------True
>>> a is not b-------------------False
-----------------------
>>> a=1.2
>>> b=1.2
>>> print(a,id(a))-------------1.2 2153931634608
>>> print(b,id(b))-------------1.2 2153931635728
>>> a is b-----------------------False
>>> a is not b------------------True

184
----------------------
>>> a=10
>>> b=10
>>> print(a,id(a))--------------10 140718856477400
>>> print(b,id(b))--------------10 140718856477400
>>> a is b--------------------True
>>> a is not b---------------False
>>> a=256
>>> b=256
>>> print(a,id(a))------------256 140718856485272
>>> print(b,id(b))------------256 140718856485272
>>> a is b----------------------True
>>> a is not b-----------------False
>>> a=0
>>> b=0
>>> print(a,id(a))---------------0 140718856477080
>>> print(b,id(b))--------------0 140718856477080
>>> a is b-----------------------True
>>> a is not b------------------False
----------------------------------------
>>> a=257
>>> b=257
>>> print(a,id(a))--------------257 2153931635952
>>> print(b,id(b))--------------257 2153931621040
>>> a is b------------------------False
>>> a is not b-------------------True
--------------------------------------------------
>>> a=-1
>>> b=-1
>>> print(a,id(a))-------------------1 140718856477048
>>> print(b,id(b))-------------------1 140718856477048
>>> a is b-----------------------------True
>>> a is not b------------------------False

185
>>> a=-5
>>> b=-5
>>> print(a,id(a))------------------ -5 140718856476920
>>> print(b,id(b))------------------ -5 140718856476920
>>> a is b----------------------True
>>> a is not b-----------------False
>>> a=-6
>>> b=-6
>>> print(a,id(a))------------ -6 2153931621040
>>> print(b,id(b))------------ -6 2153931635952
>>> a is b--------------------- False
>>> a is not b----------------- True
------------------------------------
Special Point
------------------------------------
>>> a,b=2000,2000
>>> print(a,id(a))-------------2000 2153931635984
>>> print(b,id(b))-------------2000 2153931635984
>>> a is b-----------------------True
>>> a is not b------------------False
-------------------------------
>>> a,b=1.2,1.2
>>> print(a,id(a))-------------1.2 2153931634608
>>> print(b,id(b))-------------1.2 2153931634608
>>> a is b----------------------True
>>> a is not b----------------False
-------------------------------------------
>>> lst1,lst2=[10,"RS"],[10,"RS"]
>>> print(lst1,id(lst1))-----------[10, 'RS'] 2153931508480
>>> print(lst2,id(lst2))-----------[10, 'RS'] 2153932973568

186
===============================================================
Python Ternary Operator
===============================================================
=>The Name of Python Ternary Operator is "if..else " Operator.
------------
Syntax: varname = Expression-1 if Test Condition else Expression-2
-----------
=>Here Test Condition can be either Relational OR Logical Expression and whose Result can be either True or
False.
=>If Test Condition Result is True then PVM Executes Expression-1 whose Result Placed in LHS Varname.
=>If Test Condition Result is False then PVM goes to else part and Executes Expression-2 whose Result Placed
in LHS Varname.
=>Hence in Python Ternary Operator, at any Point of Time PVM Executes either Expression-1 OR Expression-
2 and whose Result placed in LHS Varname.
==============================================================================

#Program for finding Biggest of Two Numbers


#BigTwoEx1.py
a=int(input("Enter Value of a:"))
b=int(input("Enter Value of b:"))
#Find Big of a and b
bv = a if a>b else b # Python Ternary Operator
print("Big({},{})={}".format(a,b,bv))

187
#Program for finding Biggest of Two Numbers and check for equality
#BigTwoEx2.py
a=int(input("Enter Value of a:")) # 10
b=int(input("Enter Value of b:")) # 10
res=a if a>b else b if b>a else "equal"
print("Big({},{})={}".format(a,b,res))
#Program for accepting Three Numerical Values and Find Biggest among them
#BigThreeEx1.py
a=int(input("Enter Value of a:")) # a=10
b=int(input("Enter Value of b:")) # b=10
c=int(input("Enter Value of c:"))# c=3
res=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 are Equal"
print("Big({},{},{})={}".format(a,b,c,res))
#Program for accepting Three Numerical Values and Find Biggest among them
#BigThreeEx1.py
a=int(input("Enter Value of a:")) # a=10
b=int(input("Enter Value of b:")) # b=10
c=int(input("Enter Value of c:"))# c=3
res=a if b<=a>c else b if a<b>=c else c if a<=c>b else "All are Equal"
print("Big({},{},{})={}".format(a,b,c,res))
#Program for accepting a word / Value and decide weather It is Palindrome or not
#PalindromeEx.py
value=input("Enter a Value:") # LIRIL
res="Palindrome" if value==value[::-1] else "Not Palindrome"
print("{} is {}".format(value,res))
#Program for accepting a word and Decide whether It is Vowel Word or not
#VowelWordEx.py
#Example Apple---Vowel Word try---Not Vowel Word
word=input("Enter Any Word:") # Apple
res="Vowel Word" if 'a' in word or 'e' in word or 'i' in word or 'o' in word or 'u' in word else "Not Vowel
Word"
print("{} is {}".format(word,res)

188
========================================================
Flow Control Statements in Python
(OR)
Control Structures in Python----10 Days
========================================================
Index
--------------
=>Purpose of Flow Control Statements
=>Types of Flow Control Statements
I. Conditional OR Selection OR Branching Statements
1. simple if statement
2. if..else statement
3. if..elif..else statement
4. match case statement
=>Programming Examples
II. Looping OR Iterating OR Repetative Statements
1. while loop OR while .. else loop
2. for loop OR for ...else loop
=>Programming Examples
III. Transfer Flow Statements
1. break
2. continue
3. pass
4. retrun
=>Programming Examples
=>Combined Programming Examples in Conditional, Looping and Transfer Flow Statements
--------------------------------------------------------------------------
=>Inner OR Nested Loops
a) for loop in for loop
b) while loop in while
c) for loop in while loop
d) while in for loop
=>Programming Examples

189
=======================================================
Flow Control Statements in Python
=======================================================
=>The purpose of Flow Control Statements in Python is that " To Perform Certain Operation(X-Operation in the
case of True OR Y-Operation in the Case of False) Only Once OR To Perform Certain Operation Repeatedly
for Finite Number of Times Until Test Condition becomes False".
=>In Python Programming, we have 3 Types of Flow Control Statements.
1. Conditional OR Selection OR Branching Statements
2. Looping OR Iterating OR Repetative Statements
3. Transfer Flow Statements
========================================================
1. Conditional OR Selection OR Branching Statements
========================================================
=>The purpose of Conditional OR Selection OR Branching Statements is that "To Perform X-Operation in the
Case of True OR Y-Operation in the Case of False Only Once."
=>In Python Programming, we have 4 Tupes of Conditional OR Selection OR Branching Statements. They are
1. simple if statement
2. if..else statement
3. if..elif..else statement
4. match case statement
============================================================================

190
#moviee.py
tkt=input("Do u have a Ticket(yes/no):")
if(tkt=="yes"):
print("Enter into theater")
print("Watch the Moviee")
print("Eat Pop Corn!!!")
print("Goto Home")
#Program for Accepting Two Numerical value and Decide Biggest and Check for equality also
#SimpleIFStmtEx1.py
a=float(input("Enter First Value:"))
b=float(input("Enter Second Value:"))
if(a>b):
print("Big({},{})={}".format(a,b,a))
if(b>a):
print("Big({},{})={}".format(a,b,b))
if(a==b):
print("Both the Value are Equal")
print("Program Execution completed!!!")
#Program for Accepting a Number and Decide whether It is +ve or -ve or Zero
#SimpleIFStmtEx2.py
n=float(input("Enter Any 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))
#SimpleIFStmtEx3.py
n=float(input("Enter any Number:"))
if(n<=0):
print("{} is Invalid Input".format(n))
if(n%2==0) and (n>0):
print("{} is EVEN".format(n))
191
if(n%2!=0) and (n>0):
print("{} is ODD".format(n))
#Program for accepting a Digit and display Digit Name
#SimpleIFStmtEx3.py
d=int(input("Enter a Digit:")) # d=0 1 2 3 4 5 6 7 8 9
if(d==0):
print("{} is Zero".format(d))
if(d==1):
print("{} is One".format(d))
if(d==2):
print("{} is Two".format(d))
if(d==3):
print("{} is Three".format(d))
if(d==4):
print("{} is Four".format(d))
if(d==5):
print("{} is Five".format(d))
if(d==6):
print("{} is Six".format(d))
if(d==7):
print("{} is Seven".format(d))
if(d==8):
print("{} is Eight".format(d))
if(d==9):
print("{} is Nine".format(d))

192
#Program for Accepting Two Numerical value and Decide Biggest
#IfElseStmtEx1.py
a=float(input("Enter First Value:"))
b=float(input("Enter Second Value:"))
if(a>b):
print("Big({},{})={}".format(a,b,a))
else:
print("Big({},{})={}".format(a, b, b))
print("Program Execution Completed")
#Program for Accepting Two Numerical value and Decide Biggest and Check for equality

also
#IfElseStmtEx2.py
a=float(input("Enter First Value:"))#a=10
b=float(input("Enter Second Value:"))#b=10
if(a>b): # Here Line No: 5 to 6 Represent outer if..else
print("Big({},{})={}".format(a,b,a))
else:

193
if(b>a): # Here Line No: 8 to 10 Represent Inner if..else
print("Big({},{})={}".format(a, b, b))
else:
print("Both Values are Equal")
print("other stmts--inner if..else stmt")
print("other stmts--outer if..else stmt")
#Program for accepting a Digit and display Digit NametEx2.py
#IfElseStmt3.py
d=int(input("Enter a Digit:")) # d=0 1 2 3 4 5 6 7 8 9
if(d==0):
print("{} is ZERO".format(d))
else:
if(d==1):
print("{} is ONE".format(d))
else:
if (d == 2):
print("{} is TWO".format(d))
else:
if (d == 3):
print("{} is THREE".format(d))
else:
if (d == 4):
print("{} is FOUR".format(d))
else:
if (d == 5):
print("{} is FIVE".format(d))
else:
if (d == 6):
print("{} is SIX".format(d))
else:
if (d == 7):
print("{} is SEVEN".format(d))
else:
194
if (d == 8):
print("{} is EIGHT".format(d))
else:
if (d == 9):
print("{} is NINE".format(d))
else:
print("{} is not Digit".format(d))

195
#Program for Accepting Two Numerical value and Decide Biggest and Check for equality
also
#IfElifElseStmtEx1.py
a=float(input("Enter First Value:")) # 10
b=float(input("Enter Second Value:")) # 3
if(a>b):
print("Big({},{})={}".format(a,b,a))
elif(b>a):
print("Big({},{})={}".format(a,b,b))
elif(a==b):
print("Both the Value are Equal")
else:
print("i am from else Part")
print("Program Execution completed!!!")

196
##Program for accepting a Digit and display Digit Name
#IfElifElseStmtEx2.py
d=int(input("Enter a Digit:")) # d=0 1 2 3 4 5 6 7 8 9
if(d==0):
print("{} is Zero".format(d))
elif(d==1):
print("{} is One".format(d))
elif(d==2):
print("{} is Two".format(d))
elif(d==3):
print("{} is Three".format(d))
elif(d==4):
print("{} is Four".format(d))
elif(d==5):
print("{} is Five".format(d))
elif(d==6):
print("{} is Six".format(d))
elif(d==7):
print("{} is Seven".format(d))
elif(d==8):
print("{} is Eight".format(d))
elif(d==9):
print("{} is Nine".format(d))
elif(d in range(-1,-10,-1)):
print("{} is -Ve Digit".format(d))
elif(d<0):
print("{} is -ve Number".format(d))
else:
print("{} is +Ve Number".format(d))
print("Program Execution Completed")

197
#Program for accepting a Digit and display Digit Name
#IfElifElseStmtEx3.py
d=int(input("Enter Digit:"))
dobj={0:"ZERO",1:"ONE",2:"TWO",3:"THREE",4:"FOUR",5:"FIVE",6:"SIX",7:"SEVEN",8:"EIGHT
",9:"NINE"}
res=dobj.get(d) if dobj.get(d)!=None else "-Ve Digit" if d in range(-1,-10,-1) else "+Ve Number" if d>0
else "-Ve Number"
print("{} is {}".format(d,res))
#Program for accepting a Digit and display Digit Name
#IfElifElseStmtEx3.py
d=int(input("Enter Digit:"))
dobj={0:"ZERO",1:"ONE",2:"TWO",3:"THREE",4:"FOUR",5:"FIVE",6:"SIX",7:"SEVEN",8:"EIGHT
",9:"NINE"}
print("{} is {}".format(d,dobj.get(d) if dobj.get(d)!=None else "-Ve Digit" if d in range(-1,-10,-1) else
"+Ve Number" if d>0 else "-Ve Number"))
#Program for accepting a Digit and display Digit Name
#IfElifElseStmtEx3.py
d=int(input("Enter Digit:"))
dobj={0:"ZERO",1:"ONE",2:"TWO",3:"THREE",4:"FOUR",5:"FIVE",6:"SIX",7:"SEVEN",8:"EIGHT",9:"NI
NE"}
print("{} is {}".format(d,dobj.get(d) if dobj.get(d)!=None else "-Ve Digit" if d in range(-1,-10,-1) else "+Ve
Number" if d>0 else "-Ve Number"))
================================================================
match case statement (Python3.10 Version onwards)
================================================================
=>match case statement is one of conditional statement available from Python3.10 Version onwards.
=>The purpose of match case statement is that "To Deal with Pre-Designed Conditions OR Menu Driven
Applications".
=>The Menu Driven Applications contains Pre-Designed Condition
Syntax:
match(Choice Expr):
case Choice Label1:
Block of Stements-1
198
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(proposed)
=>"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 to 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
Staements 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 ( | ) .
--------------------------------------------------------------------------------------------------------------------------------------
Examples
---------------------

199
****************************************************************************
Arithmetic Operations
****************************************************************************
1. Addition
2. Substraction
3. Multiplication
4. Division
5. Modulo Division
6. Exponentiation
7. Exit
****************************************************************************
Enter Ur Choice:
***************************************************************************

*********************************************************************
Area of Different Figures
*********************************************************************
R. Rectangle
S. Square
C. Circle
T. Triangle
E. Exit
*********************************************************************
Enter Ur Choice:
*********************************************************************
Home Work---student must do

*********************************************************************
Temprature Conversion Calculator
*********************************************************************
1. F to C
2. F to K
3. C to F
200
4. C to K
5. K to F
6. K to C
7. Exit
*********************************************************************
Enter Ur Choice: 1
*********************************************************************
Fahrenheit to Celcius: C = (F-32) (5/9)
Fahrenheit to Kelvin: K = (F-32) (5/9) + 273.15
Celsius to Fahrenheit: F = C(9/5) + 32
Celsius to Kelvin: K = C + 273.15
Kelvin to Celcius: C = K - 273.15
Kelvin to Fahrenheit: F = (K-273.15) (9/5) + 32

#MatchCaseEx1.py
import sys
s="""*********************************************************************
Temprature Conversion Calculator
*********************************************************************
1. F to C
2. F to K
3. C to F
4. C to K
5. K to F
6. K to C
7. Exit
*********************************************************************"""
print(s)
ch=int(input("Enter Ur Choice:"))
print("*********************************************************************")
match(ch):
case 1:
F=float(input("Enter Temp. Value in Trems of F to get Temp in terms of C:"))
201
C = (F - 32)*(5 / 9)
print("Temp in C=",C)
case 2:
F = float(input("Enter Temp. Value in Trems of F to get Temp in terms of K:"))
K = (F - 32)*(5 / 9) + 273.15
print("Temp in K=", K)
case 3:
C = float(input("Enter Temp. Value in Trems of C to get Temp in terms of F:"))
F = C*(9 / 5) + 32
print("Temp in F=",F)
case 4:
C = float(input("Enter Temp. Value in Trems of C to get Temp in terms of K:"))
K = C + 273.15
print("Temp in K=", K)
case 5:
K = float(input("Enter Temp. Value in Trems of K to get Temp in terms of F:"))
F = (K - 273.15)*(9 / 5) + 32
print("Temp in F=",F)
case 6:
K = float(input("Enter Temp. Value in Trems of K to get Temp in terms of C:"))
C = K - 273.15
print("Temp in C=", C)
case 7:
print("Thx for using Program")
sys.exit()
case _:
print("Ur Selection of Operation Wrong!!!--try again")
print("Program Execution Completed")

====================================
String Handling Part-2
====================================
=>We know that, on str data we can perform Both Indexing and Slicing Operations.

202
=>By using Indexing Concept, we can get Single Value from str object.
=>By using Slicing Concept, we can get Range of Values from str object.
=>Along with Indexing and Slicing Operations, we can perform Various Operations on str data 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'>

203
--------------------------------------------------------------------------------------------------------------------------------
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"
204
>>> s.index("p")------------------0
>>> s.index("y")-------------------1
>>> s.index("o")-----------------4
>>> s.index("n")----------------5
>>> s.index("K")----------------ValueError: substring not found
--------------------------------------------------------------------------------------------------------------------------------
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'
205
--------------------------------------------------------------------------------------------------------------------------------
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
206
>>> 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"
207
>>> 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()
--------------------------------------------------------------------------------------------------------------------------------

208
=>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"
209
>>> 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"

210
>>> 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=" "

211
>>> k.join(t)
'Rossum is Father of Python'
---------------------------------------------------------------------------------------------------------------------
14) startswith():
----------------------
=>The startswith() Function returns True if the string starts with the specified value, otherwise False.
Examples:
-------------------
>>>s="Python is an oop lang"
>>>s.startswith("Python")------------True
>>>s.startswith("python")------------False
---------------------------------------------------------------------------------------------------------------------
15) endswith():
----------------------
=>The endswith() Function returns True if the string ends with the specified value, otherwise False.
Examples:
-------------------
>>>s="Python is an oop lang"
>>>s.endswith("Python")------------False
>>>s.endswith("lang")------------True
---------------------------------------------------------------------------------------------------------------------
16) swapcase()
----------------------------
=>Make the lower case letters upper case and the upper case letters lower case:
Examples:
>>>s="PyThOn"
>>>s.swapcase()--------pYtHoN
---------------------------------------------------------------------------------------------------------------------
MISc Examples
---------------------------------------------------------------------------------------------------------------------
>>> s="python"
>>> s.capitalize()
'Python'
212
>>> s="python is an oop lang"
>>> s.capitalize()
'Python is an oop lang'
>>> s="python is an oop lang.python is also fun lang"
>>> s.capitalize()
'Python is an oop lang.python is also fun lang'
>>>
>>> s="python"
>>> s.title()
'Python'
>>> s="python is an oop lang"
>>> s.title()
'Python Is An Oop Lang'
>>> s="python is an oop lang.python is also fun lang"
>>> s.title()
'Python Is An Oop Lang.Python Is Also Fun Lang'
>>> s="PYTHON"
>>> s.title()
'Python'
>>> s="PYTHON"
>>> s.capitalize()
'Python'
>>>
>>>
>>> s="PyThOn"
>>> s.swapcase()
'pYtHoN'
>>> s="PYThon"
>>> s.swapcase()
'pytHON'
>>> s="PYTHON"
>>> s.swapcase()
'python'

213
>>> s="python"
>>> s.swapcase()
'PYTHON'
>>> s="12345"
>>> s.swapcase()
'12345'
>>> s="Python3.11"
>>> s.swapcase()
'pYTHON3.11'
>>> s="$%^&*()"
>>> s.swapcase()
'$%^&*()'
>>> s="PYTHON"
>>> s.lower()
'python'
>>> s="PYTHON"
>>> s.swapcase()
'python'
>>> s="PYThon"
>>> s.swapcase()
'pytHON'
>>> s.lower()
'python'
>>>
>>> s="python"
>>> s.lower()
'python'
>>> s.swapcase()
'PYTHON'
>>> s="python"
>>> s.upper()
'PYTHON'
>>> s="PYThon"

214
>>> s.upper()
'PYTHON'
>>> s="PYThon"
>>> s.lower()
'python'
>>>
>>> s="PYTHON"
>>> s.isupper()
True
>>> s="python"
>>> s.isupper()
False
>>> s="PYTHon"
>>> s.isupper()
False
>>> s="java"
>>> s.islower()
True
>>> s="JAva"
>>> s.islower()
False
>>> s.isupper()
False
>>> s="1234"
>>> s.islower()
False
>>> s.isupper()
False
>>>
>>>
>>> s="python"
>>> s.index('p')
0

215
>>> s.index('o')
4
>>> s.index('k')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> s.index('2')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> s="python"
>>> s.index('thon')
2
>>> s.index('khon')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> s="python is an oop lang"
>>> s.index('is')
7
>>> s.index('o')
4
>>> s.index('an')
10
>>> s.index('10')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> s.index("""an""")
10
>>> s="Apple"
>>> s.isalpha()
True

216
>>> s="Apple123"
>>> s.isalpha()
False
>>> s="Ap ple"
>>> s.isalpha()
False
>>> s="123"
>>> s.isalpha()
False
>>> s="Pyth$on"
>>> s.isalpha()
False
>>> s="PYTHON311"
>>> s.isalnum()
True
>>> s="PYTHON"
>>> s.isalnum()
True
>>> s="311"
>>> s.isalnum()
True
>>> s="PYT HON"
>>> s.isalnum()
False
>>> s="PYTHON3.11"
>>> s.isalnum()
False
>>> s="PYTH$on"
>>> s.isalnum()
False
>>> s="123.56"
>>> s.isalnum()
False

217
>>> s="123"
>>> s.isnumeric()
True
>>> s="123.45"
>>> s.isnumeric()
False
>>> s="123$23"
>>> s.isnumeric()
False
>>> s="2"
>>> s.isnumeric()
True
>>> s="32"
>>> s.isdigit()
True
>>> s="PYTHON311"
>>> s.isdigit()
False
>>> s=" "
>>> s.isspace()
True
>>> s="123 456"
>>> s.isspace()
False
>>> s=""
>>> s.isspace()
False
>>> s=" "
>>> s.isspace()
True
>>>
>>> s="Apple is in red"
>>> s.split()

218
['Apple', 'is', 'in', 'red']
>>> x=s.split()
>>> print(x,type(x))
['Apple', 'is', 'in', 'red'] <class 'list'>
>>> len(x)
4
>>> s="08-07-2023"
>>> print(s)
08-07-2023
>>> x=s.split("-")
>>> print(x)
['08', '07', '2023']
>>> print("Day=",x[0])
Day= 08
>>> print("Month=",x[1])
Month= 07
>>> print("Year=",x[2])
Year= 2023
>>> s="Apple#Mango#kiwi-Banana"
>>> print(s)
Apple#Mango#kiwi-Banana
>>> x=s.split("#")
>>> print(x)
['Apple', 'Mango', 'kiwi-Banana']
>>> y=s.split("-")
>>> print(y)
['Apple#Mango#kiwi', 'Banana']
>>> y[0]
'Apple#Mango#kiwi'
>>> y[0].split("#"]
File "<stdin>", line 1
y[0].split("#"]
^

219
SyntaxError: closing parenthesis ']' does not match opening parenthesis '('
>>> y[0].split("#")
['Apple', 'Mango', 'kiwi']
>>> y[0:1]=y[0].split("#")
>>> print(y)
['Apple', 'Mango', 'kiwi', 'Banana']
>>>
>>> s="123$456$678$156$"
>>> print(s)
123$456$678$156$
>>> s.split("$")
['123', '456', '678', '156', '']
>>> s="123$456$678$156"
>>> s.split("$")
['123', '456', '678', '156']
>>>
>>>
>>>
>>> lst=["apple","mango","kiwi","guava"]
>>> print(lst,type(lst)
... )
['apple', 'mango', 'kiwi', 'guava'] <class 'list'>
>>> k=""
>>> k.join(lst)
'applemangokiwiguava'
>>> print(k)

>>> k
''
>>> lst=["apple","mango","kiwi","guava"]
>>> print(lst,type(lst))
['apple', 'mango', 'kiwi', 'guava'] <class 'list'>
>>> k=""

220
>>> k=k.join(lst)
>>> print(k)
applemangokiwiguava
>>> k
'applemangokiwiguava'
>>>
>>> lst=["apple","mango","kiwi","guava"]
>>> print(lst,type(lst))
['apple', 'mango', 'kiwi', 'guava'] <class 'list'>
>>> k=" "
>>> k=k.join(lst)
>>> print(k)
apple mango kiwi guava
>>> lst=["Python","is","an","oop","lang"]
>>> k=" "
>>> k=k.join(lst)
>>> print(k)
Python is an oop lang
>>> print(k,type(k))
Python is an oop lang <class 'str'>
>>> k.split()
['Python', 'is', 'an', 'oop', 'lang']
>>> s=" "
>>> s.isnull()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'isnull'
>>>
>>>
>>> s="Python is an oop lang"
>>> print(s)
Python is an oop lang
>>> s.startswith("Python")

221
True
>>> s.startswith("Pyt")
True
>>> s.startswith("p")
False
>>> s.startswith("p".upper())
True
>>> s.startswith("lang")
False
>>> s="Python is an oop lang"
>>> print(s)
Python is an oop lang
>>> s.endswith("Python")
False
>>> s.endswith("lang")
True
>>> s.endswith("la")
False
>>> s.endswith("ng")
True
>>> s.endswith("n")
False
>>> s.endswith("g")
True
>>> s.endswith("lang".upper())
False
>>>
====================================
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.
--------------------------------------------------------------------------------------------------------------------------------
222
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()

223
------------------
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
--------------------------------------------------------------------------------------------------------------------------------
4) upper()

224
--------------------------------------------------------------------------------------------------------------------------------
=>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()
225
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
226
--------------------------------------------------------------------------------------------------------------------------------
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="#$%^@"
227
>>> 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"
228
>>> 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()
-------------------------------------------------------------------------------------------------------------------------------

229
=>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("#")

230
>>> 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'
---------------------------------------------------------------------------------------------------------------------
14) startswith():
----------------------
=>The startswith() Function returns True if the string starts with the specified value, otherwise False.
Examples:
-------------------
231
>>>s="Python is an oop lang"
>>>s.startswith("Python")------------True
>>>s.startswith("python")------------False
---------------------------------------------------------------------------------------------------------------------
15) endswith():
----------------------
=>The endswith() Function returns True if the string ends with the specified value, otherwise False.
Examples:
-------------------
>>>s="Python is an oop lang"
>>>s.endswith("Python")------------False
>>>s.endswith("lang")------------True
---------------------------------------------------------------------------------------------------------------------
16) swapcase()
----------------------------
=>Make the lower case letters upper case and the upper case letters lower case:
Examples:
>>>s="PyThOn"
>>>s.swapcase()--------pYtHoN
---------------------------------------------------------------------------------------------------------------------
MISc Examples
---------------------------------------------------------------------------------------------------------------------
>>> s="python"
>>> s.capitalize()
'Python'
>>> s="python is an oop lang"
>>> s.capitalize()
'Python is an oop lang'
>>> s="python is an oop lang.python is also fun lang"
>>> s.capitalize()
'Python is an oop lang.python is also fun lang'
>>>
>>> s="python"
232
>>> s.title()
'Python'
>>> s="python is an oop lang"
>>> s.title()
'Python Is An Oop Lang'
>>> s="python is an oop lang.python is also fun lang"
>>> s.title()
'Python Is An Oop Lang.Python Is Also Fun Lang'
>>> s="PYTHON"
>>> s.title()
'Python'
>>> s="PYTHON"
>>> s.capitalize()
'Python'
>>>
>>>
>>> s="PyThOn"
>>> s.swapcase()
'pYtHoN'
>>> s="PYThon"
>>> s.swapcase()
'pytHON'
>>> s="PYTHON"
>>> s.swapcase()
'python'
>>> s="python"
>>> s.swapcase()
'PYTHON'
>>> s="12345"
>>> s.swapcase()
'12345'
>>> s="Python3.11"
>>> s.swapcase()

233
'pYTHON3.11'
>>> s="$%^&*()"
>>> s.swapcase()
'$%^&*()'
>>> s="PYTHON"
>>> s.lower()
'python'
>>> s="PYTHON"
>>> s.swapcase()
'python'
>>> s="PYThon"
>>> s.swapcase()
'pytHON'
>>> s.lower()
'python'
>>>
>>> s="python"
>>> s.lower()
'python'
>>> s.swapcase()
'PYTHON'
>>> s="python"
>>> s.upper()
'PYTHON'
>>> s="PYThon"
>>> s.upper()
'PYTHON'
>>> s="PYThon"
>>> s.lower()
'python'
>>>
>>> s="PYTHON"
>>> s.isupper()

234
True
>>> s="python"
>>> s.isupper()
False
>>> s="PYTHon"
>>> s.isupper()
False
>>> s="java"
>>> s.islower()
True
>>> s="JAva"
>>> s.islower()
False
>>> s.isupper()
False
>>> s="1234"
>>> s.islower()
False
>>> s.isupper()
False
>>>
>>>
>>> s="python"
>>> s.index('p')
0
>>> s.index('o')
4
>>> s.index('k')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> s.index('2')
Traceback (most recent call last):

235
File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> s="python"
>>> s.index('thon')
2
>>> s.index('khon')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> s="python is an oop lang"
>>> s.index('is')
7
>>> s.index('o')
4
>>> s.index('an')
10
>>> s.index('10')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> s.index("""an""")
10
>>> s="Apple"
>>> s.isalpha()
True
>>> s="Apple123"
>>> s.isalpha()
False
>>> s="Ap ple"
>>> s.isalpha()
False
>>> s="123"
>>> s.isalpha()

236
False
>>> s="Pyth$on"
>>> s.isalpha()
False
>>> s="PYTHON311"
>>> s.isalnum()
True
>>> s="PYTHON"
>>> s.isalnum()
True
>>> s="311"
>>> s.isalnum()
True
>>> s="PYT HON"
>>> s.isalnum()
False
>>> s="PYTHON3.11"
>>> s.isalnum()
False
>>> s="PYTH$on"
>>> s.isalnum()
False
>>> s="123.56"
>>> s.isalnum()
False
>>> s="123"
>>> s.isnumeric()
True
>>> s="123.45"
>>> s.isnumeric()
False
>>> s="123$23"
>>> s.isnumeric()

237
False
>>> s="2"
>>> s.isnumeric()
True
>>> s="32"
>>> s.isdigit()
True
>>> s="PYTHON311"
>>> s.isdigit()
False
>>> s=" "
>>> s.isspace()
True
>>> s="123 456"
>>> s.isspace()
False
>>> s=""
>>> s.isspace()
False
>>> s=" "
>>> s.isspace()
True
>>>
>>> s="Apple is in red"
>>> s.split()
['Apple', 'is', 'in', 'red']
>>> x=s.split()
>>> print(x,type(x))
['Apple', 'is', 'in', 'red'] <class 'list'>
>>> len(x)
4
>>> s="08-07-2023"
>>> print(s)

238
08-07-2023
>>> x=s.split("-")
>>> print(x)
['08', '07', '2023']
>>> print("Day=",x[0])
Day= 08
>>> print("Month=",x[1])
Month= 07
>>> print("Year=",x[2])
Year= 2023
>>> s="Apple#Mango#kiwi-Banana"
>>> print(s)
Apple#Mango#kiwi-Banana
>>> x=s.split("#")
>>> print(x)
['Apple', 'Mango', 'kiwi-Banana']
>>> y=s.split("-")
>>> print(y)
['Apple#Mango#kiwi', 'Banana']
>>> y[0]
'Apple#Mango#kiwi'
>>> y[0].split("#"]
File "<stdin>", line 1
y[0].split("#"]
^
SyntaxError: closing parenthesis ']' does not match opening parenthesis '('
>>> y[0].split("#")
['Apple', 'Mango', 'kiwi']
>>> y[0:1]=y[0].split("#")
>>> print(y)
['Apple', 'Mango', 'kiwi', 'Banana']
>>>
>>> s="123$456$678$156$"

239
>>> print(s)
123$456$678$156$
>>> s.split("$")
['123', '456', '678', '156', '']
>>> s="123$456$678$156"
>>> s.split("$")
['123', '456', '678', '156']
>>>
>>>
>>>
>>> lst=["apple","mango","kiwi","guava"]
>>> print(lst,type(lst)
... )
['apple', 'mango', 'kiwi', 'guava'] <class 'list'>
>>> k=""
>>> k.join(lst)
'applemangokiwiguava'
>>> print(k)

>>> k
''
>>> lst=["apple","mango","kiwi","guava"]
>>> print(lst,type(lst))
['apple', 'mango', 'kiwi', 'guava'] <class 'list'>
>>> k=""
>>> k=k.join(lst)
>>> print(k)
applemangokiwiguava
>>> k
'applemangokiwiguava'
>>>
>>> lst=["apple","mango","kiwi","guava"]
>>> print(lst,type(lst))

240
['apple', 'mango', 'kiwi', 'guava'] <class 'list'>
>>> k=" "
>>> k=k.join(lst)
>>> print(k)
apple mango kiwi guava
>>> lst=["Python","is","an","oop","lang"]
>>> k=" "
>>> k=k.join(lst)
>>> print(k)
Python is an oop lang
>>> print(k,type(k))
Python is an oop lang <class 'str'>
>>> k.split()
['Python', 'is', 'an', 'oop', 'lang']
>>> s=" "
>>> s.isnull()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'isnull'
>>>
>>>
>>> s="Python is an oop lang"
>>> print(s)
Python is an oop lang
>>> s.startswith("Python")
True
>>> s.startswith("Pyt")
True
>>> s.startswith("p")
False
>>> s.startswith("p".upper())
True
>>> s.startswith("lang")

241
False
>>> s="Python is an oop lang"
>>> print(s)
Python is an oop lang
>>> s.endswith("Python")
False
>>> s.endswith("lang")
True
>>> s.endswith("la")
False
>>> s.endswith("ng")
True
>>> s.endswith("n")
False
>>> s.endswith("g")
True
>>> s.endswith("lang".upper())
False
>>>
Examples window on String handling-2
---------------------------------------------------------
capitalize() and title()
---------------------------------------------------------
>>> s="python"
>>> print(s)-------------------python
>>> s.capitalize()-----------'Python'
>>> print(s)-----------------python
>>> s="python"
>>> print(s)----------------python
>>> s=s.capitalize()
>>> print(s)
Python
>>>
242
>>>
>>> s="python"
>>> print(s)
python
>>> s.title()
'Python'
>>>
>>> s="python is an oop lang"
>>> print(s)
python is an oop lang
>>> s.capitalize()
'Python is an oop lang'
>>> print(s)
python is an oop lang
>>> s.title()
'Python Is An Oop Lang'
>>>
>>> s="Python IS AN OOP LANG"
>>> print(s)
Python IS AN OOP LANG
>>> s.capitalize()
'Python is an oop lang'
>>> s="Python IS AN OOP LANG"
>>> print(s)
Python IS AN OOP LANG
>>> s.title()
'Python Is An Oop Lang'
>>> s="python developed guio van rossum.python is an oop lang"
>>> print(s)
python developed guio van rossum.python is an oop lang
>>> s.capitalize()
'Python developed guio van rossum.python is an oop lang'
>>> print(s)

243
python developed guio van rossum.python is an oop lang
>>> s.title()
'Python Developed Guio Van Rossum.Python Is An Oop Lang'
----------------------------------------------------------------------------------------------------------------------
count()
----------------------------------------------------------------------------------------------------------------------
>>> s="MISSISSIPPI"
>>> print(s)---------------MISSISSIPPI
>>> s.count("M")
1
>>> s.count("S")
4
>>> s.count("P")
2
>>> s.count("I")
4
>>> s=123321456234123412
>>> print(s,type(s))--------123321456234123412 <class 'int'>
>>> s1=str(s)
>>> print(s1,type(s1))--------123321456234123412 <class 'str'>
>>> s1.count(1)--------------TypeError: must be str, not int
>>> s1.count('1')-----------4
>>> s1.count('2')-----------5
>>> s1.count(str(3))-------4
>>> len("MISSISSIPPI")------11
>>> "MISSISSIPPI".count("I")-----4
>>> s="123321456234123412"
>>> s.count("1")----------4
>>> len(s)-------------------18
-------------------------------------------------------------------------------
swapcase()
-------------------------------------------------------------------------------
>>> s="PyThOn"
244
>>> print(s)
PyThOn
>>> s.swapcase()
'pYtHoN'
>>> s="PYTHON"
>>> print(s)
PYTHON
>>> s.swapcase()
'python'
>>> s="python"
>>> print(s)
python
>>> s.swapcase()
'PYTHON'
>>> s="PYThon"
>>> print(s)
PYThon
>>> s.swapcase()
'pytHON'
>>> s="12345"
>>> print(s)
12345
>>> s.swapcase()
'12345'
>>> s="PyTHOn3.12"
>>> print(s)
PyTHOn3.12
>>> s.swapcase()
'pYthoN3.12'
------------------------------------------------------------------------------------------------------
upper() and lower()
-----------------------------------------------------------------------------------------------------
>>> s="python"

245
>>> print(s)
python
>>> s.upper()
'PYTHON'
>>> s="PYThon"
>>> print(s)
PYThon
>>> s.upper()
'PYTHON'
>>> print(s)
PYThon
>>> s.swapcase()
'pytHON'
>>>
>>> s="python"
>>> print(s)
python
>>> s.swapcase()
'PYTHON'
>>> print(s)
python
>>> s.upper()
'PYTHON'
>>> s="PYTHON"
>>> print(s)
PYTHON
>>> s.lower()
'python'
>>> print(s)
PYTHON
>>> s.swapcase()
'python'
>>> s="PYThon"

246
>>> print(s)
PYThon
>>> s.lower()
'python'
>>> print(s)
PYThon
>>> s.swapcase()
'pytHON'
----------------------------------------------------------------------------------------------
isupper() and islower()
----------------------------------------------------------------------------------------------
>>> s="PYTHON"
>>> print(s)
PYTHON
>>> s.isupper()
True
>>> s.islower()
False
>>> s="python"
>>> print(s)
python
>>> s.isupper()
False
>>> s.islower()
True
>>> s="PYThon"
>>> print(s)
PYThon
>>> s.isupper()
False
>>> s.islower()
False
>>> s="123#$%%"

247
>>> print(s)
123#$%%
>>> s.isupper()
False
>>> s.islower()
False
>>> s="P1234"
>>> print(s)
P1234
>>> s.isupper()
True
>>> s.islower()
False
>>> s="123p456"
>>> s.islower()
True
>>> s.isupper()
False
-------------------------------------------------------------------------------------------------------------
isdigit()
-------------------------------------------------------------------------------------------------------------
>>> s="123"
>>> print(s)
123
>>> s.isdigit()
True
>>> s="Python123"
>>> s.isdigit()
False
>>> s="12.34"
>>> s.isdigit()
False
-----------------------------------------------------------------------------------------------------------

248
isalpha()
----------------------------------------------------------------------------------------------------------
>>> s="python"
>>> print(s)------------python
>>> s.isalpha()-------True
>>> s="python3.10"
>>> s.isalpha()
False
>>> s="1234"
>>> s.isalpha()
False
>>> s="Python Prog"
>>> s.isalpha()
False
>>> s="Guido Van Rossum"
>>> s.isalpha()
False
-----------------------------------------------------------------------------
isalnum()
-----------------------------------------------------------------------------
>>> s="Python312"
>>> s.isalnum()
True
>>> s="123Java"
>>> s.isalnum()
True
>>> s="Python"
>>> s.isalnum()
True
>>> s="123"
>>> s.isalnum()
True
>>> s="Python3.12"
249
>>> s.isalnum()
False
>>> s="Python 312"
>>> s.isalnum()
False
-----------------------------------------------------------------------------------------------------------
isspace()
-----------------------------------------------------------------------------------------------------------
>>> s=" "
>>> s.isspace()
True
>>> s=""
>>> s.isspace()
False
>>> s="python 123"
>>> s.isspace()
False
>>> s="123 456 789"
>>> s.isspace()
False
----------------------------------------------------------------------------------------------------------
index()
----------------------------------------------------------------------------------------------------------
>>> s="PYTHON"
>>> s.index("P")
0
>>> s="RADAR"
>>> s.index("R")
0
>>> s="MISSISSIPPI"
>>> s.index("I")
1
>>> for ind,ch in enumerate(s):
250
... print(ind,"--->",ch)
...
0 ---> M
1 ---> I
2 ---> S
3 ---> S
4 ---> I
5 ---> S
6 ---> S
7 ---> I
8 ---> P
9 ---> P
10 ---> I
>>> for ind,ch in enumerate(s):
... if(ch=="I"):
... print(ind,"--->",ch)
...
1 ---> I
4 ---> I
7 ---> I
10 ---> I
---------------------------------------------------------------------------------------------------------------------------------------
split() and split("delimeter")
---------------------------------------------------------------------------------------------------------------------------------------
>>> s="Python is an oop lang"
>>> x=s.split()
>>> print(x,type(x))
['Python', 'is', 'an', 'oop', 'lang'] <class 'list'>
>>> len(x)
5
>>> len(s)
21
>>> s="06-05-2024"

251
>>> x=s.split()
>>> print(x)
['06-05-2024']
>>> x=s.split("-")
>>> print(x)
['06', '05', '2024']
>>> print("DD=",x[0])
DD= 06
>>> print("MM=",x[1])
MM= 05
>>> print("YY=",x[2])
YY= 2024
>>> s="Apple#Mango-Kiwi#Guava"
>>> x=s.split("#")
>>> print(x)
['Apple', 'Mango-Kiwi', 'Guava']
>>> y=x[1].split("-")
>>> print(y)
['Mango', 'Kiwi']
>>> x[1]=y[0]
>>> print(x)
['Apple', 'Mango', 'Guava']
>>> x.insert(-1,y[1])
>>> print(x)
['Apple', 'Mango', 'Kiwi', 'Guava']
-----------------------------------------------------------------------------------------------------------------------------
join()
---------------------------------------------------------------------------------------------------------------------------------------
>>> lst=['PYTHON', 'IS', 'AN', 'FUN', 'PROG', 'LANG']
>>> print(lst,type(lst))
['PYTHON', 'IS', 'AN', 'FUN', 'PROG', 'LANG'] <class 'list'>
>>> s=" "
>>> s.join(lst)

252
'PYTHON IS AN FUN PROG LANG'
>>> print(s)
>>> s
''
>>> lst=['PYTHON', 'IS', 'AN', 'FUN', 'PROG', 'LANG']
>>> print(lst,type(lst))
['PYTHON', 'IS', 'AN', 'FUN', 'PROG', 'LANG'] <class 'list'>
>>> s=" "
>>> s=s.join(lst)
>>> print(s)
PYTHON IS AN FUN PROG LANG
-----------------------------------------------------------------------------------------------------------------------
lstrip() , rstrip() strip()
-----------------------------------------------------------------------------------------------------------------------------
>>> s=" Python"
>>> print(s,len(s))
Python 10
>>> s=s.lstrip()
>>> print(s,len(s))
Python 6
>>> s="Python "
>>> print(s,len(s))
Python 9
>>> s=s.rstrip()
>>> print(s,len(s))
Python 6
>>> s=" Python "
>>> print(s,len(s))
Python 13
>>> s=s.strip()
>>> print(s,len(s))
Python 6
--------------------

253
>>> s="Nirkar Behra "
>>> print(s,len(s))
Nirkar Behra 18
>>> s=s.strip()
>>> print(s,len(s))
Nirkar Behra 14
>>> " ".join(s.split())
'Nirkar Behra'
>>> s="++++++++++PYTHON++++++"
>>> s.strip("+")
'PYTHON'
>>>
========================================================
2. Looping OR Iterative OR Repetative Statements
========================================================
=>The purpose of Looping OR Iterating OR Repetative Statements "To Perform Certain Operation Repeatedly
for Finite Number of Times Until Test Condition becomes False"
=>In Python Programming, we have 2 Types of Looping OR Iterating OR Repetative Statements. They are
1. while loop OR while..else loop
2. for loop OR for .... else loop
=>At the time writng any Python Program by using Loops, we must use the following 3 Points.
1. Initlization Part ( Where to Start)
2. Conditional Part ( Where to Stop)
3. Updation Part ( Either Incrementation OR Decrementation )
---------------------------------------------------------------------------------------------------------------------------------------

254
255
#Program for Generating 1 to n Numbers
# 1 2 3 4 5 6 7 8 9 10
#WhileLoopEx1.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 Part
while(i<=n): # Cond Part
print("{}".format(i))
i=i+1 # Updation Part
else:
print("I am from else part of while loop")
print("Other statements of while Loop Statements")
print("Other statements of if..else Statements")
#Program for Generating n to 1 numbers
# 10 9 8 7 6 5 4 3 2 1
#WhileLoopEx2.py
n=int(input("Enter How Many Number u want to generate:"))
if(n<=0):
print("{} is Invalid input".format(n))
else:
print("-"*50)
print("Numbers within {} to 1".format(n))
print("-" * 50)
i=n
while(i>=1):
print("\t\t{}".format(i))
i=i-1
else:
print("-" * 50)

256
#Program for Generating odd Numbers within in n
#WhileLoopEx3.py
n=int(input("Enter How Many Odd Number u want to generate within range:"))
if(n<=0):
print("{} is Invalid input".format(n))
else:
print("-"*50)
print("Odd Numbers within 1 to n".format(n))
print("-" * 50)
i=1
while(i<=n):
print("\t\t{}".format(i))
i=i+2
else:
print("-" * 50)
#Program for Generating Even Numbers within n in Decresing Order
#WhileLoopEx4.py
n=int(input("Enter How Many Even Number u want to generate within range:"))
if(n<=0):
print("{} is Invalid input".format(n))
else:
print("-"*50)
print("Even Numbers within {} to 2".format(n))
print("-" * 50)
n= n if(n%2==0) else n-1
while(n>=2):
print("\t{}".format(n))
n=n-2
else:
print("-" * 50)
#Program for generating Mul Table for a given Number
#WhileLoopEx5.py

257
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 # Initlization Part
while(i<=10): # Cond Part
print("\t{} x {}={}".format(n,i,n*i))
i=i+1 # Updation Part
else:
print("=" * 50)
#Program for Generating a chars from word or line of Text
#WhileLoopEx6.py
word=input("Enter a word OR Line of Text:")
print("Given Word={}".format(word))
i=0
while(i<len(word)):
print("\t{}".format(word[i]))
i=i+1
print("-------------OR---------------")
i=len(word)-1
while(i>=0):
print("\t{}".format(word[i]))
i=i-1
print("-------------OR---------------")
i=0
word=word[::-1]
while(i<len(word)):
print("\t{}".format(word[i]))
i=i+1
print("-------------OR---------------")
258
word=word[::-1]
i=-1
while(i>=(-len(word))):
print("\t{}".format(word[i]))
i=i-1
print("-------------OR---------------")
i=-len(word)
while(i<=-1):
print("\t{}".format(word[i]))
i=i+1
==============================================
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
----------------------------------------

259
---------------------------------------------------
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.
======================================x=======================================
#Program for generating 1 to n Numbers where n is +ve
#ForLoopEx1.py
n=int(input("Enter How Many Numbers u want to generate:"))
if(n<=0):
print("{} is Invalid".format(n))
else:
print("-" * 50)
print("Numbers within {}".format(n))
print("-" * 50)
for i in range(1,n+1):
print("\t{}".format(i))
else:
print("-"*50)
#Program for generating n to 1 Numbers where n is +ve
#ForLoopEx2.py
n=int(input("Enter How Many Numbers u want to generate:"))
if(n<=0):
print("{} is Invalid".format(n))
260
else:
print("-" * 50)
print("Numbers within {}".format(n))
print("-" * 50)
for i in range(n,0,-1):
print("\t{}".format(i))
else:
print("-"*50)
#Program for generating Mul Table for a given Number
#ForLoopEx3.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\t{} x {}={}".format(n,i,n*i))
else:
print("=" * 50)
#Program for Finding Sum of N Natural Numbers where N Is +Ve
#ForLoopEx4.py
n=int(input("Enter the Value of N for Finding Its Sum:"))
if(n<=0):
print("{} is Invalid Number:".format(n))
else:
s=0 # here Initlizing the var s=0 is called Additive Identity
for i in range(1,n+1):
print("\t{}".format(i))
s=s+i
else:
print("Sum of {} Nummbers={}".format(n,s))
261
#Program for Finding Sum of Squares of N Natural Numbers where N Is +Ve
#ForLoopEx5.py
n=int(input("Enter the Value of N for Finding Its Squares Sum:"))
if(n<=0):
print("{} is Invalid Number:".format(n))
else:
s=0 # here Initlizing the var s=0 is called Additive Identity
ss=0
print("-" * 50)
print("\tNatNums\t\tSquares")
print("-" * 50)
for i in range(1,n+1):
print("\t{}\t\t\t\t{}".format(i,i*i))
s=s+i
ss=ss+i**2
else:
print("-"*50)
print("\t{}\t\t\t\t{}".format(s,ss))
print("-" * 50)
#Program for Finding Sum of Cubes of N Natural Numbers where N Is +Ve
#ForLoopEx6.py
n=int(input("Enter the Value of N for Finding Its Cubes Sum:"))
if(n<=0):
print("{} is Invalid Number:".format(n))
else:
s=0 # here Initlizing the var s=0 is called Additive Identity
ss=0
cs=0
print("-" * 50)
print("\tNatNums\t\tSquares\t\tCubes")
print("-" * 50)
for i in range(1,n+1):
print("\t{}\t\t\t\t{}\t\t\t{}".format(i,i*i,i*i*i))
262
s=s+i
ss=ss+i**2
cs=cs+i**3
else:
print("-"*50)
print("\t{}\t\t\t\t{}\t\t\t{}".format(s,ss,cs))
print("-" * 50)
#Program for Finding Product of N Natural Numbers where N Is +Ve
#ForLoopEx7.py
n=int(input("Enter the Value of N for Finding Its Product:"))
if(n<=0):
print("{} is Invalid Number:".format(n))
else:
s=1 # here Initlizing the var s=10 is called Multiplicative Identity
for i in range(1,n+1):
print("\t{}".format(i))
s=s*i
else:
print("Product of {} Nummbers={}".format(n,s))
#Program for Finding Factorial of a Number
#n!----> 1 x 2 x 3 .... n
#OR
# n!= n x n-1 x n-2x....0!
#0!=1
# -n!---->Invalid input
#ForLoopEx8.py
n=int(input("Enter the Value of N for Finding Its Factorial:"))
if(n<0):
print("{} is Invalid Number:".format(n))
else:
fact=1
for i in range(1,n+1):
263
fact=fact*i
else:
print("Factorial({})={}".format(n,fact))
#Program for Finding Factorial of a Number
#n!----> 1 x 2 x 3 .... n
#OR
# n!= n x n-1 x n-2x....0!
#0!=1
# -n!---->Invalid input
#ForLoopEx9.py
n=int(input("Enter the Value of N for Finding Its Factorial:"))
if(n<0):
print("{} is Invalid Number:".format(n))
else:
fact=1
tn=n# Here tn is temp Var which is holding Original value bcoz Original Value is going excedes to 0
while(n>0):
fact=fact*n
n=n-1
else:
print("Factorial({})={}".format(tn,fact))

#Program for Obtaining Only Alphabets from given line of Text / word
#Line="Py3th$o6n"
#GetApphas.py
line=input("Enter Line of Text:")
print("Given line:{}".format(line))
for ch in line:
if(ch.isalpha()):
print("{}".format(ch))

264
#Program for Obtaining Only Special Symbols from given line of Text / word
#and also Find Number of Special Symbols
#Input: P6&yt$ho@N
#Expected Output: $ @
#GetSpecialSymbols.py
line=input("Enter Line of Text:")
nosp=0
print("Given Line=",line)
for ch in line:
if(not ch.isalnum()):
nosp=nosp+1
print("{}".format(ch))
else:
print("Number of Special Symbols=",nosp)
#Program for Obtaining Only Special Symbols from given line of Text / word
#and also Find Number of Special Symbols
#GetSpecialSymbolsWithoutSpaces.py
line=input("Enter Line of Text:")
nosp=0
print("Given Line=",line)
for ch in line:
if((not ch.isalnum()) and (not ch.isspace()) ):
nosp=nosp+1
print("{}".format(ch))
else:
print("Number of Special Symbols=",nosp)
#Program for Obtaining Only Special Symbols from given line of Text / word
#and also Find Number of Special Symbols
#GetSpecialSymbolsWithoutSpacesnewlgic.py
line=input("Enter Line of Text:")
nosp=0

265
print("Given Line=",line)
words=line.split() # words= ['Python', 'is', 'an', 'oop$', 'La#ng']
for word in words:
for ch in word:
if(not ch.isalnum()):
print("\t{}".format(ch))
nosp=nosp+1
else:
print("Number of Special Symbols=",nosp)
#Program for Reading List of Values from Key Board and Display those Values.
#ReadValuesEx1.py--Logic-1
nov=int(input("How Many Values u want to Enter:"))
if(nov<=0):
print("{} is Invalid Input".format(nov))
else:
lst=[] # create an empty list for adding the values
for i in range(1,nov+1):
val=float(input("Enter {} Value:".format(i)))
lst.append(val)
else:
print("List of Values={}".format(lst))

#Program for Reading List of Values from Key Board and Display those Values.
#ReadValuesEx2.py--Logic-2
import sys
print("Enter Number of Values and Press @ to stop")
lst=[]
while(True):
value=input()
if(value=="@"):
if(len(lst)==0):
print("list is empty")
else:
266
print("Content of Lst=", lst)
sys.exit()
else:
lst.append(float(value))
=======================================================
Transfer Flow Statements
=======================================================
=>The purpose of Transfer Flow Statements is that "To transfer the control of PVM from One Part of the Program
to Another Part of the Program"
=>In Python Programming, we have 4 types of Transfer Flow Statements. They are
1. break
2. continue
3. pass
4. return (In Functions )
==============================================
1. break statement
==============================================
=>break is a key word
=>break keyword must be used always inside of loops otherwise we get Syntax error
=>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 becoming False) but it executes other statements in the program.
=>Syntax1:
-------------------
for varname in Iterable_object:
------------------------------
if (test cond):
break
------------------------------
------------------------------
------------------

267
=>Syntax2:
-------------------
while(Test Cond-1):
------------------------------
if (test cond-2):
break
------------------------------
------------------------------
#Program for Demonstrating break key word
#BreakStmtEx1.py
s="PYTHON"
print("By using For Loop")
for ch in s:
print("\t{}".format(ch))
else:
print("I am from else part of for loop")
print("------------------------------------")
#My Requirment is to dispaly 'PYTH' without using Indexing and slicing
for ch in s: # s="PYTHON"
if(ch=="O"):
break
else:
print(ch,end="")
else:
print("I am from else part of for loop")
print("\nOther statements in Program")

#Program for Demonstrating break key word


#BreakStmtEx2.py

268
s="PYTHON"
print("By using while Loop")
i=0
while(i<len(s)):
print("\t{}".format(s[i]))
i=i+1
else:
print("I am from else part of while loop")
print("------------------------------------")
#My Requirment is to dispaly 'PYTH' without using Indexing and slicing
i=0
while(i<len(s)):
if(s[i]=="O"):
break
print(s[i],end="")
i=i+1
else:
print("I am from else part of while loop")
print("\nOther statements in Program")

#Program for Demonstrating break key word


#BreakStmtEx3.py
s="MISSISSIPPI"
print("By using For Loop")
for ch in s:
print("\t{}".format(ch))
else:
print("I am from else part of for loop")
print("------------------------------------")
#My Requirment is to dispaly 'MISS' without using Indexing and slicing
ni=0
i=0 # s="MISSISSIPPI"
while(i<len(s)):
269
if(s[i]=="I"):
ni=ni+1
if(ni==2):
break
print(s[i],end="")
i=i+1
else:
print("I am from else part of for loop")
print("\nOther statements in Program")
#Program for Demonstrating break key word
#BreakStmtEx3.py
s="MISSISSIPPI"
print("By using For Loop")
for ch in s:
print("\t{}".format(ch))
else:
print("I am from else part of for loop")
print("------------------------------------")
#My Requirment is to dispaly 'MISS' without using Indexing and slicing
ni=0
# s="MISSISSIPPI"
for i in range(len(s)):
if(s[i]=="I"):
ni=ni+1
if(ni==2):
break
print(s[i],end="")
else:
print("I am from else part of for loop")
print("\nOther statements in Program")

#Program for deciding whether the Number is Prime or Not


#BreakStmtEx5.py
270
n=int(input("Enter a Number to decide Prime or Not:"))
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
print("{} is {}".format(n,res))
#Program for deciding whether the Number is Prime or Not
#BreakStmtEx6.py
n=int(input("Enter a Number to decide Prime or Not:"))
if(n<=1):
print("{} is Invalid Input".format(n))
else:
res=False
for i in range(2,n):
if(n%i==0):
res=True
break
if(res):
print("{} is NOT PRIME".format(n))
else:
print("{} is PRIME".format(n))

#Program for deciding whether the Number is Prime or Not


#BreakStmtEx6.py
n=int(input("Enter a Number to decide Prime or Not:"))
if(n<=1):
print("{} is Invalid Input".format(n))
else:
res=False
271
for i in range(2,n):
if(n%i==0):
res=True
break
res="NOT PRIME" if res else "PRIME"
print("{} is {}".format(n,res))
#Program for Deciding whether the given word is Vowel or Not
#BreakStmtEx8.py
word=input("Enter a word:") #HYDERABAD
res="NOT VOWEL WORD"
for ch in word:
if ch.lower() in ['a','e','i','o','u']:
res="VOWEL WORD"
break
print("{} is {}".format(word,res))
-------------------------------------
2. 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
272
statement-n
-----------------------------------------
-----------------------------------------
=>Syntax:-
----------------
while (Test Cond):
------------------------------------------
if ( Test Cond):
continue
statement-1 # written after continue stateemnt
statement-2
statement-n
-----------------------------------------
-----------------------------------------
#Program for Demonstrating Continue Statement
#ContinueStmtEx1.py
s="PYTHON"
for ch in s:
print("{}".format(ch))
else:
print("i am else part of for loop")
print("-------------------------------------")
#My Requirement is to Duisplay: PTON
for ch in s: # S="PYTHON"
if(ch=="H") or (ch=="Y"):
continue
print(ch,end="")
else:
print("\ni am else part of for loop")
print("-------------------------------------")

273
#Program for Demonstrating Continue Statement
#ContinueStmtEx2.py
s="PYTHON"
i=0
while(i<len(s)):
print("{}".format(s[i]))
i=i+1
else:
print("i am from else part of while loop")
print("-------------------------------------")
#My Requirement is to Duisplay: PYTON
i=0
while(i<len(s)):
if s[i] in ["Y","H"]:
i=i+1
continue
print("{}".format(s[i]),end="")
i=i+1
else:
print("\ni am from else part of while loop")
print("-------------------------------------")
#Program for accepting List of Values and separate them with +ve and -ve vals
#ContinueStmtEx3.py
nov=int(input("How Many Values u want to Enter:"))
if(nov<=0):
print("{} is Invalid Input".format(nov))
else:
lst=[] # create an empty list for adding the values
for i in range(1,nov+1):
val=float(input("Enter {} Value:".format(i)))
lst.append(val)
else:
print("List of Values={}".format(lst)) # [10.0, -20.0, 30.0, -40.0, -50.0]
274
#Code for Obtaining List of +Ve vals
pslist=[]
for val in lst:
if(val<=0):
continue
pslist.append(val)
else:
print("List of +VE Values=",pslist)
print("Number of +Ve Values=",len(pslist))
print("----------------------------------")
#Code for Obtaining List of -Ve vals
nvlist=list()
for val in lst:
if(val>=0):
continue
nvlist.append(val)
else:
print("List of -VE Values=", nvlist)
print("Number of -Ve Values=", len(nvlist))
print("----------------------------------")
#Program for accepting List of words and obtain those words whose length is either 3 or 5
#ContinueStmtEx4.py
nov=int(input("How Many Words u want to Enter:"))
if(nov<=0):
print("{} is Invalid Input".format(nov))
else:
lst=[] # create an empty list for adding the values
for i in range(1,nov+1):
val=input("Enter {} Value:".format(i))
lst.append(val)
else:
print("List of Words={}".format(lst))
#['Why', 'Apple', 'Elephant', 'Python', 'while']
275
#Code for Obtaining those words whose length is either 3 or 5
word35=list() # for storing 3 or 5 length word
for word in lst:
if(len(word) not in [3,5]):
word35.append(word)
else:
print("List of words with 3 or 5 in Length")
print(word35)
#Program for accepting List fo words and Obtains only Palindrome Words
#ContinueStmtEx5.py
print("Enter Number of Words and Press any special to stop")
lst=[]
while(True):
value=input()
if(not value.isalnum()):
break
else:
lst.append(value)
print("List of Words=",lst)
#Code for Obtaining Palindrome words
plist=list() # For Storing Palindrome Words
for word in lst:
if(word!=word[::-1]):
continue
plist.append(word)
else:
print("List of Palindome Words")
print(plist)
#Program for accepting List of Values and separate them with +ve and -ve vals
#ContinueStmtEx3.py
nov=int(input("How Many Values u want to Enter:"))
if(nov<=0):
print("{} is Invalid Input".format(nov))
276
else:
lst=[] # create an empty list for adding the values
for i in range(1,nov+1):
val=float(input("Enter {} Value:".format(i)))
lst.append(val)
else:
print("List of Values={}".format(lst)) # [10.0, -20.0, 30.0, -40.0, -50.0]
#Code for Obtaining List of +Ve vals
pslist=[]
for val in lst:
if(val<=0):pass
else:
pslist.append(val)
else:
print("List of +VE Values=",pslist)
print("Number of +Ve Values=",len(pslist))
print("----------------------------------")
#Code for Obtaining List of -Ve vals
nvlist=list()
for val in lst:
if(val>=0):pass
else:
nvlist.append(val)
else:
print("List of -VE Values=", nvlist)
print("Number of -Ve Values=", len(nvlist))
print("----------------------------------")
#Program for accepting List of Text and find length of each word
#WordsLengthEx.py
line=input("Enter Line of Text:")
print("Given Line=",line)
words=line.split()
print("-------------------------------------------")
277
for word in words:
print("{}-->{}".format(word,len(word)))
print("---------------OR----------------------------")
wl=dict()
for word in words:
wl[word]=len(word)
else:
for k,v in wl.items():
print("\t{}---->{}".format(k,v))
print("---------------OR----------------------------")
wt=list()
for word in words:
wt.append((word,len(word)))
else:
for tpl in wt:
print(tpl)

nvlist.append(val)
else:
print("List of -VE Values=", nvlist)
print("Number of -Ve Values=", len(nvlist))
print("----------------------------------")
=================================================================
Inner OR Nested Loops
=================================================================
=>The Process of Defining One Loop inside of Another Loop is called Inner or Nested Loop.
=>The Execxution process of Inner OR Nested Loops is that "For Every Value of Outer Loop Inner Loop
Repeated Finite Number of Times Until Inner loop Test Cond becomes False".
=>In General , Outer Loop Defined for 'n' Times to repeat and Corersponding Inner Loop Defined for 'm' times
the total Number of times Both the loop repeates is 'n*m' times.
=>In Python Programming, we can Define Inner Loop in 4 ways. They are
1. for loop in for loop.
2. while loop in while loop.

278
3. for loop in while loop.
4. while loop in for loop.
---------------------------------------------------------------------------------------------------------------------------
Syntax-1: 1. for loop in for loop.
------------------------------------------------------------------------------------------------------------------------
for varname1 in iterable-object: # Outer Loop
-----------------------------
for varname2 in iterable-object: # Inner Loop
---------------------------
---------------------------
else:
---------------------------
else:
------------------------------------
------------------------------------------------------------------------------------------------------------------------------
Syntax-2: while loop in while loop
------------------------------------------------------------------------------------------------------------------------------
---------------------------------
while(Test Cond1): # Outer Loop
------------------------
while(Test Cond2): # Inner Loop
-------------------------
-------------------------
else:
-------------------------
else:
------------------------------

--------------------------------------------------------------------------------------------------------------------------------------
Syntax-3: for loop in while loop.
-----------------------------------------------------------------------------------------------------------------------------------
---------------------------------
while(Test Cond1): # Outer Loop
279
------------------------
for varname in Iterfable-Object: # Inner Loop
-------------------------
-------------------------
else:
-------------------------
else:
------------------------------

-----------------------------------------------------------------------------------------------------------------------------------
Syntax-4: while loop in for loop.
----------------------------------------------------------------------------------------------------------------------------------
for varname1 in iterable-object: # Outer Loop
-----------------------------
while(Test Cond2): # Inner Loop
-------------------------
-------------------------
else:
-------------------------
else:
------------------------------------

#InnerLoopEx1.py---for loop in for loop


for i in range(1,6):#Outer Loop
print("val of i-outer loop={}".format(i))
for j in range(1,4):#Inner loop
print("\tval of j-inner loop={}".format(j))
else:
print("\tOut-off inner loop")
else:
print("Out-off outer loop")

280
#InnerLoopEx2.py---while loop in while loop
i=1
while(i<=6):#Outer Loop
print("val of i-outer loop={}".format(i))
j=1
while(j<=3):# Inner loop
print("\tval of j-inner loop={}".format(j))
j=j+1
else:
print("\tOut-off inner loop")
i=i+1
else:
print("Out-off outer loop")
#InnerLoopEx3.py---foop loop in while loop
i=6
while(i>=1): # outer loop
print("val of i-outer loop={}".format(i))
for j in range(3,0,-1): # Inner loop
print("\tval of j-inner loop={}".format(j))
else:
print("\tOut-off inner loop")
i = i-1
else:
print("Out-off outer loop")
#InnerLoopEx4.py---while loop in for loop
for i in range(6,0,-1): # outer loop
print("val of i-outer loop={}".format(i))
j=1
while(j<=3): # Inner loop
print("\tval of j-inner loop={}".format(j))
j=j+1
else:
print("\tOut-off inner loop")
281
else:
print("Out-off outer loop")
#InnerLoopEx5.py---for in for in for
for i in range(1,4): # outer Loop
print("\ti\tj\tk")
print("---------------------------------")
for j in range(1,3):# Inner Loop
for k in range(1,3):#Inner-Inner loop
print("\t{}\t{}\t{}".format(i,j,k))
else:pass
else:
print("------------------------------")
else:
print("=====================================")
#InnerLoopEx6.py---Mul tables for 1 to n Numbers
n=int(input("Enter How Many Mul Tables u want display:"))
if(n<=0):
print("{} is Invalid input".format(n))
else:
for num in range(1,n+1): # Outer For loop supply the number
print("-----------------------------------")
print("Mul Table for {}".format(num))
print("-----------------------------------")
for i in range(1,11): # Inner loop--generates mul table
print("\t{} x {}={}".format(num,i,num*i))
else:
print("-----------------------------------")
#Mul Tables for random Numbers
#InnerLoopEx7.py
n=int(input("Enter How Many Mul Tables u want display:"))
if(n<=0):
print("{} is Invalid input".format(n))
else:
282
lst=list()
for i in range(1,n+1):
val=int(input("Enter {} Value for Generating Mul Table:".format(i)))
lst.append(val)
else:
print("Given List of Values:{}".format(lst))# [3, 19, -9, 0, 12]
#Code for Mul tables for Random Numbers
for num in lst: # Outer For loop supply the number from list
if(num<=0):
print("{} is Invalid input".format(num))
else:
print("-----------------------------")
print("Mul Table for:{}".format(num))
print("-----------------------------")
for i in range(1,11):#Inner Loop--generates mul Table
print("\t{} x {}={}".format(num,i,num*i))
else:
print("-----------------------------")
#Program for Generating Prime Numbers within the Given Range
#InnerLoopEx8.py
n=int(input("Enter Range in which u want Prime Numbers:"))
if(n<=2):
print("{} is Invalid input".format(n))
else:
print("Prime Numbers within:{}".format(n))
nop=0
for num in range(2,n+1): # Outer Loop--Supply the Numbers
res=True
for i in range(2,num):#Inner loop--Decides weather the Num is Prime or not
if(num%i==0):
res=False
break
if(res):
283
print("\t{}".format(num))
nop = nop + 1
else:
print("Numbers Primes within {}={}".format(n, nop))
#Given Input lst=[123,45,34,24,89]
# Expected Output: sumlist= [6,9,7,6,17]
#InnerLoopEx10.py
n=int(input("Enter How Values u want to List:"))
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:
sumlist=list()
print("Given List of Values:{}".format(lst))#[123, 45, 2345, 12, 67]
for num in lst:## Outer Loop--Supply the Numbers
s=0
for v in str(num):
s=s+int(v)
else:
sumlist.append(s)
else:
print("Given list=",lst)
print("Sum List=",sumlist)

=====================================================
Functions in Python
=====================================================
Index
---------------------------------------------------------------------------
284
=>Types of Languages
i) Un-Structured Programming Languages
ii) Structured Programming Languages
=>Purpose of Functions
=>Advantages of Functions
=>Parts of Functions
=>Phases in Functions
=>Syntax for Defining Functions in Python
=>Number of Approaches to Define Functions.
=>Programming Examples
--------------------------------------------------------------------------
=>Parameters and Arguments
=>Types of Arguments
i) Possitional Arguments
ii) Default Arguments
iii) Keyword Arguments
iv) Variable Length Arguments
v) Keyword Variable Length Arguments
=>Programming Examples
-------------------------------------------------------------------------
=>Local and Global Variables
=>Programming Examples
=>global Keyword
=>Programming Examples
=>globals()
=>Programming Examples
---------------------------------------------------------------------------
=>Comprehension Techniques
i) List Comprehension
ii) set Comprehension
iii) Dict Comprehension
iv) tuple Comprehension (Not there)
=>Programming Examples

285
---------------------------------------------------------------------------
=>Anonymous Functions OR Lambda Functions
=>Implementation and Syntax for Anonymous Functions OR Lambda Functions
=>Programming Examples
----------------------------------------------------------------------------
=>Special Functions Python
i) filter() with Normal and Anonymous Functions
ii) map() with Normal and Anonymous Functions
iii) reduce() with Normal and Anonymous Functions
=>Programming Examples
=========================================================
Types of Languages
=========================================================
=>In Industry , we have Two Types of Programming Langauges. They are
1. Un-Structured Programming Languages.
2. Structured Programming Languages.
--------------------------------------------------------------------------------------------------------------------------------------
1. Un-Structured Programming Languages
------------------------------------------------------------------------------------------------------------------------------------
=>The Un-Structured Programming Languages DOES NOT CONTAIN FUNCTIONs Concept. So that whose
related Applications has the Following Limitations.
1. Application Development time is More
2. Application Memory Space is More
3. Application Execution Time is More
4. Application Performnace is Degraded
5. Redundency(Duplication or Replication) of the Code is More
Examples: GW-BASIC
-----------------------------------------------------------------------------------------------------------------------------------
2. Structured Programming Languages.
---------------------------------------------------------------------------------------------------------------------------------------
=>The Structured Programming Languages CONTAINS FUNCTIONs Concept. So that whose related
Applications has the Following Advatnages.
1. Application Development time is Less.
286
2. Application Memory Space is Less.
3. Application Execution Time is Less.
4. Application Performnace is Enhanced (Improved)
5. Redundency(Duplication or Replication) of the Code is Minimized.
Examples: C, C++, Java, C#.net, PYTHON...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.

287
--------------------------------------------------------------------------------------------------------------------------------
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
-------------------------------------------------------------------------------------------------------------------------------

288
===================================================
Number of Approaches to Define Functions.
===================================================
=>In Python Programming, To Define any Function, we have 4 Approaches. They are
--------------------------------------------------------------------------------------------------------------------------------------
Approach-1
------------------------------------------------------------------------------------------------------------------------------------
#INPUT: Taking from Function call
#PROCESS: Taken Place in Function Body
#Output: Given to Function call
-------------------------------------------------------------------------------------------------------------------------------
Approach-2
----------------------------------------------------------------------------------------------------------------------------------
#INPUT: Taking inSide of Function Body
#PROCESS: Taken in Function Body
#Output: Display Inside of Function Body
---------------------------------------------------------------------------------------------------------------------------------
Approach-3
------------------------------------------------------------------------------------------------------------------------------------
#INPUT: Taking from Function call
#PROCESS: Taken Place in Function Body
#Output: Display Inside of Function Body
-------------------------------------------------------------------------------------------------------------------------------
Approach-4
-----------------------------------------------------------------------------------------------------------------------------------
#INPUT: Taking inSide of Function Body
#PROCESS: Taken in Function Body
#Output: Given to Function call
--------------------------------------------------------------------------------------------------------------------------------------
#Define a Function for Addition of Two Numbers.c=a+b
#Approach1.py
def addop(a,b): # Here a, b are called Formal Parameters

289
print("I am in Function Def")
c=a+b # Here c is called Local Variable
return c
#Main Program
print("I am from Main Program")
print("Type of addop=",type(addop))
res=addop(10,20) # Function Call
print("sum=",res)
print("-------------------")
c=addop(100,200) # Function Call
print("Sum=",c)
print("-------------------")
c=addop(-100,-200) # Function Call
print("Sum=",c)
#Define a Function for Addition of Two Numbers.c=a+b
#ApproachEx1.py
#INPUT: Taking from Function call
#PROCESS: Taken Place in Function Body
#Output: Given to Function call
def addop(x,y): # here x,y are called formal Parameters
z=x+y # Here z is called Local Var
return z
#Main Program
print("----------------------------")
a=float(input("Enter First Value:"))
b=float(input("Enter Second Value:"))
res=addop(a,b) # Function Call
print("Sum({},{})={}".format(a,b,res))
print("----------------------------")
x=float(input("Enter First Value:"))
y=float(input("Enter Second Value:"))
z=addop(x,y) # Function Call
print("Sum({},{})={}".format(x,y,z))
290
print("----------------------------")
#Define a Function for Addition of Two Numbers.c=a+b
#ApproachEx2.py
#INPUT: Taking inSide of Function Body
#PROCESS: Taken in Function Body
#Output: Display Inside of Function Body
def addop():
#Input: Taking inSide of Function Body
a=float(input("Enter First Value:"))
b=float(input("Enter Second Value:"))
#Process: Taken in Function Body
c=a+b
#Output: Display Inside of Function Body
print("sum({},{})={}".format(a,b,c))

#Main Program
addop() # Function Call
#Define a Function for Addition of Two Numbers.c=a+b
#ApproachEx3.py
#INPUT: Taking from Function call
#PROCESS: Taken Place in Function Body
#Output: Display Inside of Function Body
def addop(a,b):
#Process
c=a+b
#result
print("Sum({},{})={}".format(a,b,c))
#Main Program
a=float(input("Enter First Value:"))
b=float(input("Enter Second Value:"))
addop(a,b) # Function call

291
#Define a Function for Addition of Two Numbers.c=a+b
#ApproachEx4.py--Most Imp
#INPUT: Taking inSide of Function Body
#PROCESS: Taken in Function Body
#Output: Given to Function call
def addop():
#Taking Input
k=float(input("Enter First Value:"))
v=float(input("Enter Second Value:"))
#Process
r=k+v
#return the value
return k,v,r # return stmt can return one or More Number of values
#Main Program
x,y,res=addop() # Function Call with Multiline Assigment
print("sum({},{})={}".format(x,y,res))
print("-------------OR---------------------")
hyd=addop() # Function Call with Single Line Assigment
#here hyd is an object of <class,tuple>
print("sum({},{})={}".format(hyd[0],hyd[1],hyd[2]))
print("-------------OR---------------------")
print("sum({},{})={}".format(hyd[-3],hyd[-2],hyd[-1]))
Additional Programming Examples on Functions
#SimpleIntEx1.py
def simpleint():
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("Principle Amount:{}".format(p))
292
print("Time:{}".format(t))
print("Rate of Interest:{}".format(r))
print("Simple Interest:{}".format(si))
print("Total Amount to Pay:{}".format(totamt))
print("-" * 50)
#Main Program
simpleint() # Function Call
#SimpleIntEx2.py
def takevalues():
p = float(input("Enter Principle Amount:"))
t = float(input("Enter Time:"))
r = float(input("Enter Rate of Interest:"))
return p,t,r
def calsimpleint():
p,t,r=takevalues() # Function with Multiline assigment
si=(p*t*r)/100
totamt=p+si
return p,t,r,si,totamt
def displayresult():
p,t,r,si,totamt=calsimpleint()# Function with Multiline assigment
print("-" * 50)
print("Principle Amount:{}".format(p))
print("Time:{}".format(t))
print("Rate of Interest:{}".format(r))
print("Simple Interest:{}".format(si))
print("Total Amount to Pay:{}".format(totamt))
print("-" * 50)

#Main Program
displayresult() # Function call

#NOTE: displayresult()--->calsimpleint()--->takevalues() is called Function Chaining

293
#Program for accepting List of Values and find their sum and avg
#SumAvgEx1.py
def readvalues():
nov=int(input("Enter How Many Value u want:"))
if(nov<=0):
return []
else:
lst=[]
for i in range(1,nov+1):
val=float(input("Enter {} Vakue:".format(i)))
lst.append(val)
return lst
def findsumavg(lst): # lst=[10,20,30,40]
if(len(lst)==0):
print("List is empty-can't find sum and avg")
else:
s=0
for val in lst:
print("\t{}".format(val))
s=s+val
else:
print("Sum={}".format(s))
print("Avg={}".format(s/len(lst)))
#Main Program
lst=readvalues() # Function Call
findsumavg(lst) # Function call
#Program for accepting list of words and find max length words
#MaxlengthWordsEx1.py
def getwords():
print("Enter List of Words and Press @ to stop:")
lst=[]
while(True):
val=input()
294
if(val=="@"):
break
else:
lst.append(val)
return lst
def findmaxlenword(words):#['Python', 'java', 'HTML', 'django', 'Hyderabad', 'bang']
if(len(words)==0):
print("List is empty--can't find max length word")
else:
d=dict()
for word in words:
d[word]=len(word)
else:
lst=[]
print(d) # {'python': 6, 'java': 4, 'banglore': 8,'C': 1, 'C++': 3 }
ml=max(list(d.values())) # ml=8
for word,length in d.items():
if(length==ml):
lst.append(word)
else:
print("Max Length Words")
for word in lst:
print("\t{}".format(word))
else:
print("Number of Max Length Words=",len(lst))
#Main program
words=getwords()#['Python', 'java', 'HTML', 'django', 'Hyderabad', 'bang']
findmaxlenword(words)
#Program for accepting list of words and find max length words
#MaxlengthWordsEx1.py
def getwords():
print("Enter List of Words and Press @ to stop:")
lst=[]
295
while(True):
val=input()
if(val=="@"):
break
else:
lst.append(val)
return lst
def findmaxlenword(words):#['Python', 'java', 'HTML', 'django', 'Hyderabad', 'bang']
if(len(words)==0):
print("List is empty--can't find max length word")
else:
d=dict()
for word in words:
d[word]=len(word)
else:
lst=[]
print(d) # {'python': 6, 'java': 4, 'banglore': 8,'C': 1, 'C++': 3 }
list1=list(d.values()) # ml=8
#Code for Find Max Value from Dict of Values
ml=list1[0]
for val in list1:
if val>ml:
ml=val
else:
for word,length in d.items():
if(length==ml):
lst.append(word)
else:
print("Max Length Words")
for word in lst:
print("\t{}".format(word))
else:
print("Number of Max Length Words=",len(lst))

296
#Main program
words=getwords()#['Python', 'java', 'HTML', 'django', 'Hyderabad', 'bang']
findmaxlenword(words)
=========================================================
Parameters and Arguments
=========================================================
---------------------
Parameters
---------------------
=>In Python Parameters are classified into Two Types. They are
1. Formal Parameters / Variables
2. Local Variables / Parameters
------------------------------------------------
1. Formal Parameters / Variables
------------------------------------------------
=>Formal Parameters / Variables are those which are used in Function Heading.
=>The Purpose of Formal Parameters is that "To store OR Hold the Inputs coming From Function Calls".
=>The values of Formal Parameters can be accessed within in Corresponding Function Definition But not
Possible to Access in Other Part of Function Definition OR In other Part of the Program.
---------------------------------------------
Local Variables / Parameters
---------------------------------------------
=>Local Variables / Parameters are those which are used as a part of Function Body.
=>The purpose of Local Variables is that "To store the Result of Function Processing Logic"
=>The values of Local Parameters can be accessed within in Corresponding Function Definition But not Possible
to Access in Other Part of Function Definition OR In other Part of the Program.
---------------------------------------------
Examples
---------------------------------------------
def sumop(a,b,c): # Here a,b,c are called Formal Parameters
--------------------
d=a+b+c # Here d is called local Variable

297
-------------------
---------------------
Arguments
---------------------
=>Arguments are also called Variables
=>Arguments are Variables used inside of Function Call.
---------------------
Examples:
---------------------
sumop(10,20,30) # Function call--here 10 20 30 are called Argument Values
OR
x,y,z=10,20,30
sumop(x,y,z) # Function call--- here x,y,z are called Arguments
=>The Relationship between Arguments and Parameters is that Every Value of Argument Must pass to Formal
Parameters

=============================================================
Types of Arguments and Parameters
=============================================================
=The Relationship between Arguments and Parameters is that Every Value of Argument Must pass to Formal
Parameters.
=>Based on Passing the Values of Arguments to Formal Parameters, Arguments are Classifed into 5 types. They
are
1. Possitional Arguments (OR) Parameters
2. Default Arguments (OR) Parameters
3. Keyword Arguments (OR) Parameters
4. Variable Length Arguments (OR) Parameters
5. Keyword Variable Length Arguments (OR) Parameters
=========================================================================
1. Posstional Arguments
=========================================================================
=>Posstional Arguments Mechanism is the default arguments passing mechanism used by PVM in Functions for
Passing the values of Arguments of Function Call to Formal Parameters of Function Defintion.
298
=>Possitional Arguments concept says that Every Argument Value Passing to Every Formal Parameter Based
on their Posstion by maintaining Order and Meaning for Higher Accuracy. In Otherwords The number of
arguments must be equal to Number of Formal Parameters.
=>Possitional Arguments concept always used for Passing Specific Data from Function calls to Function
Definitions.
=>PVM gives High Priority for Possitional Arguments
---------------------------------
Syntax: def functionname(Param1,Param2,....Param-n): # Function Definition
-----------------------------------------------
-----------------------------------------------
Block of Statements--perform Operation
------------------------------------------------
-----------------------------------------------
-------------
Syntax: functioname(arg1,arg2,.....,arg-n) # Function call
=>Here the values of arg1,arg2,.....,arg-n of Function call are passing to Param1,Param2,....Param-n of Function
Definition Respectively.
======================================
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
arguments OR 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".

299
Rule-: When we use default parameters in the function definition, They must be used as last Parameter(s)
otherwise we get Error( SyntaxError: parameter without a default follows parameter with a default)
#Program for Demonstrating Possitional Arguments
#PossArgsEx1.py
def studinfo(sno,sname,marks):
print("\t{}\t{}\t{}".format(sno,sname,marks))
#Main Program
print("="*50)
print("\tSTNO\tNAME\tMARKS")
print("="*50)
studinfo(100,"RS",34.56) # function call
studinfo(200,"TR",45.67) # Function call
studinfo(300,"DR",35.67) # Function call
studinfo(400,"SS",11.11) # Function call
print("="*50)
#Program for Demonstrating Possitional Arguments
#PossArgsEx2.py
def studinfo(sno,sname,marks,crs): # Here sno,sname,marks are called Possitional Parameters
print("\t{}\t{}\t{}\t{}".format(sno,sname,marks,crs))
#Main Program
print("="*50)
print("\tSTNO\tNAME\tMARKS\tCOURSE")
print("="*50)
studinfo(100,"RS",34.56,"PYTHON") # function call--here 100,"RS",34.56,PYTHON are called
Possitional Arguments
studinfo(200,"TR",45.67,"PYTHON") # Function call
studinfo(300,"DR",35.67,"PYTHON") # Function call
studinfo(400,"SS",11.11,"PYTHON") # Function call
print("="*50)

300
#Program for Demonstrating Default Arguments OR Parameters
#DefaultArgsEx1.py
def studinfo(sno,sname,marks,crs="PYTHON"): # Here sno,sname,marks are called Possitional
Parameters and crs is called Default Parameter
print("\t{}\t{}\t{}\t{}".format(sno,sname,marks,crs))
#Main Program
print("="*50)
print("\tSTNO\tNAME\tMARKS\tCOURSE")
print("="*50)
studinfo(100,"RS",34.56) # function call--here 100,"RS",34.56 are called Possitional Arguments
studinfo(200,"TR",45.67) # Function call
studinfo(300,"DR",35.67) # Function call
studinfo(400,"SS",11.11) # Function call
studinfo(500,"SR",34.56,"Java") # Function call
studinfo(600,"XX",21.11) # Function call
print("="*50)
#Program for Demonstrating Default Arguments OR Parameters
#DefaultArgsEx2.py
def studinfo(crs="PYTHON",city="HYD",sno,sname,marks): # here crs and city are called Default
Arguments
print("\t{}\t{}\t{}\t{}\t{}".format(sno,sname,marks,crs,city))
#Main Program
print("="*50)
print("\tSTNO\tNAME\tMARKS\tCOURSE\tCITY")
print("="*50)
studinfo(100,"RS",34.56) # function call--here 100,"RS",34.56 are called Possitional Arguments
studinfo(200,"TR",45.67) # Function call
studinfo(300,"DR",35.67) # Function call
studinfo(400,"SS",11.11) # Function call
studinfo(500,"SR",34.56,"Java") # Function call
studinfo(600,"XX",21.11) # Function call
studinfo(700,"DT",37.11,city="USA")
studinfo(900,"PT",27.11,city="RSA",crs="Java")
301
print("="*50)
============================================
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 bcoz PVM gives First Priority for positional
arguments.
================================================
4) Variables Length Parameters (or) arguments
================================================
=>When we have familiy of multiple Similar 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'>.

302
---------------------------------------------------------------------------------------------------
Syntax for function definition with Variables Length Parameters:
--------------------------------------------------------------------------------------------------
def functionname(list of Posstional 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) .
#Program for Demonstrating Keyward Arguments
#KeyWordsArgsEx1.py
def disp(A,B,C,D):
print("\t{}\t{}\t{}\t{}".format(A,B,C,D))
#Main Program
print("-----------------------------------------------")
print("\tA\tB\tC\tD")
print("-----------------------------------------------")
disp(10,20,30,40) # Function Call with Possitional args
disp(B=20,A=10,D=40,C=30) # Function Call with Keyword args
disp(D=40,C=30,B=20,A=10) # Function Call with Keyword args
disp(10,20,D=40,C=30) # Function Call with Possitional args and Keyword args
disp(10,C=30,B=20,D=40) # Function Call with Possitional args and Keyword args
#disp(C=30,B=20,D=40,10) -----SyntaxError: positional argument follows keyword argument
print("-----------------------------------------------")
#Program for Demonstrating Keyward Arguments
#KeyWordsArgsEx2.py
def dispstudinfo(sno,sname,marks,crs="PYTHON",cnt="INDIA"):
print("\t{}\t{}\t{}\t{}\t{}".format(sno,sname,marks,crs,cnt))

303
#Main Program
print("-"*50)
print("\tSNO\tNAME\tMARKS\tCOURSE\tCOUNTRY")
print("-"*50)
dispstudinfo(100,"RS",34.56) # Function Call with Possitional Args
dispstudinfo(sname="TR",sno=200,marks=88.88) # Function Call with Keyword Args
dispstudinfo(crs="Java",sno=300,sname="DR",marks=55.55,cnt="USA") # Function Call with
Keyword Args
dispstudinfo(400,"SR",cnt="RSA",marks=67.88,crs="HTML") # Function Call with Keyword Args
print("-"*50)
#Program for Demonstrating Variable Length Arguments (OR) Parameters
#VariableArgsLenEx1.py
#This Program will not execute as it is bcoz PVM Remembers Latest Function Definition Only due to its
Interpretation Process.
def dispvals(a,b,c,d,e): # Function Def-1
print(a,b,c,d,e)
def dispvals(a,b,c,d): # Function Def-2
print(a,b,c,d)
def dispvals(a,b,c): # Function Def-3
print(a,b,c)
def dispvals(a,b): # Function Def-4
print(a,b)
def dispvals(a): # Function Def-5
print(a)
#Main Program
dispvals(10,20,30,40,50) # Function Call-1 with 5 Pos Args
dispvals(10,20,30,40) # Function Call-2 with 4 Pos Args
dispvals(10,20,30) # Function Call-3 with 3 Pos Args
dispvals(10,20) # Function Call-4 with 2 Pos Args
dispvals(10) # Function Call-5 with 1 Pos Args

304
#Program for Demonstrating Variable Length Arguments (OR) Parameters
#VariableArgsLenEx2.py
#This Program will execute as it is
def dispvals(a,b,c,d,e): # Function Def-1
print(a,b,c,d,e)
dispvals(10,20,30,40,50) # Function Call-1 with 5 Pos Args
#---------------------------------------------------------------------------------------------
def dispvals(a,b,c,d): # Function Def-2
print(a,b,c,d)
dispvals(10,20,30,40) # Function Call-2 with 4 Pos Args
#---------------------------------------------------------------------------------------------
def dispvals(a,b,c): # Function Def-3
print(a,b,c)
dispvals(10,20,30) # Function Call-3 with 3 Pos Args
#---------------------------------------------------------------------------------------------
def dispvals(a,b): # Function Def-4
print(a,b)

dispvals(10,20) # Function Call-4 with 2 Pos Args


#---------------------------------------------------------------------------------------------
def dispvals(a): # Function Def-5
print(a)

dispvals(10) # Function Call-5 with 1 Pos Args


#---------------------------------------------------------------------------------------------
#Here we have 5 fun calls---->5 fun defs
#In general we have n-fun calls------>n-Fun Def Required--Waste of time
# We are Expecting--- n-fun calls---Define One Function Def....
#Program for Demonstrating Variable Length Arguments (OR) Parameters
#PureVariableArgsLenEx1.py
def dispvals( *a):# here *a is called called Variable Length Parameters and whose type is tuple
print("-"*50)
for v in a:
305
print("{}".format(v),end=" ")
print()

#Main Program
dispvals(10,20,30,40,50) # Function Call-1 with 5 Pos Args
dispvals(10,20,30,40) # Function Call-2 with 4 Pos Args
dispvals(10,20,30) # Function Call-3 with 3 Pos Args
dispvals(10,20) # Function Call-4 with 2 Pos Args
dispvals(10) # Function Call-5 with 1 Pos Args
dispvals() # Function Call-6 with 0 Pos Args
#Program for Demonstrating Variable Length Arguments (OR) Parameters
#PureVariableArgsLenEx2.py
def dispvals(sno,sname, *a):# here *a is called called Variable Length Parameters and whose type is
tuple
print("-"*50)
print("Student Number=",sno)
print("Student Name=",sname)
s=0
for v in a:
print("{}".format(v),end=" ")
s=s+v
print()
print("Sum=",s)
#Main Program
dispvals(100,"RS",10,20,30,40,50) # Function Call-1 with 5 Pos Args
dispvals(200,"DR",10,20,30,40) # Function Call-2 with 4 Pos Args
dispvals(300,"TR",10,20,30) # Function Call-3 with 3 Pos Args
dispvals(400,"SS",10,20) # Function Call-4 with 2 Pos Args
dispvals(500,"KV",10) # Function Call-5 with 1 Pos Args
dispvals(600,"SQ") # Function Call-6 with 0 Pos Args

306
#Program for Demonstrating Variable Length Arguments (OR) Parameters
#PureVariableArgsLenEx3.py
def dispvals(sno,sname,*a, city="HYD"):# here *a is called called Variable Length Parameters and whose type
is tuple
print("-"*50)
print("Student Number=",sno)
print("Student Name=",sname)
print("Student Living City=",city)
s=0
for v in a:
print("{}".format(v),end=" ")
s=s+v
print()
print("Sum=",s)
#Main Program
dispvals(100,"RS",10,20,30,40,50) # Function Call-1 with 5 Pos Args
dispvals(200,"DR",10,20,30,40) # Function Call-2 with 4 Pos Args
dispvals(300,"TR",10,20,30) # Function Call-3 with 3 Pos Args
dispvals(400,"SS",10,20) # Function Call-4 with 2 Pos Args
dispvals(500,"KV",10) # Function Call-5 with 1 Pos Args
dispvals(600,"SQ") # Function Call-6 with 0 Pos Args
dispvals(600,"SQ",1.2,3.4,4.5,city="BANG") # Function Call-6 with 0 Pos Args
#dispvals(city="AP",sname="RA",sno=700,1.5,2.5,3.5)--SyntaxError: positional argument follows keyword
argument

307

You might also like