1 Python Notes 03jun to Jul-07
1 Python Notes 03jun to Jul-07
=========================================
History Development of Python
=========================================
=>The Python Programming Language Conceived in the Year 1980.
=>The Python Programming Language Development or Implementation
began in the year 1989
=>The Python Programming Language Officially released in the year 1991 Feb 20th
=>The Python Programming Language developed by "GUIDO VAN ROSSUM".
=>The Python Programming Language Developed at Centrum Wiskunde Informatica (CWI) Institute in
Nether Lands.
=>The ABC Programming Language is the predecessor of Python Programming Language
==============================================================
Versions of Pythons
==============================================================
=>Python Programming Language contains 3 types of Versions. They are
1) Python 1.x here 1 is called Major Versions and x is called minor Version and x represents 0 1 2 3 4 5
6.......so on
2) Python 2.x here 2 is called Major Versions and x is called minor Version and represents 0 1 2 3 4 5 6, 7
only
3) Python 3.x here 3 is called Major Versions and x is called minor Version and x represents 0 1 2 3 4 5 6,
7 8 9 10 11 12
===========================================
Features of Python
===========================================
=>Features of a language are nothing but Services or Facilities provided by language developers and they
are available in the languages and they are used by Language programmers for developing Real Time
Applications.
=>Python Programming Provides 11 features. They are
1. Simple
2. Freeware and Open Source
3. Platform Independent Lang
4. Dynamically Typed
5. Interpreted
6. High Level
7. Procedure Oriented and Object Oriented
8. Robust (Strong)
9. Extensible
10.Embedded
11. Supports for Third Party APIs like NumPy, Pandas, Scipy,
Scikit,matplotlib...etc
===============================================
1. Simple:
===============================================
=>Python is one of the Simple Programming Language bcoz of 3 Important Technical factors.
1) Python Programming Provides Rich set of APIs. So that Python Programmers can
re-use the pre-defined code without writing our own logic.
-----------------------------------------------------------------------
2) Python Programming lang provides In-built facility called "Garbage Collector and whose role is to
collect un-used memory space and improves the performnace of Python Based Applications.
-----------------------------------------
Def. of Garbage Collector:
-----------------------------------------
=>A Garbage Collector is one of the background python Program which is running in background of our
regular python Program and whose is to collect un-used memory space and improves the performnace of
Python Based Applications.
3) Python Programming Language provides User-Friendly Syntaxes. So that Python programmer can
develop error-free program in limited span of time.
====================================================
3. Platform Indepenedent Lang
====================================================
Concept:-
------------------
=>A lang is said to be Platform Indepenedent Lang if and only if whose application runs on every OS with
having any restriction on memory space".
---------------------------------------
Language Comparision:
---------------------------------------
=>C,CPP are treated Platform Depenedent languages bcoz their data types are taking
different memory space on different OSes.
=>Java is treated Platform Indepenedent Lang bcoz Java Data Types takes same memory space on all
Types of OSes but they takes only single Value. To store multiple values of same tyoe or different type, we
must Classes and Object in Java. Java Objects Can Store Multiple values of same type or different type or
both types with limited Number of Values.
------------------------------------------------------------------------
Python---Platform Indepenedent Lang
-------------------------------------------------------------------------
=>In Python Programming, all vaues are stored in the form objects with un-limited number of values and
memory space restrictions and hence python object are Platform Indepenedent
==================================================
4. Dynamically Typed
==================================================
=>In This context, we have two types programming languages. They are
Examples: Python
Examples: Write the instructions to write sum of two numbers in Python Lang
>>> a=100
>>> b=23.45
>>> c=a+b
>>> print(a,type(a))-------------------- 100 <class 'int'>
>>> print(b,type(b))--------------------- 23.45 <class 'float'>
>>> print(c,type(c))-------------------- 123.45 <class 'float'>
Note:- In python Programming, All Values are stored in the form of Objects and to creater objects there
must exist a class. Otherwise we can't create object.
===============================================
5. Interpreted Programming
===============================================
=>When we develop any python program, we must give some file name with an extension .py (File
Name.py).
=>When we execute python program, two process taken place internally
a) Compilation Process
b) Execution Process.
=>In COMPILATION PROCESS, The python Source Code submitted to Python Compiler and It reads the
source Code, Check for errors by verifying syntaxes and if no errors found then Python Compiler Converts
into Intermediate Code called BYTE CODE with an extension .pyc (FileName.pyc). If erros found in
source code then we error displyed on the console.
=>In EXECUTION PROCESS, The PVM reads the Python Intermediate Code(Byte Code) and Line by
Line and Converted into Machine Understable Code (Executable or binary Code) and It is read by OS and
Processer and finally Gives Result.
=>Hence In Python Program execution, Compilation Process and Execution Process is taking place Line
by Line conversion and It is one of the Interpretation Based Programming Language.
--------------------------------------------------------------
Definition of PVM ( Python Virtual Machine)
--------------------------------------------------------------
=>PVM is one program in Python Software and whose role is to read LINE by LINE of Byte Code and
Converted into Machine Understable Code (Executable or binary Code)
-----------------------------------------------------------------------
================================================
6. High Level Programming
================================================
=>In general, we have two types of Programming languages. They are
a) Low Level Programming Languages.
b) High Level Programming Languages.
--------------------------------------------------------------------------------------------------------------
a) Low Level Programming Languages:
------------------------------------------------------------------
=>In These Programming Languages, we represent the data in lower level data like Binary, Octal and
Hexa decimal and This type data is not by default understanble by Programmers and end users.
Example : Python
=====================================
6. Robust (Strong )
=====================================
=>Python is one of Robust (Strong) bcoz of "Exception Handling".
=>Exception:- Runtime Errors of the Program are called Exceptions
=>Exception by default generages Technocal Error Messages
=>Exception Handling:- The process of converting Technical Error Messages into User Friendly Error
Messages is called Exception Handling.
=>If the Python program uses Exception Handling the Python program is Robust.
-----------------------------------------------------------------------
===================================
9. Extensible
===================================
=>The Python programming giving its programming facilities to other languages and hence Python is one
of the extensible Programming language.
===================================
10. Embedded
===================================
=>Python Programming can call other languages coding segments for fastest execution
1) numpy----Numerical calculations
2) pandas---Analysis tool
-----------------------------------------------------------------
3) matplotlib-----Data Visualization
4) scipy
5) scikit
==========================================
Data Representation
==========================================
=>Data Representation in Python Programming is nothing storing the data in main memory of computer.
=>To store the data in main memory of computer, we need Three things. They are
a) Literals or Values
b) Identifiers or Variables
c) Data Types
-------------------------------------------------------------------------------------------
a) Literals or Values:
---------------------------------
=>Literals are the values entered by Programmer or end user or application user to real time applications.
They are classfied into .
1) Integer Literals (Ex: stno, HTNO, empno, adhar card no.....etc)
2) Float Literals ( Ex: Marks, percentage , gdp of india...etc)
3) String Literals (Ex : Names, Places, Description....etc )
4) Boolean Literals ( Examples: True False)
5) Date Literals ....etc
--------------------------------------------------------------------------------------------------------------
b) Identifiers or Variables:
-------------------------------------------
=>Once the application user enters the data / Literals from Key board to program, It is the responsibility
of Programmer to store data in the form of variables / Identifiers
=>hence all Literals or Values or Data must stored in main memory in the form of Identifiers or Variables
otherwise we can't process the data.
Examples: emp$sal=5.6---invalid
emp-sal=5.6---invalid
emp sal=6.7--invalid
emp_sal=6.7---valid
_emp_sal_ibm=7.8--valid
sal=34---valid
sal#emp=56------valid bcoz the symbol # is used in python
as commenting Symbol.
4) No Keywords to be used Variables Names ( Keywords are reserved words which will have some special
meaning to the language compilers).
Examples:
if=34----inavlid
else=5.6---inavlid
if1=34--valid
_else=5.6--valid
int=23---valid---bcoz all the class names are not
keywords
5) All the variable in Python are Case Sensitive.
EXAMPLES:
>>> age=99----valid
>>> AGE=98---valid
>>> Age=97---valid
>>> aGe=96--valid
>>> print(age,AGE,Age,aGe)----99 98 97 96
6) All Variable Names are recommended to take user-friendly. (Don't take lenghy Variable names and
Take short Variable Names.)
emp_tot_sal=45 # recommended
===================================================
Data Types in Python
===================================================
=>The purpose of Data Types is that " To allocate sufficient amount of memory space for storing input
values or literals in main memory of the computer ".
=>In Python Programming, we have 14 data types and They classified in 6 types.
=================================================
I) Fundamental Data Types
=================================================
=>The purpose of Fundamental 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 single Integer data or Whole Numbers or Integral data (
numbers without decimal values) "
=>Examples:
------------------------------ --------------------------------------------------
Python Instructions Output
------------------------------ --------------------------------------------------
>>> a=100
>>> print(a)------------------------------------------------ 100
>>> type(a)------------------------------------------------- <class 'int'>
>>> id(a)----------------------------------------------------- 1765066345808
>>> print(a, type(a), id(a))--------------------------- 100 <class 'int'> 1765066345808
-----------------------------------------------
>>> a=12
>>> b=13
>>> c=a+b
>>> print(a, type(a))-------------------------------12 <class 'int'>
>>> print(b, type(b))----------------------------- 13 <class 'int'>
>>> print(c, type(c))-------------------------------- 25 <class 'int'>
>>> print(id(a), id(b), id(c))---------------------- 1765066342992 1765066343024 1765066343408
-----------------------------------------------------------------------------------------------------------------------------
=>with 'int' data type, we can store different Number Systems Data.
=>In programming Language including Python, we have 4 Types of Number Systems. They are
Examples:
----------------------
>>> c=0b100+0B101
>>> print(c, type(c))----------------9 <class 'int'>
>>> bin(15)---------------'0b1111'
>>> bin(10)--------------'0b1010'
>>> bin(4)--------------'0b100'
>>> bin(5)--------------'0b101'
>>> a=0b1010102----------------SyntaxError: invalid digit '2' in binary literal
-------------------------------------------------------------------------------------------------------------------------------
3. Octal Number System
------------------------------------------------------------------------------------------------------------------------------
=> Octal Number System understanble by Micro Processor Kits during Program execution.
=>This Number System contains the following digits
Digits: 0 1 2 3 4 5 6 7 ------Total Digits----8
Base: 8
=>hence Base 8 Literals are called Octal Data
=>In python Programming, To store Octal Number System data, The Octal data must be preceded with a
letter '0o' or '0O'.
=>Internally, The Octal data automatically converted into Decimal Number System Data.
Examples:
-----------------
>>> a=0o23
>>> print(a, type(a))----------------------19 <class 'int'>
>>> a=0o123
>>> print(a,type(a))-----------------------83 <class 'int'>
>>> b=0o23+0O123
>>> print(b, type(b))--------------------102 <class 'int'>
>>> oct(19)------------------------------ '0o23'
>>> oct(83)--------------------------------- '0o123'
>>> a=0o18--------------------------SyntaxError: invalid digit '8' in octal literal
--------------------------------------------------------------------------------------------------------------
4. Hexa Deciaml Number System.
------------------------------------------------------
=> Hexa Deciaml Number System used in Operating System Devfelopment.
=>This Number System contains the following digits
Digits: 0 1 2 3 4 5 6 7 8 9
A(10) B(11) C(12) D(13) E(14) F(15) ------Total Digits----16
Base: 16
=>hence Base 16 Literals are called Hexa Deciaml Numbers
=>In python Programming, To store Hexa Deciaml Number System data, The Hexa Deciaml Number
data must be preceded with a letter '0x' or '0X'.
=>Internally, The Hexa Deciaml Number system data automatically converted into Decimal Number
System Data.
Examples:
--------------------
>>> a=0xAC
>>> print(a, type(a))------------------------------------172 <class 'int'>
>>> a=0xBEE
>>> print(a, type(a))---------------------------------3054 <class 'int'>
>>> a=0xBEER-------------------SyntaxError: invalid hexadecimal literal
>>> a=0xACC
>>> print(a, type(a))--------------------2764 <class 'int'>
>>> a=0xface
>>> print(a, type(a))---------------------64206 <class 'int'>
==================================X======================================
Note:
----------
>>> a=0567----SyntaxError: leading zeros in decimal integer literals are not permitted; use an
0o prefix for octal integers
======================================
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 "
=>This data also supperts Scientific Notation. Scientific Notation is one of the alternative notation for Real
Constant values or Floating Point Values. The advantage of Scientific Notation is that To store real
constatnt values in less memory space
=>float data type does not supper Binary , Octal and Hexa Decimal Number System Data. It supports only
default number called Decimal Number System.
--------------------
Examples:
-------------------
>>> a=12.34
>>> print(a,type(a), id(a))----------------------------12.34 <class 'float'> 2569509390480
>>> a=0.99
>>> print(a,type(a), id(a))----------------------------0.99 <class 'float'> 2569509394896
>>> a=3e2
>>> print(a,type(a))-------------------------------------300.0 <class 'float'>
>>> b=10e-2
>>> print(b,type(b))-------------------0.1 <class 'float'>
>>> c=0.00000000000000000000000000000000000000000000000001
>>> print(c,type(c))-------------- 1e-50 <class 'float'>
------------------------------------
Examples:
-------------------------------------
>>> a=0b1111.0b1010------------SyntaxError: invalid decimal literal
>>> b=0o123.0o345------------SyntaxError: invalid decimal literal
>>> c=0xFace.0xBEE-----------SyntaxError: invalid decimal literal
>>> d=0b1010.0o123----------SyntaxError: invalid decimal literal
---------------------------------------------------------------------
========================================
3. bool
========================================
=>'bool is one of the pre-defined class and treated as Fundamental data Type.
=>The purpose of bool data type is that " To store True or False Values (Logical values) ".
=>Here True False are keywords and treated as Values for bool data type.
=>Internally True is taken as 1 and False is Taken as 0.
-----------------------------------------------------------------------------------------------------------------------
Examples:
---------------------
>>> a=True
>>> print(a,type(a))--------------------True <class 'bool'>
>>> b=False
>>> print(b,type(b))-----------------False <class 'bool'>
----------------------------------
>>> c=true---------------------NameError: name 'true' is not defined. Did you mean: 'True'?
>>> d=false------------------NameError: name 'false' is not defined. Did you mean: 'False'?
----------------------------------------------
Examples:
-----------------------------------------------
>>> a=True
>>> b=False
>>> print(a, type(a))-----------------------True <class 'bool'>
>>> print(b, type(b))----------------------False <class 'bool'>
>>> print(a+b)---------------------------- 1
>>> print(a*b)---------------------------- 0
>>> print(True+True+False*True)-------------2
>>> print(True-True+False)------------------0
>>> print(4*True+False*3)------------------4
>>> c=0b1111+True*0.0
>>> print(c)---------------15.0
>>> print(type(c))-----------<class 'float'>
>>> print(0xA+True+0b1010)-------------21
>>> print(2*True+True*3)-----------------5
>>> print(2+True*True+2)------------5
----------------------------------------------------
>>> print(True//True)--------------1
>>> print(False//True)-------------0
>>> print(False//False)------------ZeroDivisionError: integer division or modulo by zero
>>> print(True//False)------------ZeroDivisionError: integer division or modulo by zero
>>> print(23/True)-----------23.0
>>> print(0b1010/True)--------10.0
===============================X======================================
===========================================
4. complex
===========================================
=>'complex' is one of the pre-defined class and treated as Fundamental data Type.
=>The purpose of complex data type is that "To store complex or imaginary data ".
=>The general format complex numbers is given bellow.
a+bj or a-bj
=>Here 'a' is called Real Part and 'b' is called Imaginary Part
=>Here 'j' is represents sqrt(-1)
=>Internally the values of Real and Imaginary are treated as floating point values.
=>To extract or obtain the real and imaginary parts of Complex Object, we use two pre-defined attributes /
Variables present in complex object
a) real
b) imag
=>Syntax: complexobj.real------>Gives Real part of Complex Object.
complexobj.imag----->Gives Imaginary part of Complex Object.
=>On complex data, we can perfom many operation like addition, substraction , multiplication etc
--------------------------------------------------------------------------------------------------------------------------------
Examples:
------------------------
>>> a=2+3j
>>> print(a,type(a))---------------------------(2+3j) <class 'complex'>
>>> b=3-4j
>>> print(b,type(b))--------------------------(3-4j) <class 'complex'>
>>> c=2.3+4.5j
>>> print(c,type(c))---------------------------(2.3+4.5j) <class 'complex'>
>>> d=-2.3-4.5j
>>> print(d,type(d))------------------------(-2.3-4.5j) <class 'complex'>
>>> e=0+3.4j
>>> print(e,type(e))------------------------3.4j <class 'complex'>
-------------------------------------
>>> a=10+2.3j
>>> print(a.real)------------------------- 10.0
>>> print(a.imag)------------------- 2.3
>>> b=-2.3-3.4j
>>> print(b.real)------------------------ -2.3
>>> print(b.imag)---------------------- -3.4
>>> c=0+3j
>>> print(c.real)-------------------------- 0.0
>>> print(c.imag)--------------------------- 3.0
----------------------------------------------------------------------------------------------------------------
>>> a=2+3j
>>> b=3+4j
>>> print(a+b)-------------------(5+7j)
>>> print(a-b)-------------------(-1-1j)
>>> print(a*b)------------------ (-6+17j)
------------------------------------------------------------------------------
>>> print(10+2+3j+True+1.2)-------------(14.2+3j)
======================================================
II) Sequence Categeory Data Types
======================================================
=>The purpose of Sequence Categeory Data Types is that " To store Sequence of Values
=>In Python Programming, we have 4 data types in Sequence Categeory. They are
1. str
2. bytes
3.bytearray
4. range
==================================================
1. str
==================================================
Index
---------
=>Purpose of str
=>Definition of String
=>Types of Strings
=>String Memmory Management
=>Operations of String Data
a) Indexing
b) Slicing
=>Programming Exmaples
===============================================
1. str
===============================================
=>'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 or Text Data ".
---------------------------------
=>Definition of String:
---------------------------------
=>A String is a collection or Sequence of chars enclosed within either Double or Single
Quotes or tripple Double or Single Quotes.
=>Types of Strings:
----------------------------------
=>In Python Programming, we have two types of Strings. They are
1. Single Line String Data
2. Multi Line String Data
-------------------------------------------
1. Single Line String Data:
-------------------------------------------
=>Single Line String Data must be enlcosed within Single or Double Quotes.
=>Syntax:- strobj="Single Line String Data"
(OR)
=>Syntax:- strobj='Single Line String Data'
Examples:
------------------
>>> s1="Python Programming Lang"
>>> print(s1,type(s1))--------------Python Programming Lang <class 'str'>
>>> s2='Python Prog Lang'
>>> print(s2,type(s2))------------------Python Prog Lang <class 'str'>
>>> s3="K"
>>> print(s3,type(s3))----------------K <class 'str'>
>>> s4='V'
>>> print(s4,type(s4))--------------V <class 'str'>
>>> s5="12345"
>>> print(s5,type(s5))---------------12345 <class 'str'>
>>> s6="Python3.10"
>>> print(s6,type(s6))-------------------Python3.10 <class 'str'>
--------------------------------------------------
>>> addr1="Guido van Rossum
Note:- Single Quotes or double Quotes are used for Storing Single Line String Data but used for Multi Liner
String Data.
-------------------------------------------
2. Multi Line String Data:
-------------------------------------------
=>Multi Line String Data must be enlcosed within Tripple Single or Double Quotes.
=>Syntax:- strobj=" " "String Data-1
String data-2
------------------
String Data-n " " "
(OR)
=>Syntax:- strobj=' ' 'String Data-1
String data-2
------------------
String Data-n ' ' '
Examples:
-------------------
>>> addr1="""Guido van Rossum
... 3-4 Hill Side
... Python Software Foundation
... Nether lands-56 """
>>> print(addr1, type(addr1))
Guido van Rossum
3-4 Hill Side
Python Software Foundation
Nether lands-56 <class 'str'>
--------------------------------------------------------
>>> addr2=' ' 'James Gosling
... 23-4, Red Sea Side
... Sun Micro System
... USA-45 ' ' '
>>> print(addr2,type(addr2))
James Gosling
23-4, Red Sea Side
Sun Micro System
USA-45 <class 'str'>
---------------------------------------------------------------------
>>> addr3=" " "Java Programming" " "
>>> addr4=' ' 'Python Programming' ' '
>>> print(addr3,type(addr3))----------------- Java Programming <class 'str'>
>>> print(addr4,type(addr4))-------------------Python Programming <class 'str'>
>>> c1=' ' 'H ' ' '
>>> print(c1,type(c1))------------------ H <class 'str'>
>>> c1=" " " H " " "
>>> print(c1,type(c1))------------------H <class 'str'>
-------------------------------------------------------------------------------------------------------------------------
=================================================
String Memmory Management
=================================================
=>We we store String data in the object of main memeory, Internally it is stored in the form of two types.
They are
1) With Forward Indexing
2) Backward Indexing
=>In ForWard Indexing, Index starts from left ro right with 0 to NumberValues-1 Indexes. (also called +ve
Indexing)
=>In Backward Indexing, Index starts from Right to Left -1 to NumberValues Indexes.(also called -ve
Indexing)
===============================================
Operations on str data
===============================================
=>On str data, we can perform two types of Operations. They are
1. Indexing
2. Slicing
----------------------------------------------------------------------------------------------- -
1. Indexing
---------------------
=>The process of obtaining a character from a given strobj by passing valid index is called Indexing.
=>Syntax:- strobj [ index ]
=>Here Index can be either +ve or -ve
=>if the value of Index is valid then we get Corresponding Character
=>if the value of Index is invalid then we get "IndexError" (It is called one type of error)
----------------
Example:
---------------
>> s="PYTHON"
>>> s[3]-----------------------'H'
>>> s[-3]---------------------'H'
>>> s[-1]---------------------'N'
>>> s[0]-----------------------'P'
>>> s[-6]-------------------'P'
>>> s[-5]-------------------'Y'
>>> s[3]------------------------'H'
>>> s[13]-----------------IndexError: string index out of range
>>> s[-13]----------------IndexError: string index out of range
-------------------------------------------------------------------------------------------------------------------------
2. Slicing : strobj[begin:End]-----------------1
strobj[ : End ]--------------------2
strobj[Begin: ]---------------------3
strobj[ : ]-----------------------------4
strobj[Begin:End:Step]---------5
------------------------------------------------------------------------------------------------------------
=>The process of obtaining range of characters or sub string from Given String is called Slicing.
=>Slicing operation can be performed with 5 syntaxes.
-----------------------------------
Syntax1:- strobj[ Begin:End]
=>This Syntax obtains range of characters or sub strring from given str object from BEGIN INDEX to END
INDEX-1 provided BEGIN<END othertwise we never get any output.
Examples:
------------------
>>> s="PYTHON"
>>> s[0:4]-----------------------------------'PYTH'
>>> s[0:3]----------------------------------'PYT'
>>> s[2:4]----------------------------------'TH'
>>> s[3:6]---------------------------------'HON'
>>> s[2:6]----------------------------------'THON'
>>> s[-6:-2]----------------------------------'PYTH'
>>> s[-3:-1]-----------------------------'HO'
>>> s[-5:-2]----------------------'YTH'
>>> s[6:0]------------------------ ' ' (no result )
>>> s[0:6]------------------------'PYTHON'
>>> s[0:5]---------------------'PYTHO'
>>> s[-6:-1]---------------------'PYTHO'
#Special Cases:
>>> s[2:-2]-----------------------'TH'
>>> s[1:-4]-----------------------'Y'
>>> s[1:-1]------------------------'YTHO'
>>> s[-5:4]-----------------------'YTH'
>>> s[-6:6]-----------------------'PYTHON'
>>> s[0:6]-----------------------'PYTHON'
>>> print(s)---------------------PYTHON
-----------------------------------------------------------------------------------------------------------------
2) Syntax-2: strobj [ : End ]
---------------------------------------------------------------------------
=>In This Syntax we are not specifying Begin Index.
=>If we don't specify Begin Index then PVM Takes First Character Index as Begin Index ( Either +Ve Index or
-ve Index )
=>This syntax also Generates Range of characters from First Character Index (Begin Index) to End Index-1.
Examples:
------------------
>>> s="PYTHON"
>>> print(s)-------------------PYTHON
>>> s[ : 4]---------------------'PYTH'
>>> s[ : 3]--------------------'PYT'
>>> s[ : 6]-------------------'PYTHON'
>>> s[ :-4 ]------------------'PY'
>>> s[ :-3 ]------------------'PYT'
>>> s[ :-1 ]-------------------'PYTHO'
-------------------------------------------------------------------------------------------------------- ----
Syntax-3: strobj [Begin : ]
-----------------------------------------------------------------------------------------------------------------
=>In This Syntax we are not specifying End Index.
=>If we don't specify End Index then PVM Takes Len(strobj)-1 as End Index OR Last
Character Index as End Index Value.
=>This syntax also Generates Range of characters from Begin Index to End Index (
Len(strobj)-1 OR Last Character Index as End Index Value.)
Examples:
----------------------
>>> s="PYTHON"
>>> print(s)----------------------------PYTHON
>>> s[2:]--------------------------------'THON'
>>> s[3:]-------------------------------'HON'
>>> s[0:]------------------------------'PYTHON'
>>> s[4:]------------------------------'ON'
>>> s[-3:]-----------------------------'HON'
>>> s[-6:]------------------------------'PYTHON'
>>> s[-2:]------------------------------'ON'
>>> s="PYTHON"
>>> s-------------------------------------'PYTHON'
>>> s[2:5]------------------------------'THO'
>>> s[2:]-------------------------------'THON'
>>> s[:4]-------------------------------'PYTH'
>>> s[2:-1]----------------------------'THO'
------------------------------------------------------------------------------------ -----------------------
Syntax-4: strobj [ : ]
=>In This Syntax we are not specifying Begin Index and End Index.
=>If we don't specify Begin Index then PVM Takes First Character Index as Begin Index ( Either +Ve Index or
-ve Index ). If we don't specify End Index then PVM Takes Len(strobj)-1 as End Index OR Last Character
Index as End Index Value.
=>This Syntax gives complex Str obj data.
Examples:
-------------------
>>> s="PYTHON"
>>> s-------------------------------'PYTHON'
>>> s[:]---------------------------'PYTHON'
>>> s[0:]----------------------------'PYTHON'
>>> s[:6]---------------------------'PYTHON'
-------------------------------------------------------------
>>> s="Java Programming invaented by James Gosling"
>>> s-----------------------'Java Programming invaented by James Gosling'
>>> s[:]--------------------'Java Programming invaented by James Gosling'
>>> s[10:]--------------'amming invaented by James Gosling'
>>> s[:11]----------------------'Java Progra'
-----------------------------------------------------------------------------------------------------------------------
Syntax-5: strobj[Begin : End : Step ]
--------------------
Rule-1: Here Begin, End and Step can either +Ve or -Ve
Rule-2:- If STEP value is +VE then PVM Takes the characters from Begin Index to End Index-1
in forward Direction by maintaining equal Value of STEP provided BEGIN<END
Rule-3:- If STEP value is -VE then PVM Takes the characters from Begin Index to End Index+1
in backward Direction by maintaining equal Value of STEP provided BEGIN>END
Rule-4: When we extract the for data in forward direction and if the END Index is 0 then we
never get any output
Rule-5: When we extract the for data in Backward direction and if the END Index is -1 then we never get any
output
Examples:
------------------------
>>> s="PYTHON"
>>> s[0:5:2]------------------------------'PTO'
>>> s[0:6:3]------------------------------'PH'
>>> s="PYTHON"
>>> s[0:6:1]------------------------------'PYTHON'
>>> s[0:6:2]------------------------------'PTO'
>>> s[0:6:3]------------------------------'PH'
>>> s[2:6:3]------------------------------'TN'
>>> s[5:6:3]------------------------------'N'
>>> s[0:5:-1]-----------------------------''
>>> s[5:0:-1]-----------------------------'NOHTY'
>>> s[4:2:-1]-----------------------------'OH'
>>> s[-1:-6:-1]---------------------------'NOHTY'
>>> s[-6:-1:-1]---------------------------''
>>> s[::-1]--------------------------------'NOHTYP'
>>> s[4::-1]------------------------------'OHTYP'
>>> s[::-2]--------------------------------'NHY'
>>> s[::-3]--------------------------------'NT'
>>> s="JAVA"
>>> s[::-1]--------------------------------'AVAJ'
>>> s[::]----------------------------------'JAVA'
>>> s[::2]--------------------------------'JV'
>>> s[::-2]-------------------------------'AA'
>>> s="LIRIL"
>>> s[::]==s[::-1]-----------------------True
>>> "PYTHON"[::-1]------------------'NOHTYP'
>>> "PYTHON"[::-1][0:4]------------'NOHT'
>>> "PYTHON"[::-1][0:4:2]----------'NH'
>>> s="PYTHON"
>>> s[:0:1]--------------------------------''
>>> s[:-1:-1]------------------------------''
>>> s="PYTHON"
>>> s[0:234]------------------------------'PYTHON'
>>> s[0:234:-1]---------------------------''
>>> s[234::-1]-----------------------------'NOHTYP'
====================================================
2. bytes
====================================================
=>'bytes' is one of the Pre-defined Data Types and terated as Sequence Data Type.
=>The purpose of bytes data type is that " To store Sequence of Numerical Possitive Integer
Values ranges from (0,256) "
=>In the python programming, we don't have any symbolic notation for representing the elements by using
bytes data type. But we can convert Other Type of Values into Bytes object type by using bytes()
>>> for x in b:
... print(x)
...
0
10
20
30
40
255
>>> print(b[0])----------------------100
>>> print(b[1])-----------------------200
>>> print(b[-11])-------------------IndexError: index out of range
>>> print(b[-1])-----------------255
>>> print(b[-3])-----------------34
>>> x=b[0:4] # Slicing Operation
>>> print(x,type(x))------------b'd\xc8\x0c"' <class 'bytes'>
>>> for v in x:
... print(v)
...
100
200
12
34
====================================================
3. bytearray
====================================================
=>'bytearray' is one of the Pre-defined Data Types and terated as Sequence Data Type.
=>The purpose of bytearray data type is that " To store Sequence of Numerical Possitive Integer Values ranges
from (0,256) "
=>In the python programming, we don't have any symbolic notation for representing the elements by using
bytearray data type. But we can convert Other Type of Values into array object type by using bytearray()
>>> for x in b:
... print(x)
...
0
10
20
30
40
255
>>> print(b[0])----------------------100
>>> print(b[1])-----------------------200
>>> print(b[-11])-------------------IndexError: index out of range
>>> print(b[-1])-----------------255
>>> print(b[-3])-----------------34
>>> x=b[0:4] # Slicing Operation
>>> print(x,type(x))------------b'd\xc8\x0c"' <class 'bytes'>
>>> for v in x:
... print(v)
...
100
200
12
34
>>> b[0]=123----------------valid
>>> for v in b:
... print(v)
...
123
200
12
34
0
255
----------------------------------------------------------------------------------------------------------------------------- -------
====================================================
Mutable and Immutable objects in python
====================================================
---------------------------
Mutable object:
---------------------------
=>A Mutable object is one which allows to update / modify / change the values at the same address.
=>Examples: List, set, dict...etc
--------------------------------------------------------------------------------------------------------------------------------
Immutable object:
---------------------------
=>An Immutable object is one which will satisfy the following Properties.
a) Never allows us to modify to at same address (In Otherwords Values can
modified and placed in different Address)
b) Never allows us to do Item Assignment
(or)
does not support item assignment
====================================================
4. range
====================================================
=>"range" is one of the pre-defined class and treated as Sequence Data Type.
=>The purpose of range data type is that " To store Sequnece of Numerical Integer Values by
maintaining equal Interval of value"
=>range data type is one of the immutable object
=>on the object of range data type , we can perform Both Indexing and Slicing Operations.
=>range data type contains 3 syntaxes. They are
1) range(value)
2) range(Begin, End)
3) range(Begin,End,Step)
------------------------------------------------------------------------------------------------
Syntax-1: varname=range(value)
-------------------------
=>This Syntax generates range of values from 0 to value-1
=>Here varname is an object of <class,"range">
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
>>> print(r[0])---------------------0
>>> print(r[-1])--------------------5
>>> for val in r[::-1]:
... print(val)
...
5
4
3
2
1
0
>>> for val in r[0:3]:
... print(val)
...
0
1
2
>>> for val in r:
... print(val)
...
0
1
2
3
4
5
Examples:
------------------
>>> r=range(10,21)
>>> print(r,type(r))-----------------range(10, 21) <class 'range'>
>>> for val in r:
... print(val)
...
10
11
12
13
14
15
16
17
18
19
20
>>> for val in range(100,106):
... print(val)
...
100
101
102
103
104
105
>>> for val in range(1000,1006):
... print(val,end=" ")-------------- 1000 1001 1002 1003 1004 1005
=>Syntax-1 and Syntax-2, the default value of Step is 1 which is nothing but equal Interval of value.
---------------------------------------------------------------------------------------------------------------------------------
----
Syntax-3: varname=range(Begin , End,Step)
-------------------------
=>This Syntax generates range of values from Begin to End-1 by maintaining Equal Interval of value with
Step Value (Interval value )
=>Here varname is an object of <class,"range">
Examples:
-------------------
>>> r=range(10,21,2)
>>> print(r,type(r))------------------------range(10, 21, 2) <class 'range'>
>>> for v in r:
... print(v)
...
10
12
14
16
18
20
>>> for v in range(100,121,5):
... print(v)
...
100
105
110
115
120
>>> for v in range(100,151,10):
... print(v)
...
100
110
120
130
140
150
>>> for v in range(100,160,10):
... print(v)
...
100
110
120
130
140
150
========================================================================
Examples:
------------------------
Q 1)Generate 0 1 2 3 4 5 6 7 8 9 ----- range(10)
-----------------------------------------------------------------------------------------------------------------
>>> for val in range(10):
... print(val)
...
0
1
2
3
4
5
6
7
8
9
-----------------------------------------------------------------------------------------------------------------
Q 2) Generate 10 11 12 13 14 15 16 17 18 19 20---range(10,21)
-----------------------------------------------------------------------------------------------------------------
>>> for val in range(10,21):
... print(val)
...
10
11
12
13
14
15
16
17
18
19
20
-----------------------------------------------------------------------------------------------------------------
Q3) Generate 100 102 104 106 108 110------range(100,111,2)
-----------------------------------------------------------------------
>>> for val in range(100,111,2):
... print(val)
...
100
102
104
106
108
110
-----------------------------------------------------------------------------------------------------------------
Q4) Generate -1 -2 -3 -4 -5 -6 -7 -8 -9 -10----range(-1, -11, -1)
-----------------------------------------------------------------------------------------------------------------
>>> for val in range(-1, -11, -1):
... print(val)
...
-1
-2
-3
-4
-5
-6
-7
-8
-9
-10
-----------------------------------------------------------------------------------------------------------------
Q5) Generate 120 115 110 105 100 ------- range(120, 99 , -5)
-----------------------------------------------------------------------
>>> for val in range(120, 99 , -5):
... print(val)
...
120
115
110
105
100
-----------------------------------------------------------------------------------------------------------------
Q6) Generate 10 9 8 7 6 5 4 3 2 1-----range(10,0,-1)
-----------------------------------------------------------------------
>>> for val in range(10,0,-1):
... print(val)
...
10
9
8
7
6
5
4
3
2
1
------------------------------------------------------------------
Q7) Generate -10 -9 -8 -7 -6 -5------------------ range(-10, -4, 1)
-------------------------------------------------------------------
>>> for val in range(-10, -4, 1):
... print(val)
...
-10
-9
-8
-7
-6
-5
-----------------------------------------------------------------------
Q8) Generate -10 -15 -20 -25 -30 -35---------------range(-10,-36, -5)
>>> for val in range(-10,-36, -5):
... print(val)
...
-10
-15
-20
-25
-30
-35
--------------------------------------------------------------------
Q9) generate 100 80 60 40 20 0-----range(100,-1,-20)
>>> for val in range(100,-1,-20):
... print(val)
...
100
80
60
40
20
0
-----------------------------------------------------------------------
Q 10) Generate 1000 750 500 250 0----range(1000,-1,-250)
-----------------------------------------------------------------------
>>> for val in range(1000,-1,-250):
... print(val)
...
1000
750
500
250
0
-----------------------------------------------------------------------
Q 11) Generate -5 -4 -3 -2 -1 0 1 2 3 4 5------ range(-5, 6, 1)
----------------------------------------------------------------------
>>> for val in range(-5, 6, 1):
... print(val)
...
-5
-4
-3
-2
-1
0
1
2
3
4
5
----------------------------------------------------------------------------------------------------------------
MiSc. Examples:
----------------------------
>>> for val in r[::2][::-1]:
... print(val)
...
120
118
116
114
112
110
108
106
104
102
100
>>> print(r[::2][::-1][0])---------------------120
>>> for val in r[::2][::-1][0:3]:
... print(val)
...
120
118
116
-----------------------------------------------------------------------
================================================
Type Casting techniques in Python
================================================
=>The Process of Converting One type of Possible value into another Type of value is Called Type
Casting.
=>In Python Programming, we have 5 types of 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 )
----------------------------------------------------------------------------
Example1: float type----> 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.0009
>>> print(a,type(a))--------------0.0009 <class 'float'>
>>> b=int(a)
>>> print(b,type(b))-------------0 <class 'int'>
-----------------------------------------------------------------------
Example2: bool type----> int type----->Possible
-----------------------------------------------------------------------
>>> a=True
>>> print(a, type(a))------------------------True <class 'bool'>
>>> b=int(a)
>>> print(b,type(b))-------------------------1 <class 'int'>
>>> a=False
>>> print(a, type(a))-----------------------False <class 'bool'>
>>> b=int(a)
>>> print(b,type(b))----------------------- 0 <class 'int'>
----------------------------------------------------------------------------
Example3: Complex type----> int type----->Not Possible
-----------------------------------------------------------------------------------
>>> a=2+3j
>>> print(a, type(a))------------------(2+3j) <class 'complex'>
>>> b=int(a)-----TypeError not possible convert 'complex' value into int type.
--------------------------------------------------------------------------------------------------------------------------
Example-4: Strings------>Int
--------------------------------------------------------------------------------------------------------------------------
Case-1:
-------------
>>> a="10" # str int------>int----> Possible
>>> print(a, type(a))-----10 <class 'str'>
>>> b=int(a)
>>> print(b,type(b))--------10 <class 'int'>
------------------
Case-2: # Str float------> int--->Not Possible
------------------
>>> a="12.34" #str float
>>> print(a, type(a))-----------------12.34 <class 'str'>
>>> b=int(a)---------------ValueError: invalid literal for int() with base 10: '12.34'
------------------
Case-3: # Str bool------> int--->Not Possible
--------------------
>>> a="True"
>>> print(a, type(a))-----------------True <class 'str'>
>>> b=int(a)-----------------ValueError: invalid literal for int() with base 10: 'True'
-------------------------------------------
Case-4: # Str Complex-----int------->Not Possible
-----------------------------------
>>> a="2+3j"
>>> print(a, type(a))----------------2+3j <class 'str'>
>>> b=int(a)--------------ValueError: invalid literal for int() with base 10: '2+3j'
-------------------------------------
Case-4: # Pure Str-----int------->Not Possible
-----------------------------------
>>> a="Python"
>>> print(a, type(a))-------------------Python <class 'str'>
>>> b=int(a)-------------ValueError: invalid literal for int() with base 10: 'Python'
>>> a="THREE"
>>> print(a, type(a))-----------THREE <class 'str'>
>>> b=int(a)------------ValueError: invalid literal for int() with base 10: 'THREE'
-------------------------------------------------------------------------------------------------------------------------
===========================================
2. float()
===========================================
=>float() is used for Converting One Type of Possible Value into float type value.
=>Syntax:- varname=float( int / bool / complex / str )
----------------------------------------------------------------------------
Example1: int type----> float type----->Possible
----------------------------------------------------------------------------
>>> a=100
>>> print(a, type(a))-------------100 <class 'int'>
>>> b=float(a)
>>> print(b,type(b))--------------100.0 <class 'float'>
----------------------------------------------------------------------------
Example2: bool type----> float type----->Possible
----------------------------------------------------------------------------
>>> a=True
>>> print(a, type(a))-------------------True <class 'bool'>
>>> b=float(a)
>>> print(b,type(b))-------------------1.0 <class 'float'>
>>> a=False
>>> print(a, type(a))------------------False <class 'bool'>
>>> b=float(a)
>>> print(b,type(b))-------------------0.0 <class 'float'>
-----------------------------------------------------------------------
Example3: complex type----> float type----->Not Possible
-----------------------------------------------------------------------
>>> a=2+3j
>>> print(a, type(a))------------------(2+3j) <class 'complex'>
>>> b=float(a)-----------------TypeError: float() argument must be a string or a real number, not 'complex'
-------------------------------------------------------------------------------------
Example4: Str data ---> float
----------------------------------------------------------------------------
Case-1: Str int----->float----> Possible
-----------------
>>> a="12"
>>> print(a, type(a))------------------12 <class 'str'>
>>> b=float(a)
>>> print(b,type(b))-----------------12.0 <class 'float'>
----------------------------------------------------------------------------
Case-2: Str float----->float---->Possible
-----------------
>>> a="12.34" # str float
>>> print(a, type(a))------------12.34 <class 'str'>
>>> b=float(a)
>>> print(b,type(b))----------12.34 <class 'float'>
----------------------------------------------------------------------------
Case-3: Str bool----->float---->Not Possible
-----------------
>>> a="True"
>>> print(a, type(a))
True <class 'str'>
>>> b=float(a)----------------ValueError: could not convert string to float: 'True'
-------------------------------------------------------------------------------
Case-4: Str complex----->float---->Not Possible
-----------------
>>> a="2+3j" # Str Complex
>>> print(a, type(a))--------------2+3j <class 'str'>
>>> b=float(a)-----------ValueError: could not convert string to float: '2+3j'
-------------------------------------------------------------------
Case-5: Pure Str ----->float---->Not Possible
-----------------
>>> a="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 bool type value.
=>Syntax:- varname=bool( int / float / complex / str )
=>ALL NON-ZERO VALUES ARE CONSIDERED AS TRUE
=>ALL ZERO VALUES ARE CONSIDERED AS FALSE
----------------------------------------------------------------------------
Example1: int type----> bool type----->Possible
----------------------------------------------------------------------------
>>> a=123
>>> print(a, type(a))-------------------123 <class 'int'>
>>> b=bool(a)
>>> print(b,type(b))-------------------True <class 'bool'>
>>> a=-234
>>> print(a, type(a))-----------------234 <class 'int'>
>>> b=bool(a)
>>> print(b,type(b))----------------True <class 'bool'>
>>> a=0
>>> print(a, type(a))---------------0 <class 'int'>
>>> b=bool(a)
>>> print(b,type(b))----------------False <class 'bool'>
----------------------------------------------------------------------------
Example2: float type----> bool type----->Possible
----------------------------------------------------------------------------
>>> a=12.34
>>> print(a, type(a))------------12.34 <class 'float'>
>>> b=bool(a)
>>> print(b,type(b))-------------True <class 'bool'>
>>> a=0.00000000000000000000000000000000000000000001
>>> print(a, type(a))-------------1e-44 <class 'float'>
>>> b=bool(a)
>>> print(b,type(b))------------True <class 'bool'>
>>> a=0.00000000000000
>>> print(a, type(a))--------------0.0 <class 'float'>
>>> b=bool(a)
>>> print(b,type(b))--------------False <class 'bool'>
---------------------------------------------------------------------------------
Example3: complex type----> bool type----->Possible
----------------------------------------------------------------------------
>>> a=2+3j
>>> print(a, type(a))---------(2+3j) <class 'complex'>
>>> b=bool(a)
>>> print(b,type(b))-------------True <class 'bool'>
>>> a=0+0j
>>> print(a, type(a))--------------0j <class 'complex'>
>>> b=bool(a)
>>> print(b,type(b))-----------False <class 'bool'>
-------------------------------------------------------------------------------------
Example4: str type----> bool type
----------------------------------------------------------------------------
Case-1: str int-------->bool----Possible
--------------
>>> a="1234"
>>> print(a, type(a))--------------------1234 <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'>
>>> len(a)------------------------------1
>>> a=" "
>>> print(a, type(a))-------------- <class 'str'>
>>> len(a)-----------------------5
>>> b=bool(a)
>>> print(b,type(b))---------------True <class 'bool'>
>>> a=""
>>> print(a, type(a))-------------- <class 'str'>
>>> len(a)----------------------- 0
>>> b=bool(a)
>>> print(b,type(b))---------------False <class 'bool'>
----------------------------------------------------------------
Case-1: str float-------->bool----Possible
--------------
>>> a="12.34"
>>> print(a, type(a))----------------12.34 <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))---------------True <class 'bool'>
>>> a="0.0"
>>> print(a, type(a))------------0.0 <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))-------------True <class 'bool'>
>>> len(a)---------------3
----------------------------------------------------------------
Case-3: str complex-------->bool----Possible
--------------
>>> a="2+3j"
>>> print(a, type(a))---------------2+3j <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))---------------True <class 'bool'>
>>> a="0+0j"
>>> print(a, type(a))------------0+0j <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))----------------True <class 'bool'>
----------------------------------------------------------------
Case-4: str bool-------->bool----Possible
--------------
>>> a="True"
>>> print(a, type(a))--------------True <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))-------------True <class 'bool'>
>>> a="False"
>>> print(a, type(a))-------------False <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))-----------True <class 'bool'>
----------------------------------------
Case-5: pure str -------->bool----Possible
--------------
>>> a="Python"
>>> print(a, type(a))-------------Python <class 'str'>
>>> b=bool(a)
>>> print(b,type(b))------------True <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 )
--------------------------------------------------------------------------------------------------
Example1: int type----> complex type----->Possible
----------------------------------------------------------------------------
>>> a=10
>>> print(a, type(a))-----------10 <class 'int'>
>>> b=complex(a)
>>> print(b,type(b))-------------(10+0j) <class 'complex'>
----------------------------------------------------------------------------------
Example2: float type----> complex type----->Possible
----------------------------------------------------------------------------
>>> a=12.34
>>> print(a, type(a))------------12.34 <class 'float'>
>>> b=complex(a)
>>> print(b,type(b))---------------(12.34+0j) <class 'complex'>
----------------------------------------------------------------------
Example3: bool type----> complex type----->Possible
-----------------------------------------------------------------------
>>> a=True
>>> print(a, type(a))-------------------True <class 'bool'>
>>> b=complex(a)
>>> print(b,type(b))-----------------(1+0j) <class 'complex'>
>>> a=False
>>> print(a, type(a))-----------------False <class 'bool'>
>>> b=complex(a)
>>> print(b,type(b))------------------0j <class 'complex'>
--------------------------------------------------------------------------------------
Example4: Str type----> complex type
----------------------------------------------------------------------------
Case-1: str int------complex type-----Possible
----------------------------------------------------------------------------
>>> a="12"
>>> print(a, type(a))-----------------12 <class 'str'>
>>> b=complex(a)
>>> print(b,type(b))-------------(12+0j) <class 'complex'>
----------------------------------------------------------------------------
Case-2: str float------complex type-----Possible
----------------------------------------------------------------------------
>>> a="1.2"
>>> print(a, type(a))---------------1.2 <class 'str'>
>>> b=complex(a)
>>> print(b,type(b))--------------(1.2+0j) <class 'complex'>
---------------------------------------------------------------------------------
Case-3: str bool------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: pure str ------complex type-----Not Possible
----------------------------------------------------------------------------
>>> a="Python"
>>> print(a, type(a))---------------Python <class 'str'>
>>> b=complex(a)------------ValueError: complex() arg is a malformed string
-------------------------------------------------------
Misc Examples:
----------------------------------
>>> b=complex(bool("Python"))
>>> print(b,type(b))--------------(1+0j) <class 'complex'>
>>> b=complex(bool(float(int(345))))
>>> print(b,type(b))----------------(1+0j) <class 'complex'>
------------------------------------------------------------------------------------
>>> b=complex(0b1010)
>>> print(b,type(b))-------------------------(10+0j) <class 'complex'>
>>> b=complex(float(0b1010))
>>> print(b,type(b))---------------------------(10+0j) <class 'complex'>
>>> b=complex(float(0b1010.0xA))----------SyntaxError: invalid decimal literal
------------------------------------------------------------------------------------------------------------------------
===========================================
5. str()
===========================================
=>str() is used for Converting All types Values into str type value.
=>Syntax:- varname=str( int / float / bool / complex )
-----------------------------------------------------------------------
>>> a=123
>>> print(a, type(a))------------------123 <class 'int'>
>>> b=str(a)
>>> print(b,type(b))-------------------123 <class 'str'>
>>> a=12.34
>>> print(a, type(a))--------------12.34 <class 'float'>
>>> b=str(a)
>>> print(b,type(b))--------------12.34 <class 'str'>
>>> a=True
>>> print(a, type(a))-------------True <class 'bool'>
>>> b=str(a)
>>> print(b,type(b))---------------True <class 'str'>
>>> a=2+3.4j
>>> print(a, type(a))------------(2+3.4j) <class 'complex'>
>>> b=str(a)
>>> print(b,type(b))----------(2+3.4j) <class 'str'>
==========================================================================
III) List Categeory Data Types ( Collection Data Types or Data Structures)
==========================================================================
=>The purpose of List Categeory Data Types is that " To store Multiple Values either of same type or different
type or both the types with duplicate and Unique values".
=========================================
1) list
=========================================
Index:
-----------
=>Properties of list
=>List types
=>List mem mgmt
=>Operations on list
a) Indexing
b) Slicing
=>Pre-defined Functions in list
=>Inner or nested List
=>Pre-defined Functions in inner list
=>Programming Examples
-------------------------------
Properties of list:
-------------------------------
=>"list" is one of the pre-defined class and treated as list data type.
=>The purpose of list data type is that " To store Multiple Values either of same type or
different type or both the types with duplicate and Unique values".
=>The elements or Values of list must be written (or) enclosed within Square Brackets.
=>An object of list maintains Insertion order.
=>On the object of list object we can perform Both Indexing and Slicing Operations.
=>An object of list belongs to Mutable.
=>We can create 2 types of list objects. They are
1. Empty List
2. Non-Empty List
----------------------
1.Empty List:
----------------------
=>An empty list is one which does not contain any elements and whose length is 0
=>Syntax:- listobj=[ ]
(OR)
listobject=list()
----------------------
2.Non-Empty List:
----------------------
=>An non-empty list is one which contains elements and whose length is > 0
=>Syntax:- listobj=[Val1,Val2,.............Val-n]
----------------------------------------------------------------------------------------
Examples:
-----------------
>>> l1=[10,20,30,40,-23,15]
>>> print(l1,type(l1))----------------------------------[10, 20, 30, 40, -23, 15] <class 'list'>
>>> l2=[10,"Rossum",22.22,"Python",True]
>>> print(l2,type(l2))-----------------------------------[10, 'Rossum', 22.22, 'Python', True] <class 'list'>
>>> l3=[10,10,10,"Python","Python",34.56]
>>> print(l3,type(l3))-----------------------[10, 10, 10, 'Python', 'Python', 34.56] <class 'list'>
>>> len(l1)------------6
>>> len(l2)---------5
>>> len(l3)----------6
---------------------------------
>>> l4=[]
>>> print(l4,type(l4))----------------[] <class 'list'>
>>> len(l4)---------------------------- 0
>>> l5=list()
>>> print(l5,type(l5))------------------[] <class 'list'>
>>> len(l5)------------------------------- 0
-----------------------------------------------------------------------
>>> l2=[10,"Rossum",22.22,"Python",True]
>>> print(l2,type(l2),id(l2))----[10, 'Rossum', 22.22, 'Python', True] <class 'list'> 2974731208512
>>> l2[0]-------------10
>>> l2[1]-----------'Rossum'
>>> l2[-1]-------------True
>>> l2[-3]---------------22.22
>>> l2[1:4]---------------['Rossum', 22.22, 'Python']
>>> l2[::]---------------[10, 'Rossum', 22.22, 'Python', True]
>>> l2[::-1]-------------[True, 'Python', 22.22, 'Rossum', 10]
>>> l2[::2]-------------[10, 22.22, True]
>>> l2[1::2]----------------['Rossum', 'Python']
>>> l2[::-2]-----------------[True, 22.22, 10]
>>> l2[::-2][0]-------------True
>>> l2[::-2][10]------------IndexError: list index out of range
------------------------------------------------------
>>> l1=[10,20,30]
>>> ba=bytearray(l1)
>>> print(ba,type(ba))-----------------bytearray(b'\n\x14\x1e') <class 'bytearray'>
>>> l2=list(ba)
>>> print(l2,type(l2))-----------------[10, 20, 30] <class 'list'>
--------------------------------------------------------------
>>> l2=[10,"Rossum",22.22,"Python",True]
>>> print(l2,type(l2),id(l2))--[10, 'Rossum', 22.22, 'Python', True] <class 'list'> 2974731208512
>>> l2[0]=100
>>> print(l2,type(l2),id(l2))--[100, 'Rossum', 22.22, 'Python', True] <class 'list'> 2974731208512
=======================================x===============================
========================================
Pre-defined Functions in list
========================================
=>Along with the operations of lndexing and Sliciing on list object, we can also perform
various operations on list object by using predefined functions present in list object.
------------------------
1) append():
------------------------
=>This function is used for adding the value to the list object always at end.
=>Syntax:- listobj.append(Value)
----------------
Examples:
----------------
>>> l1=[]
>>> print(l1,type(l1),id(l1))----------------------[] <class 'list'> 2974735360640
>>> len(l1)----------------------------0
>>> l1.append(10)
>>> print(l1,type(l1),id(l1))-------------------[10] <class 'list'> 2974735360640
>>> l1.append("KVR")
>>> l1.append("Python")
>>> l1.append("Java")
>>> print(l1,type(l1),id(l1))-----[10, 'KVR', 'Python', 'Java'] <class 'list'> 2974735360640
---------------------------------------------------------------------------------------------------
2) insert() :
----------------------------------------------------------------------------------------------------
=>This Function is used for inserting the specifed value in list object at perticular Index.
=>Syntax: listobj.insert(Index,Value)
=>Here Index Can be either +Ve Index ort -ve Index.
Examples:
-----------------
>>> l1=[10,"Rossum",34.45]
>>> print(l1,type(l1),id(l1))---------[10, 'Rossum', 34.45] <class 'list'> 2974731208512
>>> l1.insert(2,"Python")
>>> print(l1,type(l1),id(l1))----------[10, 'Rossum', 'Python', 34.45] <class 'list'> 2974731208512
>>> l1[-1]=55.55 # Updated
>>> print(l1,type(l1),id(l1))--------[10, 'Rossum', 'Python', 55.55] <class 'list'> 2974731208512
----------------------------------------------------------------------------------------------------
3) remove(): ---based on Value
-----------------------------------
=>This Function is used for removing the First Occurence of specified value from list object.
=>If the specfied value does not exist then we get ValueErrort.
=>Syntax:- listobj.remove(value)
Examples:
-------------------
>>> l1=[10,"Rossum",34.45]
>>> print(l1,type(l1),id(l1))-----------[10, 'Rossum', 34.45] <class 'list'> 2974731208512
>>> l1.remove(10)
>>> print(l1,type(l1),id(l1))-------------['Rossum', 34.45] <class 'list'> 2974731208512
>>> l1.remove(34.45)
>>> print(l1,type(l1),id(l1))---------['Rossum'] <class 'list'> 2974731208512
>>> l1.remove(120)-------------ValueError: list.remove(x): x not in list
------------------------------------------------------------------
>>> l1=[10,"Rossum",10,"Python",10]
>>> print(l1,type(l1),id(l1))--------[10, 'Rossum', 10, 'Python', 10] <class 'list'> 2974735360832
>>> l1.remove(10)
>>> print(l1,type(l1),id(l1))-------['Rossum', 10, 'Python', 10] <class 'list'> 2974735360832
>>> l1.remove(10)
>>> print(l1,type(l1),id(l1))--------['Rossum', 'Python', 10] <class 'list'> 2974735360832
>>> l1.remove(10)
>>> print(l1,type(l1),id(l1))----['Rossum', 'Python'] <class 'list'> 2974735360832
>>> l1.remove(10)-----------ValueError: list.remove(x): x not in list
--------------------------------------------------------------------------------------------------------------------
4) pop(index): ---based on Index
---------------------------------------------
=>This function is used for removing an element of list based on Index.
=>Syntax:- listobj.pop(Index)
=>here Index can be either +ve or -ve
=>If the index is invalid then we get IndexError.
-------------------
Examples:
--------------------
>>> print(l1,type(l1),id(l1))------------[10, 'Rossum', 'Python', 10] <class 'list'> 2974731208512
>>> l1.pop(-1)----------------10
>>> print(l1,type(l1),id(l1))----------[10, 'Rossum', 'Python'] <class 'list'> 2974731208512
>>> l1.pop(-2)-----------'Rossum'
>>> print(l1,type(l1),id(l1))---------[10, 'Python'] <class 'list'> 2974731208512
>>> l1.pop(11)------------IndexError: pop index out of range
==========================
>>> l1=[10,20,30]
>>> print(l1)----------------[10, 20, 30]
>>> l1.pop(0)--------------10
>>> l1.pop(0)-------------20
>>> l1.pop(1)----------IndexError: pop index out of range
>>> l1.pop(0)----------30
>>> l1.pop(1)----------IndexError: pop from empty list
======================
>>> l=list()
>>> l.pop(0)------------IndexError: pop from empty list
>>> list().pop(2)-------------IndexError: pop from empty list
>>> list().remove(0)--------ValueError: list.remove(x): x not in list
---------------------------------------------------------------------------------------------------------------------------
5) pop():
------------------------
=>This function is used for removing last element of of list but latest inserted element.
=>Syntax:-
listobj.pop()
Examples:
--------------------
>>> l1=[10,"Rossum",10,"Python",10]
>>> print(l1,type(l1),id(l1))-----------[10, 'Rossum', 10, 'Python', 10] <class 'list'> 2974735360768
>>> l1.pop()--------------10
>>> print(l1,type(l1),id(l1))---------[10, 'Rossum', 10, 'Python'] <class 'list'> 2974735360768
>>> l1.pop()--------------'Python'
>>> print(l1,type(l1),id(l1))--------[10, 'Rossum', 10] <class 'list'> 2974735360768
>>> l1.pop()----------10
>>> print(l1,type(l1),id(l1))---------[10, 'Rossum'] <class 'list'> 2974735360768
>>> l1.pop()------------'Rossum'
>>> print(l1,type(l1),id(l1))----------[10] <class 'list'> 2974735360768
>>> l1.pop()----------10
>>> print(l1,type(l1),id(l1))-------------[] <class 'list'> 2974735360768
>>> l1.pop()--------------------IndexError: pop from empty list
>>> list().pop()---------------IndexError: pop from empty list
>>> l1=[10,"Rossum",10,"Python",10]
>>> l1.pop()-----------------10
>>> print(l1,type(l1),id(l1))---------[10, 'Rossum', 10, 'Python'] <class 'list'> 2974735360960
>>> l1.insert(2,"Java")
>>> print(l1,type(l1),id(l1))-----[10, 'Rossum', 'Java', 10, 'Python'] <class 'list'> 2974735360960
>>> l1.pop()-----------'Python'
>>> print(l1,type(l1),id(l1))--------[10, 'Rossum', 'Java', 10] <class 'list'> 2974735360960
>>> l1.pop()-----------10
>>> print(l1,type(l1),id(l1))-----------[10, 'Rossum', 'Java'] <class 'list'> 2974735360960
-----------------------------------------------------------------------
Note: del operator
-----------------------------
=>'del' operator is used for deleting the element(s) of any object either based on indexing or slicing or
complete object.
Syntax:- del objectname[index] # Based on Indexing
6) count():
------------------
=>This function is used finding number of occurences of elements in list
=>Syntax:- listobj.count()
-------------------
Examples:
-------------------
>>> l1=[10,20,30,10,40,20,50,60,10,20]
>>> print(l1)-------------------------[10, 20, 30, 10, 40, 20, 50, 60, 10, 20]
>>> l1.count(10)-----------3
>>> l1.count(20)-----------3
>>> l1.count(40)----------1
>>> l1.count(400)----------0
>>> l1=["apple","orange","kiwi","apple","apple"]
>>> l1.count("apple")----------------3
>>> l1.count("sberry")------------0
-----------------------------------------------------------------------------------------------------------
7) index() :
----------------------
=>This Function is used for finding Index of first occurence of specified value from list object.
=>if a specified value is not present list object then we get ValueError
=>Syntax: listobj.index(Value)
--------------------
Examples:
--------------------
>>> l1=[10,20,30,10,40,20,50,60,10,20]
>>> print(l1)-----------------[10, 20, 30, 10, 40, 20, 50, 60, 10, 20]
>>> l1.index(10)-----------0
>>> l1=["Python","Java","Data Sci","Django"]
>>> print(l1)--------------['Python', 'Java', 'Data Sci', 'Django']
>>> l1.index("Java")-----------1
>>> l1.index("Data Sci")--------2
>>> l1.index("PHP")----------ValueError: 'PHP' is not in list
>>> l1.index("python")----------ValueError: 'python' is not in list
---------------------------------------------------------------------------------------------------
8) copy():
----------------------------
=>This Function is used for copying the content of one object into another object ( implements Shallow
Copy)
=>Syntax:- listobj2=listobj1.copy()
Examples:---Shallow Copy
--------------------
>>> l1=[10,"RS"]
>>> print(l1,id(l1))---------------------[10, 'RS'] 2967238870848
>>> l2=l1.copy() # Shallow Copy
>>> print(l2,id(l2))--------------------[10, 'RS'] 2967238884672
>>> l1.append("Python")
>>> l2.append("DS")
>>> print(l1,id(l1))----------------[10, 'RS', 'Python'] 2967238870848
>>> print(l2,id(l2))---------------[10, 'RS', 'DS'] 2967238884672
----------------------------------------------------------------------------------------
Examples: # Slicce Based Copy----Shallow Copy
----------------------------------------------------------------------------------------
>>> l1=[10,20,30,40,50]
>>> print(l1,id(l1))-----------------[10, 20, 30, 40, 50] 2967238884672
>>> l2=l1[::] # Slicce Based Copy----Shallow Copy
>>> print(l2,id(l2))--------------------[10, 20, 30, 40, 50] 2967238870848
>>> l2.remove(10)
>>> l1.pop()-------------------50
>>> print(l1,id(l1))------------------[10, 20, 30, 40] 2967238884672
>>> print(l2,id(l2))----------------[20, 30, 40, 50] 2967238870848
------------------------------------------
Examples:--Deep Copy
------------------------------------------
>>> l1=[10,"RS"]
>>> print(l1,id(l1))------------------[10, 'RS'] 2967243016192
>>> l2=l1 # Deep Copy
>>> print(l2,id(l2))----------------[10, 'RS'] 2967243016192
>>> l1.append("Python")
>>> print(l1,id(l1))-----------------[10, 'RS', 'Python'] 2967243016192
>>> print(l2,id(l2))----------------[10, 'RS', 'Python'] 2967243016192
>>> l2.insert(2,"DS")
>>> print(l1,id(l1))-----------------[10, 'RS', 'DS', 'Python'] 2967243016192
>>> print(l2,id(l2))-------------[10, 'RS', 'DS', 'Python'] 2967243016192
----------------------------------------------------------------------------------------------------------------
9) extend():
----------------------------------
=>This function is used for extending the functionality of Source list object with Destination list object.
=>Syntax: Sourcelistobject.extend(Destinationlistobject)
Examples:
-----------------
>>> l1=[10,20,30,40] # ----Source List
>>> l2=["Python","Data Sci","Django"] # Destination list object
>>> l1.extend(l2)
>>> print(l1)-----------[10, 20, 30, 40, 'Python', 'Data Sci', 'Django']
>>> print(l2)-----------['Python', 'Data Sci', 'Django']
-------------------------------------------------------
>>> l1=[10,20,30,40]
>>> l2=["Python","Data Sci","Django"]
>>> l3=["Oracle","MySQL","MongoDB"]
>>> l1.extend(l2,l3)---------TypeError: list.extend() takes exactly one argument (2 given)
>>> #___________________OR________________________________________________
>>> l1=l1+l2+l3 # Here we are using + operator instead of extend()
>>> print(l1)---[10, 20, 30, 40, 'Python', 'Data Sci', 'Django', 'Oracle', 'MySQL', 'MongoDB']
>>> print(l2)------['Python', 'Data Sci', 'Django']
>>> print(l3)------['Oracle', 'MySQL', 'MongoDB']
---------------------------------------------------------------------
10) reverse()
---------------------------------------------------------------------
=>This Function is used for obtaining Reverse of elements of List ( front to back and back to front)
=>Syntax:- listobj.reverse()
-------------------
Examples:
-------------------
>>> l1=[10,20,30,40]
>>> print(l1)-------------[10, 20, 30, 40]
>>> l1.reverse()
>>> print(l1)--------------[40, 30, 20, 10]
Examples:
--------------------
>>> l1=[10,2,56,23,12,-5,0,34,12]
>>> print(l1)--------------------------[10, 2, 56, 23, 12, -5, 0, 34, 12]
>>> l1.sort()
>>> print(l1)---------------------------[-5, 0, 2, 10, 12, 12, 23, 34, 56]
>>> l1.reverse()
>>> print(l1)---------------------[56, 34, 23, 12, 12, 10, 2, 0, -5]
-------------------------------------------
>>> l1=[10,2,56,23,12,-5,0,34,12]
>>> print(l1)
[10, 2, 56, 23, 12, -5, 0, 34, 12]
>>> l1.sort(reverse=True)
>>> print(l1)-------------------------------[56, 34, 23, 12, 12, 10, 2, 0, -5]
=-------------------------------------------------------------
>>> l1=[10,2,56,23,12,-5,0,34,12]
>>> print(l1)----------------------------------[10, 2, 56, 23, 12, -5, 0, 34, 12]
>>> l1.sort(reverse=False)
>>> print(l1)----------------------------------[-5, 0, 2, 10, 12, 12, 23, 34, 56]
-----------------------------------------------------------------------------------------
>>> l1=["Trump","Modiji","Putin","Sachin","Rohit","Rossum"]
>>> print(l1)-------------['Trump', 'Modiji', 'Putin', 'Sachin', 'Rohit', 'Rossum']
>>> l1.sort()
>>> print(l1)-----------------['Modiji', 'Putin', 'Rohit', 'Rossum', 'Sachin', 'Trump']
--------------------------------------------------------------------------------
>>> l1=["Trump","Modiji","Putin","Sachin","Rohit","Rossum"]
>>> print(l1)-------------------------------['Trump', 'Modiji', 'Putin', 'Sachin', 'Rohit', 'Rossum']
>>> l1.sort(reverse=True)
>>> print(l1)-------------['Trump', 'Sachin', 'Rossum', 'Rohit', 'Putin', 'Modiji']
--------------------------------------------------------------------------------
>>> l1=[10,"Rossum",34.56,2+3j,True]-----------Heterogenous values
>>> print(l1)-------------------[10, 'Rossum', 34.56, (2+3j), True]
>>> l1.sort()-----------TypeError: '<' not supported between instances of 'str' and 'int'
-----------------------------------------------------------------------
==============================================
Types of Copy Techniques
==============================================
=>In Python Programming, we have two types of Copy Techniques. They are
1. Shallow Copy
2. Deep Copy
-----------------------------------------------------------------------------------------------------------------------
1) Shallow Copy:
----------------------------------------------------------------------------------------------------------------------
=>Shallow Copy will satisfy the following Properties.
a) Intial Content of Both Objects are Same
b) The memory address of Both Objects are Different.
c) Modification are Independent( When we do some change in one object and
it
will not reflect to another object)
-----------------------------
Examples:
-----------------------------
>>> l1=[10,"RS"]
>>> print(l1,id(l1))------------------[10, 'RS'] 2967243016192
>>> l2=l1 # Deep Copy
>>> print(l2,id(l2))----------------[10, 'RS'] 2967243016192
>>> l1.append("Python")
>>> print(l1,id(l1))-----------------[10, 'RS', 'Python'] 2967243016192
>>> print(l2,id(l2))----------------[10, 'RS', 'Python'] 2967243016192
>>> l2.insert(2,"DS")
>>> print(l1,id(l1))-----------------[10, 'RS', 'DS', 'Python'] 2967243016192
>>> print(l2,id(l2))-------------[10, 'RS', 'DS', 'Python'] 2967243016192
------------------------------------------------------------------------
================================================
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] ,......val-n ]
I want to store sno,sname , list of internal marks, External Marks and College Name
lst=[10,"Ram",15,17,14,70,67,72, "OUCET"]
(OR)
==============================================
2) tuple
==============================================
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 either of same type or
different type or both the types with duplicate and Unique values".
=>The elements or Values of tuple must be written (or) enclosed within Braces ( ) .
=>An object of tuple maintains Insertion order.
=>On the object of tuple we can perform Both Indexing and Slicing Operations.
=>An object of tuple belongs to immutable.
=>We can create 2 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:- ltupleobj=()
(OR)
tupleobject=tuple()
----------------------
2.Non-Empty tuple:
----------------------
=>An non-empty tuple is one which contains elements and whose length is > 0
=>Syntax:- tupleobj=( Val1,Val2,.............Val-n )
Note:- The Functionality of tuple is extactly similar to list but list object belongs to mutable and tuple
belongs to immutable.
--------------------------------------------------------------------------------------------------------------------------
>>> t1=(10,20,30,10,20)
>>> print(t1,type(t1))------------------------------(10, 20, 30, 10, 20) <class 'tuple'>
>>> t2=(10,"Rossum",44.44,"Python",3+4j,True)
>>> print(t2,type(t2))---------------(10, 'Rossum', 44.44, 'Python', (3+4j), True) <class 'tuple'>
>>> t2[0]--------------10
>>> t2[2]----------44.44
>>> t2[-1]----------True
>>> t2[::-1]---------(True, (3+4j), 'Python', 44.44, 'Rossum', 10)
>>> len(t1)----------5
>>> len(t2)---------6
---------------------------------------------------------
>>> t3=()
>>> t4=tuple()
>>> print(t3,type(t3))-----------() <class 'tuple'>
>>> print(t4,type(t4))-------------() <class 'tuple'>
>>> len(t3)----------0
>>> len(t4)---------0
-----------------------------------------------------------------------------
>>> t2=(10,"Rossum",44.44,"Python",3+4j,True)
>>> print(t2)--------------------(10, 'Rossum', 44.44, 'Python', (3+4j), True)
>>> t2[0]=100-----------TypeError: 'tuple' object does not support item assignment
-----------------------------------------
>>> l1=[10,20,34.56,67]
>>> print(l1)-------------------[10, 20, 34.56, 67]
>>> t1=tuple(l1)
>>> print(t1)-----------------(10, 20, 34.56, 67)
==============================================
pre-defined function in tuple
==============================================
=>tubple object contains 2 pre-defined functions. They are
1. count()
2. index()
Examples:
------------------
>>> t1=(10,10,10,20,30,40,20)
>>> t1.count(10)----------3
>>> t1.count(20)---------2
>>> t1.count(40)--------1
>>> t1.count(400)---------0
>>> t1=(10,"Ram",44.44)
>>> t1.index("Ram")----------1
>>> t1.index(10)-------------0
>>> t1.index(100)----------ValueError: tuple.index(x): x not in tuple
NOTE: tuple object does not contain the following Function, bcoz tuple is immutable
=============================================
inner or nested tuple
=============================================
=>The Process of defining onetuple inside of another tuple is called Inner or Nested tuple.
=>Syntax: tplobj= ( val1, val2.....( val11,val12,...val1n) ,......val-n )
=> Inside of tuple, one can write inner tuple and also inner list
=>Inside of list, one can write inner tuple and also inner list
--------------------------
Examples:
--------------------------
>>> t1=(10,"Ram",(10,20,30),[50,60,70], "OUCET" )
>>> print(t1,type(t1))-------------(10, 'Ram', (10, 20, 30), [50, 60, 70], 'OUCET') <class 'tuple'>
>>> t1[2]---------(10, 20, 30)
>>> t1[3]--------[50, 60, 70]
>>> print(t1,type(t1))-------------(10, 'Ram', (10, 20, 30), [50, 60, 70, 77], 'OUCET') <class 'tuple'>
---------------------------------------------------------------------------------------------------------
>>> l1=[10,"Ram",(10,20,30),[50,60,70], "OUCET" ]
>>> print(l1,type(l1))-------------[10, 'Ram', (10, 20, 30), [50, 60, 70], 'OUCET'] <class 'list'>
---------------------------------------------------------------------------------------------------------------
Note:
----------
sorted():
----------------
=>It is one of the general pre-defined function , which is used for sorting tuple object data in Ascending
order and returns Sorted Elements innbthe form list.
=>Syntax:- listobj=sorted(tuple obj)
Examples:
------------------
>>> t1=(10,12,4,6,-4,0,33)
>>> t1.sort()-----------AttributeError: 'tuple' object has no attribute 'sort'
>>> k=sorted(t1)
>>> print(k,type(k))---------[-4, 0, 4, 6, 10, 12, 33] <class 'list'>
>>> #_____________OR___________________
>>> l=list(t1)
>>> print(l)-------------------[10, 12, 4, 6, -4, 0, 33]
>>> l.sort()
>>> t=tuple(l)
>>> print(t)--------------------(-4, 0, 4, 6, 10, 12, 33)
========================================================================
IV) Set Categeory Data Types ( Collection Data Types or Data Structures)
=>=>The purpose of Set Categeory Data Types is that " To store Multiple Values either of same type or
different type or both the types with Unique values".
=>In Python programming, we have two data types in Set Categeory. They are
1. set (Both Immutable and Mutable)
2. frozenset (immutable)
================================================
1.set
================================================
=>Properties of set:
---------------------------------
=>'set' is one of the pre-defined class and treated as Set Data Types.
=>The purpose of set data type is that To store Multiple Values either of same type or different type or
both the types with Unique values".
=>The elements of set must organized within curly braces { } and whose elements separated semi colon.
=>An object of set never maintains insertion order bcoz PVM dusplay any possibility of elements of set.
=>Since object of set never maintains insertion order and hence we can't perform Indexing and slicing
Operations.
=>An object of set belongs to Both immutable bcoz set' object does not support item assignment and
mutable bcoz we can add elements to set object by using add().
=>We have two types of set objects. They are
a) empty set
b) non-empty set
------------------
a) empty set:
------------------
=>An empty set is one, which contains elements and whose length is equal to 0
=>Syntax:- setobj=set() # setobj={}---is invalid
---------------------------
b) non-empty set:
---------------------------
=>An non-empty set is one, which contains elements and whose length is >0
=>Syntax:- setobj={v1,v2....vn}
-----------------------------------------------------------------------------------------------------------------------
Examples:
--------------------
>>> s1={10,20,30,40,50,60,10,10}
>>> print(s1,type(s1))-------------------{50, 20, 40, 10, 60, 30} <class 'set'>
>>> len(s1)---------------6
>>> s2={"Python","Java","Django","Data Sci","Python"}
>>> print(s2,type(s2))------------------{'Python', 'Data Sci', 'Java', 'Django'} <class 'set'>
>>> s3={10,"Rossum",34.56,True,2+3j}
>>> print(s3,type(s3))--------------{True, 34.56, 'Rossum', 10, (2+3j)} <class 'set'>
>>> len(s2)-----------------4
>>> len(s3)-----------------5
--------------------------------------------------
>>> s1={}
>>> print(s1,type(s1))-----------{} <class 'dict'>
>>> s1=set()
>>> print(s1,type(s1))-----------set() <class 'set'>
>>> len(s1)--------------------0
--------------------------------
>>> s3={10,"Rossum",34.56,True,2+3j}
>>> s3[0]--------------------TypeError: 'set' object is not subscriptable
>>> s3[0:4]--------------TypeError: 'set' object is not subscriptable
--------------------------------------------------------------
================================================
Pre-defined Functions in set
================================================
=>On the object of set, we can perform various operations by using the pre-defined functions of set.
=>The folowing are the function of set.
-----------------------------------------------------------------------------------------------------
1) add()
-----------------------------------------------------------------------------------------------------
=>This Function is used for adding the elements to set object
=>Syntax:- setobj1.add(Value)
=>Examples:
-----------------------
>>> s1=set()
>>> print(s1,type(s1),id(s1))-----------------set() <class 'set'> 2175600857536
>>> len(s1)-------------0
>>> s1.add(10)
>>> s1.add("Python")
>>> s1.add(12.34)
>>> print(s1,type(s1),id(s1))-------------{'Python', 10, 12.34} <class 'set'> 2175600857536
>>> len(s1)------------3
------------------------------------------------------
2) clear():
------------------
=>This function is used removing all the elements of set.
=>Syntax: setobj.clear()
-------------------
Examples:
-------------------
>>> s3={10,"Rossum",34.56,True,2+3j}
>>> print(s3,id(s3))------------------{True, 34.56, 'Rossum', 10, (2+3j)} 2175600858432
>>> len(s3)---------------5
>>> s3.clear()
>>> print(s3,id(s3))-----------set() 2175600858432
>>> len(s3)----------------0
------------------------------------------------------------------------------------------------
3) remove() :
----------------------------------------------------
=>This function is used for removing an element from set object.
=>If element does not exist in set object then we get KeyError( bcoz elements of set are unique and unique
elements are called Keys)
=>Syntax: setobj.remove(Element)
------------------
Examples:
------------------
>>> s3={10,"Rossum",34.56,True,2+3j}
>>> print(s3,id(s3))-------------{True, 34.56, 'Rossum', 10, (2+3j)} 2175600856640
>>> s3.remove(34.56)
>>> print(s3,id(s3))--------------{True, 'Rossum', 10, (2+3j)} 2175600856640
>>> s3.remove(True)
>>> print(s3,id(s3))-----------{'Rossum', 10, (2+3j)} 2175600856640
>>> s3.remove("Python")-----------KeyError: 'Python'
-----------------------------------------------------------------------
4) discard():
-----------------------------------------------------------------------
=>This Function is used removing the element from set object
=>If element does not exist in set object then we never get KeyError
=>Syntax:- setobj.discard(element)
Examples:
-------------------
>>> s3={10,"Rossum",34.56,True,2+3j}
>>> print(s3,id(s3))--------------{True, 34.56, 'Rossum', 10, (2+3j)} 2175600858432
>>> s3.discard("Rossum")
>>> print(s3,id(s3))---------------{True, 34.56, 10, (2+3j)} 2175600858432
>>> s3.discard(2+3j)
>>> print(s3,id(s3))--------------{True, 34.56, 10} 2175600858432
>>> s3.discard("Rossum")-----No Error
>>> s3.discard("Java")-----No Error
>>> s3.remove("Java")-------KeyError: 'Java'
-----------------------------------------------------------------------
5) pop():
-----------------------------------------------------------------------
=>This Function is used for removing any arbitrary Element from set object.
=>if we use pop() on empty set then we get KeyError
=>Syntax: setobj.pop()
---------------
Examples:
---------------
>>> s3={10,"Rossum",34.56,True,2+3j}
>>> s3.pop()-------------------True
>>> s3.pop()--------------34.56
>>> s3.pop()-------------'Rossum'
>>> s3.pop()------------10
>>> s3.pop()-------------(2+3j)
>>> print(s3,id(s3))---------set() 2175600857536
>>> s3.pop()----------KeyError: 'pop from an empty set'
>>> set().pop()-----------KeyError: 'pop from an empty set'
>>> s1={10,20,30,40,50,60,10}
>>> s1.pop()-----------50
>>> s1.pop()---------20
>>> s1.pop()-----------40
>>> s1.pop()------------10
>>> s1.pop()----------60
>>> s1.pop()------------30
>>> s1.pop()--------KeyError: 'pop from an empty set'
--------------------------------------------------------------------
Note:
--------
>>> {10,20,30,40,50,60,10}.pop()----------50
>>>s1=set()
>>>s1.pop()-----------KeyError: 'pop from an empty set'
>>>set().pop()-------KeyError: 'pop from an empty set'
-----------------------------------------------------------------------
6) copy():
--------------------------------
=>This Function is used for copying the content of one set object into another set object ( shallow copy)
=>Syntax: setobj2=setobj1.copy()
Examples:
----------------
>>> s1={"Apple","Mango","kiwi","Sberry","Guava","Orange"}
>>> s2=s1.copy() # shallow Copy
>>> print(s1,id(s1))-----------{'Mango', 'kiwi', 'Sberry', 'Apple', 'Guava', 'Orange'} 2175600858432
>>> print(s2,id(s2))----------{'Mango', 'kiwi', 'Sberry', 'Apple', 'Guava', 'Orange'} 2175600857984
>>> s1.add("Java")
>>> s2.add("python")
>>> print(s1,id(s1))---{'Mango', 'kiwi', 'Java', 'Sberry', 'Apple', 'Guava', 'Orange'}
2175600858432
>>> print(s2,id(s2))--------{'Mango', 'kiwi', 'Sberry', 'Apple', 'python', 'Guava', 'Orange'}
2175600857984
Note:
------------
>>> s1=set()
>>> s2=s1.copy()
>>> print(s1,id(s1))----------set() 2175600856192
>>> print(s2,id(s2))---------set() 2175600856640
--------------------------------------------------------------------------------------------------------
7) issuperset():---
-------------------------
Syntax: setobj1.issuperset(setobj2)
=>This function Returns True provided all elements of setobj2 present in setobj1. Otherwise it return
False.
Examples:
-----------------
>>> S1={10,20,30,40,50}
>>> S2={10,20}
>>> S3={10,60,70}
>>> S1.issuperset(S2)---------True
>>> S1.issuperset(S3)-----------False
Note:
----------
>>> S1.issuperset(set())----------------True
>>> set().issuperset(set())-------------True
---------------------------------------------------------------------------------------------------------
8) issubset():---
-------------------------
Syntax: setobj1.issubset(setobj2)
Examples:
---------------
>>> s1={10,20,30,40,50}
>>> s2={40,50}
>>> s3={10,40,70}
>>> s2.issubset(s1)----------------True
>>> s3.issubset(s1)-------------False
Note:
---------
>>> set().issubset(s1)--------True
>>> set().issubset(set())-------True
-----------------------------------------------------------------------------------------------------------
9) isdisjoint():
-------------------------
Syntax: setobj1.isdisjoint(setobj2)
=>This Function Returns True provided setobj1 and setobj2 does not contains any common element(s).
Otherwise it return False.
Examples:
----------------
>>> s1={10,20,30,40,50}
>>> s2={40,60,70}
>>> s3={"Python","Django"}
>>> s1.isdisjoint(s3)--------------True
>>> s1.isdisjoint(s2)-----------False
----------------------------------------------
>>> s1={"Sachin","Rohit","Kohli"}
>>> s2={"Rossum","Ritche","Travis"}
>>> s3={"Sachin","MC"}
>>> s1.isdisjoint(s2)------------True
>>> s1.isdisjoint(s3)-----------False
----------------------------------------------------
>>> s1={"Sachin","Rohit","Kohli"}
>>> s1.isdisjoint(set())-----------True
>>> set().isdisjoint(set())-----------True
--------------------------------------------------------------------------------------------------------
10) union():
-------------------------------------
=>Syntax:- setobj3=setobj1.union(setobj2)
=>This Function is used for obtaining all the elements from both setobj1 and setobj2 uniquely.
Examples:
-----------------
>>> cp={"Sachin","Rohit","Kohli","Pandey"}
>>> tp={"Kohli","Ramesh","Rajesh"}
>>> cptp=cp.union(tp)
>>> print(cptp)---------------{'Rajesh', 'Pandey', 'Ramesh', 'Kohli', 'Rohit', 'Sachin'}
(OR)
>>> cptp=tp.union(cp)
>>> print(cptp)---------------{'Rajesh', 'Pandey', 'Rohit', 'Kohli', 'Ramesh', 'Sachin'}
-------------------------------------------------------------------------------------------------------------
11) intersection() :
-------------------------------------
=>Syntax:- setobj3= setobj1. intersection (setobj2)
=>This Function is used for obtaining common elements from both setobj1 and setobj2
Examples:
--------------------
>>> cp={"Sachin","Rohit","Kohli","Pandey"}
>>> tp={"Kohli","Ramesh","Rajesh"}
>>> bothcptp=cp.intersection(tp)
>>> print(bothcptp)---------------{'Kohli'}
>>> bothcptp=tp.intersection(cp)
>>> print(bothcptp)------------------{'Kohli'}
----------------------------------------------------------------------------------------------------------------------------
12) difference():
------------------------------------
=>Syntax: setobj3=setobj1.difference(setobj2)
=>This Function removes the common elements from setobj1 and setobj2 and takes and display remain
elements of setobj1.
Examples:
------------------
>>> cp={"Sachin","Rohit","Kohli","Pandey"}
>>> tp={"Kohli","Ramesh","Rajesh"}
>>> onlycp=cp.difference(tp)
>>> print(onlycp)-----------{'Pandey', 'Rohit', 'Sachin'}
>>> onlytp=tp.difference(cp)
>>> print(onlytp)----------------{'Rajesh', 'Ramesh'}
--------------------------------------------------------------------------------------------------------------------------------
13) symmetric difference()
--------------------------------------------------------------------------------------------------------------------------------
=>Syntax: setobj3=setobj1.symmetric_difference(setobj2)
=>=>This Function removes the common elements from setobj1 and setobj2 and takes and display remain
elements from both setobj1 and setobj2 and place them in setobj3.
Examples:
--------------------
>>> cp={"Sachin","Rohit","Kohli","Pandey"}
>>> tp={"Kohli","Ramesh","Rajesh"}
>>> exclcptp=cp.symmetric_difference(tp)
>>> print(exclcptp)--------------------{'Rohit', 'Sachin', 'Rajesh', 'Pandey', 'Ramesh'}
------------------------OR-----------------------------------------------------
>>> exclcptp=cp.union(tp).difference(cp.intersection(tp))
>>> print(exclcptp)-------------{'Rohit', 'Sachin', 'Rajesh', 'Pandey', 'Ramesh'}
--------------------------------------------------------------------------------------------------------------------------------
14)update():
---------------------------
=>Syntax:- setobj1.update(setobj2)
=>This function updates or adding all the unique values of setobj2 to setobj1.
Examples:
-------------------------
>>> s1={10,"Rajesh"}
>>> s2={"Python","Data Science"}
>>> s1.update(s2)
>>> print(s1)-----------------{10, 'Rajesh', 'Data Science', 'Python'}
>>> print(s2)---------------{'Data Science', 'Python'}
>>> s3={"Oracle","MySQL","MongoDB"}
>>> s1.update(s3)
>>> print(s1)-------------------{'Oracle', 'MongoDB', 'Rajesh', 'Python', 10, 'Data Science', 'MySQL'}
---------------------------------------------
>>> s1={10,"Rajesh"}
>>> s2={10,20}
>>> s1.update(s2)
>>> print(s1)------------------{10, 'Rajesh', 20}
--------------------------------------------------------------------
=================================================
2. frozenset
=================================================
=>Properties of 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 of same type or different type
or both the types with Unique values".
=>The elements of frozenset always represented by converting other type of elements (set, tuple,list..etc)
by using frozenset() bcoz frozenset set does not cointain any symbolic notation.
=>Syntax:- frozensetobj=frozenset(object)
=>An object of frozenset never maintains insertion order bcoz PVM display any possibility of elements of
frozenset.
=>Since object of frozenset never maintains insertion order and hence we can't perform Indexing and
slicing Operations.
=>An object of frozenset belongs to immutable bcoz frozenset' object does not support item assignment
and never allows to add the elements externally.
=>We have two types of frozenset objects. They are
a) empty frozenset
b) non-empty frozenset
------------------
a) empty frozenset:
------------------
=>An empty frozenset is one, which contains elements and whose length is equal to 0
=>Syntax:- frozensetobj=frozenset()
---------------------------
b) non-empty frozenset:
---------------------------
=>An non-empty frozenset is one, which contains elements and whose length is >0
=>Syntax:- frozensetobj=frozenset( {v1,v2....vn} )
frozensetobj=frozenset( (v1,v2....vn) )
frozensetobj=frozenset( [v1,v2....vn] )
Note:
-----------
=>The Functionality of frozenset is similar to set and set object belongs to both mutable and immutable
where as frozenset belongs to only immutable.
=======================================================================
Examples:
---------------------
>>> s1={10,20,30,40,50}
>>> print(s1,type(s1))---------------{50, 20, 40, 10, 30} <class 'set'>
>>> fs=frozenset(s1)
>>> print(fs,type(fs))-----------------frozenset({50, 20, 40, 10, 30}) <class 'frozenset'>
>>> t1=(10,"Rossum","Python",34.56)
>>> print(t1,type(t1))----------------(10, 'Rossum', 'Python', 34.56) <class 'tuple'>
>>> fs1=frozenset(t1)
>>> print(fs1,type(fs1))--------------frozenset({10, 'Rossum', 34.56, 'Python'}) <class 'frozenset'>
>>> l1=[10,10,20,20]
>>> print(l1,type(l1))------------------[10, 10, 20, 20] <class 'list'>
>>> fs2=frozenset(l1)
>>> print(fs2,type(fs2))-----------------frozenset({10, 20}) <class 'frozenset'>
>>> len(fs)--------------5
>>> len(fs1)------------4
>>> len(fs2)-------------2
>>> fs3=frozenset()
>>> print(fs3,type(fs3))--------------frozenset() <class 'frozenset'>
>>> len(fs3)----------------0
>>> fs[0]----------------TypeError: 'frozenset' object is not subscriptable
>>> fs[0:3]----------------TypeError: 'frozenset' object is not subscriptable
>>> fs[0]=100------------TypeError: 'frozenset' object does not support item assignment
>>> fs1.add(100)----------AttributeError: 'frozenset' object has no attribute 'add'
================================X======================================
=================================================
pre-defined function in frozenset
=================================================
=>Frozenset contains the following Functions.
1) copy
2) isuperset()
3) issubset()
4) isdisjoint()
5) union()
6) intersection()
7) difference()
8) symmetric_diffence()
Examples:
-----------------
>>> fs2=fs1.copy()
>>> print(fs1,id(fs1))------------- frozenset({40, 10, 20, 30}) 2547261088128
>>> print(fs2,id(fs2))---------------frozenset({40, 10, 20, 30}) 2547261088128
------------------------------------------
>>> fs1=frozenset({10,20,30,40})
>>> fs2=frozenset((100,20,300,400))
>>> fs1----------------frozenset({40, 10, 20, 30})
>>> fs2----------------frozenset({400, 100, 20, 300})
>>> fs1.issuperset(fs2)-------------False
>>> fs1.issubset(fs2)---------------False
>>> fs1.issubset({10,20})------------False
>>> fs1.issubset(frozenset({10,20,30,40,50,60}))-----------True
----------------------------------------------------------------------
>>> fs1----------------------frozenset({40, 10, 20, 30})
>>> fs2----------------------frozenset({400, 100, 20, 300})
>>> fs3=fs1.union(fs2)
>>> print(fs3)--------------------frozenset({100, 40, 10, 300, 400, 20, 30})
>>> fs4=fs1.intersection(fs2)
>>> print(fs4)---------------frozenset({20})
>>> fs5=fs1.difference(fs2)
>>> print(fs5)---------------------frozenset({40, 10, 30})
>>> fs6=fs2.difference(fs1)
>>> print(fs6)---------------------frozenset({400, 100, 300})
>>> fs7=fs2.symmetric_difference(fs1)
>>> print(fs7)------------------frozenset({100, 40, 10, 300, 400, 30})
--------------------------------------------------------------------------------------------------------
Note: Frozenset does not contain the following Functions.
6) copy():
--------------------------------
=>This Function is used for copying the content of one set object into another set object ( shallow copy)
=>Syntax: setobj2=setobj1.copy()
Examples:
----------------
>>> s1={"Apple","Mango","kiwi","Sberry","Guava","Orange"}
>>> s2=s1.copy() # shallow Copy
>>> print(s1,id(s1))-----------{'Mango', 'kiwi', 'Sberry', 'Apple', 'Guava', 'Orange'} 2175600858432
>>> print(s2,id(s2))----------{'Mango', 'kiwi', 'Sberry', 'Apple', 'Guava', 'Orange'} 2175600857984
>>> s1.add("Java")
>>> s2.add("python")
>>> print(s1,id(s1))---{'Mango', 'kiwi', 'Java', 'Sberry', 'Apple', 'Guava', 'Orange'}
2175600858432
>>> print(s2,id(s2))--------{'Mango', 'kiwi', 'Sberry', 'Apple', 'python', 'Guava', 'Orange'}
2175600857984
Note:
------------
>>> s1=set()
>>> s2=s1.copy()
>>> print(s1,id(s1))----------set() 2175600856192
>>> print(s2,id(s2))---------set() 2175600856640
--------------------------------------------------------------------------------------------------------
7) issuperset():---
-------------------------
Syntax: setobj1.issuperset(setobj2)
=>This function Returns True provided all elements of setobj2 present in setobj1. Otherwise it return
False.
Examples:
-----------------
>>> S1={10,20,30,40,50}
>>> S2={10,20}
>>> S3={10,60,70}
>>> S1.issuperset(S2)---------True
>>> S1.issuperset(S3)-----------False
Note:
----------
>>> S1.issuperset(set())----------------True
>>> set().issuperset(set())-------------True
---------------------------------------------------------------------------------------------------------
8) issubset():---
-------------------------
Syntax: setobj1.issubset(setobj2)
Examples:
---------------
>>> s1={10,20,30,40,50}
>>> s2={40,50}
>>> s3={10,40,70}
>>> s2.issubset(s1)----------------True
>>> s3.issubset(s1)-------------False
Note:
---------
>>> set().issubset(s1)--------True
>>> set().issubset(set())-------True
-----------------------------------------------------------------------------------------------------------
9) isdisjoint():
-------------------------
Syntax: setobj1.isdisjoint(setobj2)
=>This Function Returns True provided setobj1 and setobj2 does not contains any common element(s).
Otherwise it return False.
Examples:
----------------
>>> s1={10,20,30,40,50}
>>> s2={40,60,70}
>>> s3={"Python","Django"}
>>> s1.isdisjoint(s3)--------------True
>>> s1.isdisjoint(s2)-----------False
----------------------------------------------
>>> s1={"Sachin","Rohit","Kohli"}
>>> s2={"Rossum","Ritche","Travis"}
>>> s3={"Sachin","MC"}
>>> s1.isdisjoint(s2)------------True
>>> s1.isdisjoint(s3)-----------False
----------------------------------------------------
>>> s1={"Sachin","Rohit","Kohli"}
>>> s1.isdisjoint(set())-----------True
>>> set().isdisjoint(set())-----------True
--------------------------------------------------------------------------------------------------------
10) union():
-------------------------------------
=>Syntax:- setobj3=setobj1.union(setobj2)
=>This Function is used for obtaining all the elements from both setobj1 and setobj2 uniquely.
Examples:
-----------------
>>> cp={"Sachin","Rohit","Kohli","Pandey"}
>>> tp={"Kohli","Ramesh","Rajesh"}
>>> cptp=cp.union(tp)
>>> print(cptp)---------------{'Rajesh', 'Pandey', 'Ramesh', 'Kohli', 'Rohit', 'Sachin'}
(OR)
>>> cptp=tp.union(cp)
>>> print(cptp)---------------{'Rajesh', 'Pandey', 'Rohit', 'Kohli', 'Ramesh', 'Sachin'}
-------------------------------------------------------------------------------------------------------------------------
11) intersection() :
-------------------------------------
=>Syntax:- setobj3= setobj1. intersection (setobj2)
=>This Function is used for obtaining common elements from both setobj1 and setobj2
Examples:
--------------------
>>> cp={"Sachin","Rohit","Kohli","Pandey"}
>>> tp={"Kohli","Ramesh","Rajesh"}
>>> bothcptp=cp.intersection(tp)
>>> print(bothcptp)---------------{'Kohli'}
>>> bothcptp=tp.intersection(cp)
>>> print(bothcptp)------------------{'Kohli'}
----------------------------------------------------------------------------------------------------------------------------
12) difference():
------------------------------------
=>Syntax: setobj3=setobj1.difference(setobj2)
=>This Function removes the common elements from setobj1 and setobj2 and takes and display remain
elements of setobj1.
Examples:
------------------
>>> cp={"Sachin","Rohit","Kohli","Pandey"}
>>> tp={"Kohli","Ramesh","Rajesh"}
>>> onlycp=cp.difference(tp)
>>> print(onlycp)-----------{'Pandey', 'Rohit', 'Sachin'}
>>> onlytp=tp.difference(cp)
>>> print(onlytp)----------------{'Rajesh', 'Ramesh'}
--------------------------------------------------------------------------------------------------------------------------------
13) symmetric_difference()
--------------------------------------------------------------------------------------------------------------------------------
=>Syntax: setobj3=setobj1.symmetric_difference(setobj2)
=>=>This Function removes the common elements from setobj1 and setobj2 and takes and display remain
elements from both setobj1 and setobj2 and place them in setobj3.
Examples:
--------------------
>>> cp={"Sachin","Rohit","Kohli","Pandey"}
>>> tp={"Kohli","Ramesh","Rajesh"}
>>> exclcptp=cp.symmetric_difference(tp)
>>> print(exclcptp)--------------------{'Rohit', 'Sachin', 'Rajesh', 'Pandey', 'Ramesh'}
------------------------OR-----------------------------------------------------
>>> exclcptp=cp.union(tp).difference(cp.intersection(tp))
>>> print(exclcptp)-------------{'Rohit', 'Sachin', 'Rajesh', 'Pandey', 'Ramesh'}
--------------------------------------------------------------------------------------------------------------------------------
14)update():
---------------------------
=>Syntax:- setobj1.update(setobj2)
=>This function updates or adding all the unique values of setobj2 to setobj1.
Examples:
-------------------------
>>> s1={10,"Rajesh"}
>>> s2={"Python","Data Science"}
>>> s1.update(s2)
>>> print(s1)-----------------{10, 'Rajesh', 'Data Science', 'Python'}
>>> print(s2)---------------{'Data Science', 'Python'}
>>> s3={"Oracle","MySQL","MongoDB"}
>>> s1.update(s3)
>>> print(s1)-------------------{'Oracle', 'MongoDB', 'Rajesh', 'Python', 10, 'Data Science', 'MySQL'}
---------------------------------------------
>>> s1={10,"Rajesh"}
>>> s2={10,20}
>>> s1.update(s2)
>>> print(s1)------------------{10, 'Rajesh', 20}
=================================================
2. frozenset
=================================================
=>Properties of 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 of same type or different type
or both the types with Unique values".
=>The elements of frozenset always represented by converting other type of elements (set, tuple,list..etc)
by using frozenset() bcoz frozenset set does not cointain any symbolic notation.
=>Syntax:- frozensetobj=frozenset(object)
=>An object of frozenset never maintains insertion order bcoz PVM display any possibility of elements of
frozenset.
=>Since object of frozenset never maintains insertion order and hence we can't perform Indexing and
slicing Operations.
=>An object of frozenset belongs to immutable bcoz frozenset' object does not support item assignment
and never allows to add the elements externally.
=>We have two types of frozenset objects. They are
a) empty frozenset
b) non-empty frozenset
--------------------------
a) empty frozenset
--------------------------
=>An empty frozenset is one, which contains elements and whose length is equal to 0
=>Syntax:- frozensetobj=frozenset()
---------------------------
b) non-empty frozenset
---------------------------
=>An non-empty frozenset is one, which contains elements and whose length is >0
=>Syntax:- frozensetobj=frozenset( {v1,v2....vn} )
frozensetobj=frozenset( (v1,v2....vn) )
frozensetobj=frozenset( [v1,v2....vn] )
Note:
-----------
=>The Functionality of frozenset is similar to set and set object belongs to both mutable and immutable
where as frozenset belongs to only immutable.
=========================================================================
Examples:
---------------------
>>> s1={10,20,30,40,50}
>>> print(s1,type(s1))---------------{50, 20, 40, 10, 30} <class 'set'>
>>> fs=frozenset(s1)
>>> print(fs,type(fs))-----------------frozenset({50, 20, 40, 10, 30}) <class 'frozenset'>
>>> t1=(10,"Rossum","Python",34.56)
>>> print(t1,type(t1))----------------(10, 'Rossum', 'Python', 34.56) <class 'tuple'>
>>> fs1=frozenset(t1)
>>> print(fs1,type(fs1))--------------frozenset({10, 'Rossum', 34.56, 'Python'}) <class 'frozenset'>
>>> l1=[10,10,20,20]
>>> print(l1,type(l1))------------------[10, 10, 20, 20] <class 'list'>
>>> fs2=frozenset(l1)
>>> print(fs2,type(fs2))-----------------frozenset({10, 20}) <class 'frozenset'>
>>> len(fs)--------------5
>>> len(fs1)------------4
>>> len(fs2)-------------2
>>> fs3=frozenset()
>>> print(fs3,type(fs3))--------------frozenset() <class 'frozenset'>
>>> len(fs3)----------------0
>>> fs[0]----------------TypeError: 'frozenset' object is not subscriptable
>>> fs[0:3]----------------TypeError: 'frozenset' object is not subscriptable
>>> fs[0]=100------------TypeError: 'frozenset' object does not support item assignment
>>> fs1.add(100)----------AttributeError: 'frozenset' object has no attribute 'add'
================================X======================================
=================================================
pre-defined function in frozenset
=================================================
=>Frozenset contains the following Functions.
1) copy
2) isuperset()
3) issubset()
4) isdisjoint()
5) union()
6) intersection()
7) difference()
8) symmetric_diffence()
Examples:
-----------------
>>> fs2=fs1.copy()
>>> print(fs1,id(fs1))------------- frozenset({40, 10, 20, 30}) 2547261088128
>>> print(fs2,id(fs2))---------------frozenset({40, 10, 20, 30}) 2547261088128
------------------------------------------
>>> fs1=frozenset({10,20,30,40})
>>> fs2=frozenset((100,20,300,400))
>>> fs1----------------frozenset({40, 10, 20, 30})
>>> fs2----------------frozenset({400, 100, 20, 300})
>>> fs1.issuperset(fs2)-------------False
>>> fs1.issubset(fs2)---------------False
>>> fs1.issubset({10,20})------------False
>>> fs1.issubset(frozenset({10,20,30,40,50,60}))-----------True
----------------------------------------------------------------------
>>> fs1----------------------frozenset({40, 10, 20, 30})
>>> fs2----------------------frozenset({400, 100, 20, 300})
>>> fs3=fs1.union(fs2)
>>> print(fs3)--------------------frozenset({100, 40, 10, 300, 400, 20, 30})
>>> fs4=fs1.intersection(fs2)
>>> print(fs4)---------------frozenset({20})
>>> fs5=fs1.difference(fs2)
>>> print(fs5)---------------------frozenset({40, 10, 30})
>>> fs6=fs2.difference(fs1)
>>> print(fs6)---------------------frozenset({400, 100, 300})
>>> fs7=fs2.symmetric_difference(fs1)
>>> print(fs7)------------------frozenset({100, 40, 10, 300, 400, 30})
--------------------------------------------------------------------------------------------------------
Note: Frozenset does not contain the following Functions.
Here Key1,Key2...Key-n are called Values of Key and They must Unique
Here Val1, Val2...Val-n are called Values of Value and They may or may not be unique.
==========================================================================
Examples:
-----------------
>>> d1={10:"Python",20:"Data Sci",30:"Django"}
>>> print(d1,type(d1))----------{10: 'Python', 20: 'Data Sci', 30: 'Django'} <class 'dict'>
>>> d2={10:3.4,20:4.5,30:5.6,40:3.4}
>>> print(d2,type(d2))------------{10: 3.4, 20: 4.5, 30: 5.6, 40: 3.4} <class 'dict'>
>>> len(d1)--------------3
>>> len(d2)------------4
-------------------------------------------------
>>> d3={}
>>> print(d3,type(d3))------------{} <class 'dict'>
>>> len(d3)-------------0
>>> d4=dict()
>>> print(d4,type(d4))-------------{} <class 'dict'>
>>> len(d4)---------------0
------------------------------------------------------------------------
>>> d2={10:3.4,20:4.5,30:5.6,40:3.4}
>>> print(d2)----------------------------------{10: 3.4, 20: 4.5, 30: 5.6, 40: 3.4}
>>> d2[0]----------------------------------------KeyError: 0
>>> d2[10]-------------------------------------3.4
>>> d2[10]=10.44
>>> print(d2)-------------------------------{10: 10.44, 20: 4.5, 30: 5.6, 40: 3.4}
-------------------------------------------------------------------------------------
>>> d2={10:3.4,20:4.5,30:5.6,40:3.4}
>>> print(d2,type(d2),id(d2))----{10: 3.4, 20: 4.5, 30: 5.6, 40: 3.4} <class 'dict'> 2090750380736
>>> d2[50]=5.5
>>> print(d2,type(d2),id(d2))---{10: 3.4, 20: 4.5, 30: 5.6, 40: 3.4, 50: 5.5} <class 'dict'>
2090750380736
-------------------------------------------------------------------------------------
>>> d3={}
>>> print(d3,type(d3),id(d3))-------------------{} <class 'dict'> 2090750332992
>>> d3["Python"]=1
>>> d3["Java"]=3
>>> d3["C"]=2
>>> d3["GO"]=1
>>> print(d3,type(d3),id(d3))-----{'Python': 1, 'Java': 3, 'C': 2, 'GO': 1} <class 'dict'>
2090750332992
-------------------------------------------------------------
>>> d4=dict()
>>> print(d4,type(d4),id(d4))---------------{} <class 'dict'> 2090754532032
>>> d4[10]="Apple"
>>> d4[20]="Mango"
>>> d4[30]="Kiwi"
>>> d4[40]="Sberry"
>>> d4[50]="Orange"
>>> print(d4,type(d4),id(d4))---{10: 'Apple', 20: 'Mango', 30: 'Kiwi', 40: 'Sberry', 50: 'Orange'}
<class 'dict'> 2090754532032
>>> d4[10]="Guava"
>>> print(d4,type(d4),id(d4))----{10: 'Guava', 20: 'Mango', 30: 'Kiwi', 40: 'Sberry', 50: 'Orange'}
<class 'dict'>
2090754532032
--------------------------------------------------------------------------------------
>>> d2={10:3.4,20:4.5,30:5.6,40:3.4}
>>> print(d2,type(d2),id(d2))---{10: 3.4, 20: 4.5, 30: 5.6, 40: 3.4} <class 'dict'> 2090754531520
>>> d2[50]=1.2
>>> print(d2,type(d2),id(d2))---{10: 3.4, 20: 4.5, 30: 5.6, 40: 3.4, 50: 1.2} <class 'dict'>
2090754531520
================================================
Pre-defined Functions in dict
================================================
=>On the object of dict, we can perform some additional operationsby using the pre-defined
functions present in dict object.
-----------------------------------
1) clear()
-----------------------------------
=>This fucntion is used for removing all the elemnts from dict object.
=>Syntax:- dictobj.clear()
Examples:
>>> d1={10:3.4,20:4.5,30:5.6,40:3.4}
>>> print(d1,len(d1))-------------------{10: 3.4, 20: 4.5, 30: 5.6, 40: 3.4} 4
>>> d1.clear()
>>> print(d1,len(d1))-----------------{} 0
>>> print({}.clear())----------------None
>>> print(dict().clear())---------------None
--------------------------------------------------------------------------------------------------------------
2) copy():
-------------------------------------------------------------
=>This function is used for copying the content of one dict object into another dict object.
=>Syntax: dictobj2=dictobj1.copy()
Examples:
-----------------
>>> d1={10:3.4,20:4.5,30:5.6,40:3.4}
>>> print(d1,id(d1))----------{10: 3.4, 20: 4.5, 30: 5.6, 40: 3.4} 2090750382720
>>> d2=d1.copy() # shallow Copy
>>> print(d2,id(d2))-----{10: 3.4, 20: 4.5, 30: 5.6, 40: 3.4} 2090750332864
>>> d1[50]=1.2
>>> d2[45]=11.2
>>> print(d1,id(d1))-----{10: 3.4, 20: 4.5, 30: 5.6, 40: 3.4, 50: 1.2} 2090750382720
>>> print(d2,id(d2))----{10: 3.4, 20: 4.5, 30: 5.6, 40: 3.4, 45: 11.2} 2090750332864
-------------------------------
>>> d1={}.copy()
>>> print(d1,len(d1))----------{} 0
>>> d2=dict().copy()
>>> print(d2,len(d2))-------------{} 0
------------------------------------------------------------------------------------------------------------------
3) pop():
---------------------------------
=>This Function is used for removing (Key,value) from dict object provided Value of Key must exist in dict
object otherwise we get KeyError.
=>Syntax: dictobj.pop(Key)
Examples:
-----------------
>>> d1={10:3.4,20:4.5,30:5.6,40:3.4}
>>> d1.pop(20)-------------4.5
>>> print(d1)------------------{10: 3.4, 30: 5.6, 40: 3.4}
>>> d1.pop(30)------------5.6
>>> print(d1)--------------{10: 3.4, 40: 3.4}
>>> d1.pop(40)-----------3.4
>>> print(d1)-------------{10: 3.4}
>>> d1.pop(60)--------KeyError: 60
-------------------------------------------------------------------------------------------------------------------
4) popitem():
-------------------------------------------------------------------------------------------------------------------
=>This function is used for removing last (key,value) from non-dict object otherwise we get
KeyError
=>Syntax:- dictobj.popitem()
Examples:
-----------------
>>> d1={10: 'Guava', 20: 'Mango', 30: 'Kiwi', 40: 'Sberry', 50: 'Orange'}
>>> print(d1)
{10: 'Guava', 20: 'Mango', 30: 'Kiwi', 40: 'Sberry', 50: 'Orange'}
>>> d1.popitem()------------(50, 'Orange')
>>> print(d1)------------{10: 'Guava', 20: 'Mango', 30: 'Kiwi', 40: 'Sberry'}
>>> d1.popitem()----------(40, 'Sberry')
>>> print(d1)-----------{10: 'Guava', 20: 'Mango', 30: 'Kiwi'}
>>> d1.popitem()-----------(30, 'Kiwi')
>>> print(d1)---------------{10: 'Guava', 20: 'Mango'}
>>> d1.popitem()------------(20, 'Mango')
>>> print(d1)--------------{10: 'Guava'}
>>> d1.popitem()-----------(10, 'Guava')
>>> print(d1)--------------{}
>>> d1.popitem()------------KeyError: 'popitem(): dictionary is empty'
>>> {}.popitem()-----------KeyError: 'popitem(): dictionary is empty'
>>> dict().popitem()---------KeyError: 'popitem(): dictionary is empty'
---------------------------------------
Special Note:
----------------------------------------
>>> d1=dict( [(10,1.2),(20,2.3),(30,4.5)] ) # Converting List of tuples into dict object
>>> d1-----------------{10: 1.2, 20: 2.3, 30: 4.5}
-----------------------------------------------------------------------
>>> dict( [(10,1.2),(20,2.3),(30,4.5)] ).pop(60)---------KeyError: 60
>>> dict( [(10,1.2),(20,2.3),(30,4.5)] ).popitem()---------(30, 4.5)
>>> d1-----------------------------------{10: 1.2, 20: 2.3, 30: 4.5}
>>> d1.popitem()---------------(30, 4.5)
>>> d1---------------------{10: 1.2, 20: 2.3}
>>> d1.popitem()-------------(20, 2.3)
>>> d1---------------{10: 1.2}
>>> d1.popitem()---------------(10, 1.2)
>>> d1-----------------------------{}
>>> d1.popitem()-----------------KeyError: 'popitem(): dictionary is empty'
-------------------------------------------------------------------------------------------------------------------
6) get()
------------------------------------
=>This Function is used for obtaining Value of Value by passing Value of Key from Non-Empty dict object
otherwise we get None
=>Syntax: dictobj.get(Key)
--------------------
Examples:
--------------------
>>> d1={10: 'Guava', 20: 'Mango', 30: 'Kiwi', 40: 'Sberry', 50: 'Orange'}
>>> print(d1)
{10: 'Guava', 20: 'Mango', 30: 'Kiwi', 40: 'Sberry', 50: 'Orange'}
>>> d1[20]---------------'Mango'
>>> d1[10]-------------'Guava'
>>> d1[30]---------------'Kiwi'
============================OR=========================
>>> d1.get(20)------------------'Mango'
>>> d1.get(10)-----------------'Guava'
>>> d1.get(30)-----------------'Kiwi'
>>> d1.get(50)-------------------'Orange'
>>> print(d1.get(500))----------None
>>> print(dict().get(10))----------None
>>> print({}.get(10))-----------None
>>> dict([[10,1.2],[20,3.4]]).get(20)----------3.4
>>> dict([[10,1.2],[20,3.4]]).get(10)--------1.2
>>> print(dict([[10,1.2],[20,3.4]]).get(30))-------None
-------------------------------------------------------------------------------------------------------------------
7) keys()
-------------------------------------------------------------------------------------------------------------------
=>This Functrion is used for obtaining Value of Keys from non-empty dict object.
=>Syntax: varname=dictobj.keys()
(OR)
dictobj.keys()
Examples:
--------------------
>>> d1={10: 'Guava', 20: 'Mango', 30: 'Kiwi', 40: 'Sberry', 50: 'Orange'}
>>> print(d1)---------{10: 'Guava', 20: 'Mango', 30: 'Kiwi', 40: 'Sberry', 50: 'Orange'}
>>> k=d1.keys()
>>> print(k)----------dict_keys([10, 20, 30, 40, 50])
>>> for kv in k:
... print(kv)
...
10
20
30
40
50
======================OR===================
>>> for kv in d1.keys():
... print(kv)
...
10
20
30
40
50
>>> d2={}.keys()
>>> d2------------dict_keys([])
>>> d3=dict().keys()
>>> d3----------------dict_keys([])
8) values():
------------------
=>This Function is used for obtaining Values of Value from non-empty dict object.
=>Syntax: varname=dictobj.values()
(OR)
dictobj.values()
Examples:
--------------------
>>> d1={10: 'Guava', 20: 'Mango', 30: 'Kiwi', 40: 'Sberry', 50: 'Orange'}
>>> print(d1)-----------------{10: 'Guava', 20: 'Mango', 30: 'Kiwi', 40: 'Sberry', 50: 'Orange'}
>>> v=d1.values()
>>> print(v,type(v))--dict_values(['Guava', 'Mango', 'Kiwi', 'Sberry', 'Orange']) <class
'dict_values'>
>>> for vv in v:
... print(vv)
...
Guava
Mango
Kiwi
Sberry
Orange
>>> for v in d1.values():
... print(v)
...
Guava
Mango
Kiwi
Sberry
Orange
Note:
-----------
>>> d1={10: 'Guava', 20: 'Mango', 30: 'Kiwi', 40: 'Sberry', 50: 'Orange'}
>>> print(d1)
{10: 'Guava', 20: 'Mango', 30: 'Kiwi', 40: 'Sberry', 50: 'Orange'}
>>> for x in d1:
... print(x)
...
10
20
30
40
50
----------------------------------------------------------------------------------------------------------------
9) items():
---------------------------------------
=>This Function is used for obtaining (Key,value) from non-empty dict object.
=>Syntax: varname=dictobj.items()
(OR)
dictobj.items()
Examples:
-----------------
>>> d1={10: 'Guava', 20: 'Mango', 30: 'Kiwi', 40: 'Sberry', 50: 'Orange'}
>>> print(d1)----{10: 'Guava', 20: 'Mango', 30: 'Kiwi', 40: 'Sberry', 50: 'Orange'}
>>> kvs=d1.items()
>>> print(kvs,type(kvs))---dict_items([(10, 'Guava'), (20, 'Mango'), (30, 'Kiwi'), (40, 'Sberry'),
(50, 'Orange')]) <class 'dict_items'>
------------------------------------
>>> for kv in kvs:
... print(kv)
...
(10, 'Guava')
(20, 'Mango')
(30, 'Kiwi')
(40, 'Sberry')
(50, 'Orange')
=====OR=======
>>> for kv in d1.items():
... print(kv)
...
(10, 'Guava')
(20, 'Mango')
(30, 'Kiwi')
(40, 'Sberry')
(50, 'Orange')
=======OR=================
>>> for k,v in d1.items():
... print(k,"--->",v)
...
10 ---> Guava
20 ---> Mango
30 ---> Kiwi
40 ---> Sberry
50 ---> Orange
------------------------------------------------------------------------------------------------------------------
10) update():
---------------------------------
=>This Function is used for updating( Newly Inserting or Changing the old value of Value with New
Value with Same Key ) One dict object with another dict object
=>Syntax:- dictobj1.update(dictobj2)
----------------
Examples:
----------------
>>> d1={10:"Python",20:"Data Science"}
>>> d2={30:"Django",40:"R"}
>>> d1.update(d2)------------>>> print(d1)
{10: 'Python', 20: 'Data Science', 30: 'Django', 40: 'R'}
>>> print(d2)------------{30: 'Django', 40: 'R'}
---------------------------------------------------------
>>> d1={10:"Python",20:"Data Science"}
>>> d2={30:"Django",40:"R",10:"Python Prog"}
>>> d1.update(d2)
>>> print(d1)----{10: 'Python Prog', 20: 'Data Science', 30: 'Django', 40: 'R'}
>>> print(d2)----{30: 'Django', 40: 'R', 10: 'Python Prog'}
================================X====================================
Misc Cases with Dict:
--------------------------------
>>> d1={1:["Python","Data
Scienece","Django"],2:("C","DS"),3:{"Java","Servlets","JSP","JDBC","Spring"} }
>>> print(d1,type(d1))
{1: ['Python', 'Data Scienece', 'Django'], 2: ('C', 'DS'), 3: {'Servlets', 'Java', 'JDBC',
'JSP', 'Spring'}} <class 'dict'>
>>> for k,v in d1.items():
... print(k,"-->",v)
...
1 --> ['Python', 'Data Scienece', 'Django']
2 --> ('C', 'DS')
3 --> {'Servlets', 'Java', 'JDBC', 'JSP', 'Spring'}
-------------------------------------------------
>>> d1={10:["Tel","Hindi","Eng","Maths","Sci","Soc"],
... 12:["Maths","Phy","Che"],
... 13:["C","CPP","JAVA","PYTHON"] }
>>> print(d1,type(d1))
{10: ['Tel', 'Hindi', 'Eng', 'Maths', 'Sci', 'Soc'], 12: ['Maths', 'Phy', 'Che'], 13: ['C', 'CPP', 'JAVA',
'PYTHON']} <class 'dict'>
>>> for k in d1.keys():
... print(k)
...
10
12
13
>>> for v in d1.values():
... print(v)
...
['Tel', 'Hindi', 'Eng', 'Maths', 'Sci', 'Soc']
['Maths', 'Phy', 'Che']
['C', 'CPP', 'JAVA', 'PYTHON']
>>> for k,v in d1.items():
... print(k,"<--->",v)
...
10 <---> ['Tel', 'Hindi', 'Eng', 'Maths', 'Sci', 'Soc']
12 <---> ['Maths', 'Phy', 'Che']
13 <---> ['C', 'CPP', 'JAVA', 'PYTHON']
-----------------------------------------------------------------------------------------------
Misc Case with Inner list, Inner tuple, list of tuples converted into dict:
---------------------------------------------------------------------------------------------------------
>>> l1=[[10,"RS"],[20,"JG"],[30,"TR"]]
>>> print(l1,type(l1))------------------[[10, 'RS'], [20, 'JG'], [30, 'TR']] <class 'list'>
>>> d1=dict(l1)
>>> print(d1,type(d1))--------{10: 'RS', 20: 'JG', 30: 'TR'} <class 'dict'>
-------------------------------
>>> t1=( (10,"RS"),(20,"JG"),(30,"TR") )
>>> print(t1,type(t1))-----------((10, 'RS'), (20, 'JG'), (30, 'TR')) <class 'tuple'>
>>> d1=dict(t1)
>>> print(d1,type(d1))-----------{10: 'RS', 20: 'JG', 30: 'TR'} <class 'dict'>
--------------------------------------------------------
>>> l1=[(10,"RS"),(20,"JG"),(30,"TR")]
>>> print(l1,type(l1))------------[(10, 'RS'), (20, 'JG'), (30, 'TR')] <class 'list'>
>>> d1=dict(l1)
>>> print(d1,type(d1))-------------{10: 'RS', 20: 'JG', 30: 'TR'} <class 'dict'>
===============================X=======================================
=======================================
NoneType data type
=======================================
=>'NoneType' is one the pre-defined class and treated as None type Data type
=> "None" is keyword acts as value for <class,'NoneType'>
=>The value of 'None' is not False, Space , empty , 0
=>An object of NoneType class can't be created explicitly.
--------------------------------------------------------------------
Examples:
------------------
>>> a=None
>>> print(a,type(a))------------None <class 'NoneType'>
>>> a=NoneType()---------NameError: name 'NoneType' is not defined
==============================================
Number of approaches to develop programs in Python
==============================================
=>Definition of Program:
-----------------------------------------
=>A Program is a collection of Optimized Instructions.
------------------------------------------------------------------------------
=>In real time, to develop any python program, we have two approaches. they are
a) Interactive Mode
b) Batch Mode
--------------------------------------------------------------------------------
a) Interactive Mode:
----------------------------------
=>In this mode of Development, Python Programmer can issue a single statement and obtains single result
=>This Mode of development is most useful for testing one Instruction at a time.
=>This Mode of development is not recommended for Big Problem Solving bcoz Big Problem solving
statements are not possible to save and more over re-using the statements of Interactive mode on other
parts of the projects is not possible.
=>hence To solve Big Problems we must go for Batch Mode Programming.
Example:
----------
#program for computing sum of two nums
a=10
b=20
c=a+b
print("----------------")
print("Val of a=",a)
print("Val of b=",b)
print("sum=",c)
print("----------------")
=================================================
Display the result of python program
=================================================
=>To display the result of python program, we use a pre-defined function called print().
=>In otherwords print() is of the pre-defined function used for display the result of Python
program.
=>print() can be used in various ways.
--------------------------------------------------------------------------------------------
Syntax-1: print(val1,val2,...val-n)
(OR)
print(var1,var2.....var-n)
=>This syntax displays values directly or variable values
Examples:
-----------------
>>> a=10
>>> print(a,type(a))-----------------------10 <class 'int'>
>>> a=10
>>> b=20
>>> c=a+b
>>> print(a,b,c)---------------------------10 20 30
>>> print(100,200,300,400)-------------------100 200 300 400
-----------------------------------------------------------------------------------------------
Syntax-2: print(message1,message2,message3.....message-n)
here message1,message2,message3.....message-n are of type <class, 'str'>
=>This syntax displays only messages.
Examples:
---------------
>>> print("Hyd")-----------Hyd
>>> print('Hello Python')-----------Hello Python
>>> print(s1+s2+s3)-----------------PythonMLDL
>>> print(s1+10)--------TypeError: can only concatenate str (not "int") to str
>>> print(s1+str(10) )-----Python10
-----------------------------------------------------------------------------------------------------------------------------
Syntax-3: print(msg cum value)
(or)
print(value cum message )
Examples:
----------------------
>>> a=10
>>> b=20
>>> c=a+b
>>> print("Val of a=",a)------------Val of a= 10
>>> print("Val of b=",b)----------Val of b= 20
>>> print("sum=",c)--------------sum= 30
----------------------------------------
>>> a=10
>>> b=20
>>> c=a+b
>>> print(a," is the value")-----------10 is the value
>>> print(b," is the value of b")-------20 is the value of b
>>> print(c," is the sum")------30 is the sum
------------------------------------------------------------------------
>>> a=10
>>> b=20
>>> c=30
>>> d=a+b+c
>>> print("Sum of ",a,",",b," and ",c,"=",d)---Sum of 10 , 20 and 30 = 60
-----------------------------------------------------------------------------------------------------------------------------
Syntax-4: print(msg cum value with format() )
(or)
print(value cum message with format() )
=>This syntax displays Values cum Messages OR Messages cum values with format()
Examples:
---------------------
>>> a=10
>>> b=20
>>> c=a+b
>>> print("Val of a=",a)-------------Val of a= 10
>>> print("Val of a={}".format(a))--------Val of a=10
>>> print("{} is the value of a".format(a))--------10 is the value of a
>>> print("sum={}".format(c))--------sum=30
>>> print("Sum of {} and {}={}".format(a,b,c))----Sum of 10 and 20=30
>>> a=10
>>> b=20
>>> c=30
>>> d=a+b+c
>>> print("Sum of {},{} and {}={}".format(a,b,c,d))---Sum of 10,20 and 30=60
---------------------------------------------------------------------------------------------------------
Syntax-5: print(msg cum value with format specifiers )
(or)
print(value cum message with format specifiers )
=>This syntax displays Values cum Messages OR Messages cum values with format specifiers.
Examples:
-------------------
>>> a=10
>>> b=23
>>> c=a+b
>>> print("Val of a=",a)---------Val of a= 10
>>> print("Val of a={}".format(a))---------Val of a=10
>>> print("Val of a=%d" %a)--------Val of a=10
>>> print("%d is the val of a" %a)----------10 is the val of a
>>> print("Sum of %d and %d=%d" %(a,b,c) )-------Sum of 10 and 23=33
------------------------------------------------------------------
>>> a=10
>>> b=20
>>> c=a+b
>>> print("sum of %f and %f=%f" %(a,b,c))------sum of 10.000000 and 20.000000=30.000000
>>> print("sum of %0.2f and %0.3f=%0.2f" %(a,b,c))---sum of 10.00 and 20.000=30.00
>>> print("sum of %0.2f and %0.3f=%d" %(a,b,c))-------sum of 10.00 and 20.000=30
---------------------
>>> stno=10
>>> sname="Rossum"
>>> print("My number is %d and Name is %s " %(stno,sname))---
My number is 10 and Name is Rossum
>>> print("My number is %d and Name is '%s' " %(stno,sname))
My number is 10 and Name is 'Rossum'
=================================X=====================================
===================================================
Reading the data from Keyboard in Python Program
===================================================
=>To read the data dynamically from Keyboard, we have two pre-defined Functions. They are
1) input()
2) input(message)
---------------------------------------------------------------------------
1) input():
--------------------------------------------------------------------------
=>This function is used for reading the data dynamically from Key board in the form of str
always.
=>Syntax:- varname=input()
=>here varname is an object of <class,'str'>. We can convert str value into any other data type
by using Type Casting Techniques.
Examples:
-----------------------
#Program for accepting two numerical values and add them
#sumex3.py
print("Enter Two Value:")
a=float( input() )
b=float( input() )
print("Sum of {} and {}={}".format(a,b,a+b))
============================================================
2) input(message):
---------------------------------------------
=>This Function is used for reading the data from Key Board by displaying User-Prompting Message
which is of type str.
=>Syntax:- var name=input("Message")
=>here varname is an object of <class,'str'>. We can convert str value into any other data type
by using Type Casting Techniques.
=>"Message" represents User-Prompting Message.
Example:
#Program cal si and totamt to pay
#simpleint.py
p=float(input("Enter Principle Amount:"))
t=float(input("Enter Time:"))
r=float(input("Enter Rate of Interest:"))
#cal si
si=(p*t*r)/100
totamt=p+si
print("------------------------------------------------")
print("\tPrinciple Amount={}".format(p))
print("\tTime={}".format(t))
print("\tRate of Interest ={}".format(r))
print("\tSimple Interest={}".format(si))
print("\tTotal Amount to pay={}".format(totamt))
print("------------------------------------------------")
Example:
#Program for accepting two numerical values and add them
#sumex1.py
print("Enter First Value:")
s1=input() # s1=10
print("Enter Second Value:")
s2=input() #s2=20
print("Val of s1={} and whose type={}".format(s1,type(s1)))
print("Val of s2={} and whose type={}".format(s2,type(s2)))
a=float(s1)
b=float(s2)
c=a+b
print("Sum of {} and {}={}".format(a,b,c))
Example:
#Program for accepting two numerical values and add them
#sumex2.py
print("Enter Two Value:")
s1=input()
s2=input()
a=float(s1)
b=float(s2)
c=a+b
print("Sum of {} and {}={}".format(a,b,c))
Example:
#Program for accepting two numerical values and add them
#sumex3.py
print("Enter Two Value:")
a=float( input() )
b=float( input() )
print("Sum of {} and {}={}".format(a,b,a+b))
=========================================
Operators and Expressions in Python
=========================================
=>An Operator is a symbol which is used to perform certation on data / objects.
=>If two or more Variables / Objects connected with Operators then it is called Expression.
=>In Python Programming, we have 7 operators. They are
1) Arithmetic Operators
2) Assignment Operator
3) Relational Operators
4) Logical Operators
5) Bitwise Operators ( Most Imp )
6) Membership Operators
a) in
b) not in
7) Identity Operators
a) is
b) is not
-----------------------------------------------------------------------------------------------------------------
Note: Python does not support Unary Operator ++ and --
Python does not support Ternary Operator ( ? :)
======================================================
1) Arithmetic Operators
======================================================
=>These Operators are used for performing Arithmetic Operations such as addition ,
substraction, multiplication etc.
=>If any Arithmetic Operators connected with two or more Variables then it is called Arithmetic
Expression.
=>The following Tables gives list of Arithmetic Operators
----------------------------------------------------------------------------------------------------------------------
SLNO Symbol Meaning Examples : a=10 b=3
----------------------------------------------------------------------------------------------------------------------
1. + Addition print(a+b)------->13
2. - Subtract print(a-b)-------->7
3. * Multiply print(a*b)------->30
4. / Division print(a/b)--->3.3333333333333335
(Float Quiotient)
5. // Floor Division print(a//b)------->3
(Integer Quiotient)
7. ** Exponentiation print(a**b)-------->1000
Example:
----------
a=int(input("Enter Value of a:"))
b=int(input("Enter Value of b:"))
print("="*50)
print("Arithmetic Operations")
print("="*50)
print("\t{} + {}={}".format(a,b,a+b))
print("\t{} - {}={}".format(a,b,a-b))
print("\t{} * {}={}".format(a,b,a*b))
print("\t{} / {}={}".format(a,b,a/b))
print("\t{} // {}={}".format(a,b,a//b))
print("\t{} % {}={}".format(a,b,a%b))
print("\t{} ** {}={}".format(a,b,a**b))
print("="*50)
Example:
--------------
#program for cal Square Root and Cube Root
#sqcbroot.py
n=int(input("Enter a number:"))
sqroot=n**0.5
cbroot=n**(1/3)
print("SquareRoot({})={}".format(n,sqroot))
print("CubeRoot({})={}".format(n,cbroot))
Example:
--------------
#program for swapping of any two values
#Swapex1.py
a=input("Enter Value of a:")
b=input("Enter Value of b:")
print("-"*50)
print("Original value of a:{}".format(a))
print("Original value of b:{}".format(b))
print("-"*50)
#swapping logic
t=a
a=b
b=t
print("Swapped value of a:{}".format(a))
print("Swapped value of b:{}".format(b))
print("-"*50)
Example:
----------------
#program for swapping of any two values
#Swapex2.py
a=input("Enter Value of a:")
b=input("Enter Value of b:")
print("-"*50)
print("Original value of a:{}".format(a))
print("Original value of b:{}".format(b))
print("-"*50)
#swapping logic
a,b=b,a # Multi Line Assigment---swapping Operation
print("Swapped value of a:{}".format(a))
print("Swapped value of b:{}".format(b))
print("-"*50)
Examples:
-----------------
>>> a=10
>>> b=20
>>> c=a+b
>>> print(a,b,c)---------10 20 30
---------------------------------------------
>>> sno=100
>>> sname="Rossum"
>>> print(sno,sname)--------100 Rossum
--------------------------------------------------------------------------------------------------
b) Multi Line Assignment Operator:
--------------------------------------------------------------------------
=>With Multi Line Assignment Operator, we can transfer Multiple Right Hand Side Values /
Expressions to Left Hand Side variables.
=>Syntax:- Var1,Var2...Var-n=Val1,Val2....Val-n
(OR)
Var1,Var2...Var-n=Expr-1,Expr-2...Expr-n
Examples:
-------------------
>>> a,b=10,20
>>> add,sub,mul=a+b,a-b,a*b
>>> print(a,b)---------10 20
>>> print(add,sub,mul)----------30 -10 200
-------------------------------------------
>>> sno,sname,marks=10,"Rossum",44.44
>>> print(sno,sname,marks)--------------------------10 Rossum 44.44
Note:-
>>> a=10,20,30,40,50,60
>>> print(a,type(a))----------------(10, 20, 30, 40, 50, 60) <class 'tuple'>
===============================X=======================================
===============================================
3) Relational Operators
===============================================
=>The porpose of Relational Operators is that " To Compare two Values "
=>The two or more Variables connected with Relational Operators is called Relational
Expression.
=>The Result of Relational Expression always gives either True or False (bool value)
=>The following table gives list of Relational Operators along with meaning and examples.
-------------------------------------------------------------------------------------------------------------------------------
slno Symbol Meaning Examples a=10 b=20
----------------------------------------------------------------------------------------------------------------------- --------
1. > Greater Than print(a>b)----------False
print(a>2)----------True
print(a<0)---------False
3. == Equality print(a==b)-------False
print(a==10)-------True
print(a!=a)------False
Examples:
---------------------
>>> print((2+3j)>=(2.0+3.0j))-----TypeError: '>=' not supported between instances of 'complex'
and 'complex'
---------------------------------------------------------------------------------------------
>>> a=2+3j
>>> b=2+3j
>>> print(a==b)----------------True
>>> print(a>b)----TypeError: '>' not supported between instances of 'complex' and 'complex'
>>> print(a!=b)-----False
>>> print(a>=b)-----TypeError: '>=' not supported between instances of 'complex' and 'complex'
===================================================================
Example:
------------
#Program for demonstarting Relational Operators
#rop.py
a,b=int(input("Enter Value of a:")),int(input("Enter Value of b:"))
print("="*50)
print("\tRelation Operators")
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)
Example:
------------
#program for swapping of any two values
#Swapex1.py
a=input("Enter Value of a:")
b=input("Enter Value of b:")
print("-"*50)
print("Original value of a:{}".format(a))
print("Original value of b:{}".format(b))
print("-"*50)
#swapping logic
t=a
a=b
b=t
print("Swapped value of a:{}".format(a))
print("Swapped value of b:{}".format(b))
print("-"*50)
Example:
------------
#program for swapping of any two values
#Swapex2.py
a=input("Enter Value of a:")
b=input("Enter Value of b:")
print("-"*50)
print("Original value of a:{}".format(a))
print("Original value of b:{}".format(b))
print("-"*50)
#swapping logic
a,b=b,a # Multi Line Assigment---swapping Operation
print("Swapped value of a:{}".format(a))
print("Swapped value of b:{}".format(b))
print("-"*50)
=============================================
4) Logical Operators
=============================================
=>The purpose of Logical Operators is that b" To combile two or more Relational Expressions
and compare two or more values:"
=>If two or more Relational Expressions are connected with Logical Operators then it is called
Logical Expression or Logical Condition ( Compund Condition).
=>The result of Logical Expression is either to be True or False.
=>In Python Programming, we have 3 types of Logical Operatoors and they are given in the following
table.
-------------------------------------------------------------------------------------------------------------------------------
SLNO Symbol Meaning
-------------------------------------------------------------------------------------------------------------------------------
1. and Physical ANDing
2. or Physical ORing
3. not ---------------------------------
-------------------------------------------------------------------------------------------------------------------------------
1) Explanation of "and" operator:
--------------------------------------------------------------------------------------------------------------------------
=>The Functionality of "and" operator expressed by using the following Truth Tables.
-------------------------------------------------------------------------------
RelExpr1 RelExpr2 RelExpr1 and RelExpr2
-------------------------------------------------------------------------------
False True False
-------------------------------------------------------------------------------
RelExpr1 RelExpr2 RelExpr1 or RelExpr2
-------------------------------------------------------------------------------
False True True
-------------------------------------------------------------------------------
RelExpr1 not RelExpr1 / Logical Expression
-------------------------------------------------------------------------------
False True
True False
-------------------------------------------------------------------------------------------------------------------
Examples:
-----------------
>>> print( not ((10!=33) or (100==200) or (10!=10)) )--------False
>>> print(10>3)----------------True
>>> print(not 10>3)-----------False
>>> print(not True)----------False
>>> print(not False)----------True
---------------------------------------------------------------------------------------------------------------------
Special Note:
-----------------------------
>>> print(not 10)----------------False
>>> print(not 0)----------------True
>>> print(not -123)-----------False
>>> print(not -123+123)-------True
---------------------------------------------------------
>>> True and True----------------True
>>> True and False---------------False
>>> False and False------------False
>>> True and True--------------True
>>> True and 100-----------------100
>>> 10>2 and 100>3--------------True
----------------------------------------------------------------
>>> 1000 and 3000-----------------------3000
>>> 20 and -34---------------------------- -34
>>> 100 and 100-100----------------- 0
>>> -123 and 234----------------------- 234
>>> 0 and 234--------------------------- 0
>>> 100 and 0 and 234-----------------0
>>> 100 and -123 and 234-------------- 234
>>> 100 and -123 and 0------------------ 0
>>> 100 or 200------------------------------- 100
>>> -100 or 200----------------------------- -100
>>> 100-100 or 200----------------------- 200
>>> 200 or 0------------------------------ 200
>>> 0 or 0---------------------------- 0
>>> False and 200-----------------------False
>>> False or 200-----------------200
>>> 100 or 200 or 0--------------100
>>> 100 or 200 and 0--------------- 100
>>> 100 or 200 and 200 and 0----------100
>>> 0 or 200 and 200 and 0-------------0
>>> 100 and 200 or 300 or 300 and True--------200
>>> 100 and 200 and 0 and -45 and False or 56------56
--------------------------------------------------------------------------------------
>>> "Python" and "DSc"-----------'DSc'
>>> "Python" and ""------------- ''
>>> "False" and "True"------------- 'True'
>>> "False" or "True"--------------'False'
>>> 100 and 200 and "False" or "True"----------'False'
>>> "" or True--------------------True
-----------------------------------------------------------------------------------------------------------------------
>>> 100 and -200 and 0 and 123 or "python" or "0" or "Java"------'python'
>>> not(100 and -200 and 0 and 123 or "python" or "0" or "Java")-----False
1 0 0
0 0 0
1 1 1
-------------------------------------------------------------------------------------------
Examples:
------------------
>>>a=5--------------------->0101
>>>b=10------------------->1010
--------------
>>>c=a&b ---------------->0000------------result-------0
>>>print(c)
------------------------------------------------------------
>>> a=5
>>> b=10
>>> c=a&b
>>> print(c)---------0
>>> print(10&4)-------0
>>> print(5&7)----------5
----------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------
4. Bitwise OR Operator ( | ):
------------------------------------------------------------------------------------------------------------------
=>The Functionality of Bitwise OR Operator ( | ) is shown in the following Table.
-------------------------------------------------------------------------------------------------
K V K|V
-------------------------------------------------------------------------------------------------
0 1 1
1 0 1
0 0 0
1 1 1
------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------
5. Bitwise Complement Operator ( ~ ):
------------------------------------------------------------------------------------------------------------------
=>Bitwise Complement Operator (~) works in such way that " Given Number Converted into Binary and
Converted Binary Number Inverted (Inverted means 0 becomes 1 and 1 becomes 0)"
=>Syntax:- ~Value
or
=>Syntax:- varname= ~Value
Or
=>Syntax:- varname2= ~Variable1
--------------------------------------------------------------------------------------------------------
Formula for Bitwise Complement (~) = ~value=> - (value+1)
--------------------------------------------------------------------------------------------------------
Examples:
------------------
>>>a=5--------------------->0101
>>>b=10------------------->1010
>>>c=a|b ----------------> 1111------------Result----15
>>>print(c)-----15
-----------------------------------------
>>> print(4|5)---------------5
>>> print(15|10)----------15
----------------------------------------------------------------------------------------------
5. Bitwise Complement Operator ( ~ ):
----------------------------------------------------------------------------------------------
>>> a=4
>>> ~a----------------- -5
>>> a=9
>>> print(a)--------------9
>>> ~a ------------------- -10
-----------------------------------------------------
>>> a=15
>>> print(~a)--------------- -16
>>> a=99
>>> print(~a)--------------------- -100
>>> a=123456
>>> print(~a)------------------------- -123457
>>> a=-456
>>> ~a --------------------------------- 455
>>> a=-1
>>> ~a ---------------------------------------0
-------------------------------------------------------------------------
=====================================================
5) Bitwise Operators ( Most Imp )
=====================================================
=>Bitwise operators are applicable on Integer Data Only but not on floating point values bcoz
floating values does not have certainity its value.
=>The internal flow of Bitwise Operators is that " First They converts Integer Data into Binary Format and
Process the binary data on the basis of BIT by BIT and finally gives the result in the form of Decimal Number
System."
=>In Python Programming, we have the following Bitwise Operators.
1 0 0
0 0 0
1 1 1
-----------------------------------------------------------------------------------------------
Examples:
------------------
>>>a=5--------------------->0101
>>>b=10------------------->1010
--------------
>>>c=a&b ---------------->0000------------result-------0
>>>print(c)
------------------------------------------------------------
>>> a=5
>>> b=10
>>> c=a&b
>>> print(c)---------0
>>> print(10&4)-------0
>>> print(5&7)----------5
----------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------
4. Bitwise OR Operator ( | ):
------------------------------------------------------------------------------------------------------------------
=>The Functionality of Bitwise OR Operator ( | ) is shown in the following Table.
-------------------------------------------------------------------------------------------------------
K V K|V
--------------------------------------------------------------------------------------------------------
0 1 1
1 0 1
0 0 0
1 1 1
--------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------
5. Bitwise Complement Operator ( ~ ):
------------------------------------------------------------------------------------------------- -----------------
=>Bitwise Complement Operator (~) works in such way that " Given Number Converted into Binary and
Converted Binary Number Inverted (Inverted means 0 becomes 1 and 1 becomes 0)"
=>Syntax:- ~Value
or
=>Syntax:- varname= ~Value
Or
=>Syntax:- varname2= ~Variable1
--------------------------------------------------------------------------------------------------------
Formula for Bitwise Complement (~) = ~value=> - (value+1)
--------------------------------------------------------------------------------------------------------
Examples:
------------------
>>>a=5--------------------->0101
>>>b=10------------------->1010
Examples:
-----------------
>>>a=5---------------------->0101
>>>b=4---------------------->0100
-----------------------------------------------------
>>>c=a^b------------------->0001---------------result 1
>>>print(c)------------------- 1
--------------------------------------------------------------
>>> a=10
>>> b=15
>>> print(a^b)---------------------------5
--------------------------------------------------------------------------------------
Special Examples:
----------------------------------------------------------------------------------------
>>> s1={10,20,30}
>>> s2={30,40,50}
>>> s3=s1.union(s2) # # Bitwise OR ( | )
>>> print(s3)-----------------{50, 20, 40, 10, 30}
----------------------------------------------------------------------------------------
>>> s4=s1|s2
>>> print(s4,type(s4))------------------{50, 20, 40, 10, 30} <class 'set'>
----------------------------------------------------------------------------------------
>>> s1={10,20,30}
>>> s2={30,40,50}
>>> s3=s1.intersection(s2)
>>> print(s3)------------------{30}
---------------------------------------------
>>> s1={10,20,30}
>>> s2={30,40,50}
>>> s4=s1&s2 # Bitwise AND ( & )
>>> print(s4,type(s4))-----------------{30} <class 'set'>
-------------------------------------------------------------------------------------------------------
>>> s1={10,20,30}
>>> s2={30,40,50}
>>> s3=s1.symmetric_difference(s2)
>>> print(s3,type(s3))--------------{40, 10, 50, 20} <class 'set'>
---------------------------------------------------
>>> s1={10,20,30}
>>> s2={30,40,50}
>>> s4=s1^s2 # Bitwise XOR ( ^ )
>>> print(s4,type(s4))-----------------{40, 10, 50, 20} <class 'set'>
------------------------------------------------------------------------------------------------------
>>> s1={10,20,30}
>>> s2={30,40,50}
>>> s3=s1.difference(s2)
>>> print(s3)--------------------------{10, 20}
>>> s4=s2.difference(s1)
>>> print(s4)--------------------------{40, 50}
------------------------------------------------------------------------------
>>> s5=s1-s2
>>> print(s5)--------------{10, 20}
>>> s6=s2-s1
>>> print(s6)---------------{40, 50}
================================X==================================
>>> s1={"Apple","Banana","Orange"}
>>> s2={"Orange","Apple","Kiwi"}
>>> s3=s1|s2
>>> print(s3)--------------------------------{'Banana', 'Apple', 'Kiwi', 'Orange'}
>>> s4=s1&s2
>>> print(s4)-------------------------------{'Orange', 'Apple'}
>>> s5=s1^s2
>>> print(s5)-------------------------------{'Banana', 'Kiwi'}
>>> s6=s1-s2
>>> s7=s2-s1
>>> print(s6)-------------------------------{'Banana'}
>>> print(s7)-------------------------------{'Kiwi'}
=================================================
6) Membership Operators
=================================================
=>The purpose of Membership Operators in python is that "To check the existence of Value in
Iterable Object".
=>An Iterable Object is one which contains multiple elements(Sequence, List, set and dict ).
=>In Python Programming, we have 2 types of Membership Operators. They are
1. in
2. not in
-------------------------------------------------------------------------------------------------
1) in:
------------------------------------------------------------------------------------------------
Syntax:- value in Iterable_object
=>The 'in' operator returns True provides "value" present Iterable_object
=>The 'in' operator returns False provides "value" not present Iterable_object
---------------------------------------------------------------------------------------------------------------------
2) not in:
------------------------------------------------------------------------------------------------
Syntax:- value not in Iterable_object
=>The 'not in' operator returns True provides "value" not present Iterable_object
=>The 'not in' operator returns False provides "value" present Iterable_object
---------------------------------------------------------------------------------------------------------------------------
>>> s="PYTHON"
>>> print(s,type(s))------------------------PYTHON <class 'str'>
>>> "P" in s-----------------------True
>>> "p" in s---------------------False
>>> "T" in s----------------------True
>>> "K" in s------------------------False
----------------------------------------
>>> s="PYTHON"
>>> print(s,type(s))-------------PYTHON <class 'str'>
>>> "K" not in s---------------True
>>> "V" not in s-----------------True
>>> "P" not in s-----------------False
>>> "p" not in s-----------------True
>>> "O" not in s-----------------False
-----------------------------------------------------------------------------------------------------------------------
>>> s="PYTHON"
>>> print(s,type(s))----------------------------PYTHON <class 'str'>
>>> "PT" in s-----------------------------------False
>>> "PY" in s----------------------------------True
>>> "PT" not in s------------------------------True
>>> "PYT" not in s----------------------------False
>>> "PYT" in s--------------------------------True
>>> "HON" in s-------------------------------True
>>> "HON" not in s--------------------------False
>>> "NOH" in s-------------------------------False
>>> "NOH" not in s-------------------------True
>>> "NOH" in s[::-1]----------------------- True
>>> "P" in s[::-1]---------------------------- True
>>> "PY" in s[::-1]---------------------------False
>>> "PY" in s[::-1][::-1]--------------------True
>>> "PON" in s------------------------------False
>>> "PTO" in s[::2]-------------------------True
>>> "OTP" in s[::2][::-1]-------------------True
>>> s in s-------------------------------------True
>>> s in s[::]--------------------------------------True
>>> s[::2] in s[::]---------------------------------False
>>> s[::2] in s[::][::2]----------------------------True
====================================================================
>>> lst=[10,"Rossum","Python",34.56,2+3j]
>>> print(lst)-----------------[10, 'Rossum', 'Python', 34.56, (2+3j)]
>>> 12.34 not in lst----------------------True
>>> 2+3j not in lst-----------------------False
>>> "Rossum" in lst-----------------------True
>>> "Pyt" in lst----------------------------False
>>> lst[-3]---------------------------------'Python'
>>> "Pyt" in lst[-3]-----------------------True
>>> "Pyt" in lst[-3][:----------------------...
KeyboardInterrupt
>>> "Pyt" in lst[-3][:-1]-----------------True
>>> lst=[10,"Rossum","Python",34.56,2+3j]
>>> lst[-1].real in lst---------------------False
>>> lst[-1].imag in lst[::-1][0]----------TypeError: argument of type 'complex' is not iterable
>>> lst[-1] in lst---------------------------True
>>> list() in lst-----------------------------False
>>> lst[::-1] not in lst---------------------True
>>> lst in lst--------------------------------False
========================================================
7) Identity Operators (Python Command Prompt):
==========================================================
=>The Purpose of Identity Operators is that "To compare the memory address of two objects ".
=>In Python Programming, we have type of Identity Operators. They are
1. is
2. is not
-----------------------------------------------------------------------a---------------------------------------------
1) is :
-------------------------------------
Syntax:- object1 is object2
=>The 'is' operator returns True provided both object1 and object2 contains same address.
=>The is' operator returns False provided both object1 and object2 contains different address.
----------------------------------------------------------------------------------------------------------------------------
2) is not :
-------------------------------------
Syntax:- object1 is not object2
=>The 'is not ' operator returns True provided both object1 and object2 contains Different
address.
=>The is not ' operator returns False provided both object1 and object2 contains Same
address.
----------------------------------------------------------------------------------------------------------------------------
Examples:
-----------------------
>>> a=None
>>> b=None
>>> print(a,type(a), id(a))---------None <class 'NoneType'> 140722879559672
>>> print(b,type(b), id(b))-----------None <class 'NoneType'> 140722879559672
>>> a is b------------True
>>> a is not b--------False
----------------------------------------------------------------------------------
>> d1={10:"Apples",20:"Mangoes",30:"Oranges"}
>>> print(d1,type(d1),id(d1))----{10: 'Apples', 20: 'Mangoes', 30: 'Oranges'} <class 'dict'> 1434501402176
>>> d2={10:"Apples",20:"Mangoes",30:"Oranges"}
>>> print(d2,type(d2),id(d2))----{10: 'Apples', 20: 'Mangoes', 30: 'Oranges'} <class 'dict'>
1434501402560
>>> d1 is d2-------------False
>>> d1 is not d2-----------True
-------------------------------------------------------------------------------------------------------------------
>>> s1={10,20,30,40}
>>> s2={10,20,30,40}
>>> print(s1,type(s1),id(s1))-------{40, 10, 20, 30} <class 'set'> 2797963152960
>>> print(s2,type(s2),id(s2))-------{40, 10, 20, 30} <class 'set'> 2797963152512
>>> s1 is s2------------------False
>>> s1 is not s2------------True
>>> fs1=frozenset(s1)
>>> fs2=frozenset(s2)
>>> print(fs1,type(fs1),id(fs1))--frozenset({40, 10, 20, 30}) <class 'frozenset'> 2797963154304
>>> print(fs2,type(fs2),id(fs2))-frozenset({40, 10, 20, 30}) <class 'frozenset'> 2797963153856
>>> fs1 is fs2----------False
>>> fs1 is not fs2-------True
-------------------------------------------------------------------------------------------------------------
>>> l1=[10,"Rossum"]
>>> l2=[10,"Rossum"]
>>> print(l1,type(l1),id(l1))----------[10, 'Rossum'] <class 'list'> 2797958988672
>>> print(l2,type(l2),id(l2))---------[10, 'Rossum'] <class 'list'> 2797958989632
>>> t1=(10,"RS")
>>> t2=(10,"RS")
>>> print(t1,type(t1),id(t1))---(10, 'RS') <class 'tuple'> 2797959379072
>>> print(t2,type(t2),id(t2))---(10, 'RS') <class 'tuple'> 2797959378752
>>> l1 is l2------False
>>> l1 is not l2-----True
>>> t1 is t2-------False
>>> t1 is not t2-------True
--------------------------------------------------------------------------------------------------------------------
>>> r1=range(10,20)
>>> r2=range(10,20)
>>> print(r1,type(r1),id(r1))------range(10, 20) <class 'range'> 2797959079392
>>> print(r2,type(r2),id(r2))------range(10, 20) <class 'range'> 2797959081984
>>> r1 is r2-----------------------False
>>> r1 is not r2------------------True
>>> b1=bytearray([10,20,30])
>>> b2=bytearray([10,20,30])
>>> print(b1,type(b1),id(b1))-----bytearray(b'\n\x14\x1e') <class 'bytearray'> 2797963141104
>>> print(b2,type(b2),id(b2))-----bytearray(b'\n\x14\x1e') <class 'bytearray'> 2797963141232
>>> b1 is b2-----------------------------False
>>> b1 is not b2------------------------True
>>> b1=bytes([10,20,30])
>>> b2=bytes([10,20,30])
>>> print(b1,type(b1),id(b1))----------b'\n\x14\x1e' <class 'bytes'> 2797959081504
>>> print(b2,type(b2),id(b2))----------b'\n\x14\x1e' <class 'bytes'> 2797959085440
>>> b1 is b2-------------------------False
>>> b1 is not b2--------------------True
>>> s="INDIA"
>>> r="INDIA"
>>> print(s,type(s),id(s))---------------INDIA <class 'str'> 2797963139184
>>> print(r,type(r),id(r))----------------INDIA <class 'str'> 2797963139184
>>> s is r----------------------------------True
>>> s is not r------------------------------False
>>> s1="INDIA"
>>> s2="INDia"
>>> print(s1,type(s1),id(s1))-----------------INDIA <class 'str'> 2797963139184
>>> print(s2,type(s2),id(s2))-----------------INDia <class 'str'> 2797963141232
>>> s1 is s2--------------------------------------False
>>> s1 is not s2---------------------------------True
>>> "INDIA" is "INDIA"---------------------True
>>> s1="PYTHON"
>>> s2="PYTHON"
>>> s1 is s2--------------------------------------True
------------------------------------------------------------------------------------------------------------------
>>> a=2+3j
>>> b=2+3j
>>> print(a,type(a), id(a))--------------------(2+3j) <class 'complex'> 2797955049008
>>> print(b,type(b), id(b))------------------- (2+3j) <class 'complex'> 2797955051344
>>> a is b---------------------------------------False
>>> a is not b----------------------------------True
>>> a=True
>>> b=True
>>> print(a,type(a), id(a))--------------------True <class 'bool'> 140715741719400
>>> print(b,type(b), id(b))-------------------True <class 'bool'> 140715741719400
>>> a is b---------------------------------------True
>>> a is not b----------------------------------False
>>> a=True
>>> b=False
>>> print(a,type(a), id(a))--------------------True <class 'bool'> 140715741719400
>>> print(b,type(b), id(b))--------------------False <class 'bool'> 140715741719432
>>> a is b---------------------------------------False
>>> a is not b----------------------------------True
>>>
>>> a=12.34
>>> b=12.34
>>> print(a,type(a), id(a))----------------------12.34 <class 'float'> 2797955041360
>>> print(b,type(b), id(b))----------------------12.34 <class 'float'> 2797955041552
>>> a is b------------------------------------------False
>>> a is not b-------------------------------------True
>>> a=2.5
>>> b=2.5
>>> print(a,type(a), id(a))-----------------------2.5 <class 'float'> 2797955046256
>>> print(b,type(b), id(b))----------------------2.5 <class 'float'> 2797955045584
------------------------------------------------------------------
int data type
------------------------------------------------------------------
>>> a=10
>>> b=10
>>> print(a,type(a), id(a))------------------------10 <class 'int'> 2797954007568
>>> print(b,type(b), id(b))------------------------10 <class 'int'> 2797954007568
>>> a is b--------------------------------------------True
>>> a is not b---------------------------------------False
>>> a=256
>>> b=256
>>> print(a,type(a), id(a))--------------------------256 <class 'int'> 2797954015440
>>> print(b,type(b), id(b))-------------------------256 <class 'int'> 2797954015440
>>> a is b--------------------------------------------True
>>> a is not b---------------------------------------False
>>> a=257
>>> b=257
>>> print(a,type(a), id(a))-----------------------257 <class 'int'> 2797955048976
>>> print(b,type(b), id(b))-----------------------257 <class 'int'> 2797955051120
>>> a is b-------------------------------------------False
>>> a is not b--------------------------------------True
>>> a=10
>>> a=0
>>> b=0
>>> print(a,type(a), id(a))-----------------------0 <class 'int'> 2797954007248
>>> print(b,type(b), id(b))---------------------- 0 <class 'int'> 2797954007248
>>> a is b------------------------------------------True
>>> a is not b--------------------------------------False
>>> a=a+10
>>> print(a,type(a), id(a))-----------------------10 <class 'int'> 2797954007568
>>> print(b,type(b), id(b))-----------------------0 <class 'int'> 2797954007248
>>> a is b-------------------------------------------False
>>> a is not b--------------------------------------True
>>>
>>> a=-4
>>> b=-4
>>> print(a,type(a), id(a))---------------------- -4 <class 'int'> 2797954007120
>>> print(b,type(b), id(b))---------------------- -4 <class 'int'> 2797954007120
>>> a is b-------------------------------------------True
>>> a is not b---------------------------------------False
>>> a=-5
>>> b=-5
>>> print(a,type(a), id(a))---------------------- -5 <class 'int'> 2797954007088
>>> print(b,type(b), id(b))--------------------- -5 <class 'int'> 2797954007088
>>> a is b-------------------------------------------True
>>> a is not b---------------------------------------False
>>> a=-6
>>> b=-6
>>> print(a,type(a), id(a))----------------------- -6 <class 'int'> 2797955051344
>>> print(b,type(b), id(b))----------------------- -6 <class 'int'> 2797955048976
>>> a is b--------------------------------------------False
>>> a is not b---------------------------------------True
>>> a=3456
>>> b=3456
>>> print(a,type(a), id(a))------------------------3456 <class 'int'> 2797955051120
>>> print(b,type(b), id(b))------------------------3456 <class 'int'> 2797955051344
>>> a is b--------------------------------------------False
>>> a is not b---------------------------------------True
-------------------------------------------------------------------------------------------------------
>>> a,b=1000,1000
>>> print(a,type(a), id(a))------------------------1000 <class 'int'> 2797955051088
>>> print(b,type(b), id(b))------------------------1000 <class 'int'> 2797955051088
>>> a is b-------------------------------------------True
>>> a is not b---------------------------------------False
>>> a,b=-4567,-4567
>>> print(a,type(a), id(a))-------------------- -4567 <class 'int'> 2797955049008
>>> print(b,type(b), id(b))------------------- -4567 <class 'int'> 2797955049008
>>> a is b----------------------------------------True
>>> a is not b------------------------------------False
>>>
>>>
>>> a,b=["INDIA","DELHI"],["INDIA","DELHI"]
>>> print(a,type(a), id(a))------------['INDIA', 'DELHI'] <class 'list'> 2797963135104
>>> print(b,type(b), id(b))------------['INDIA', 'DELHI'] <class 'list'> 2797963134976
>>> a is b---------------------------------------False
>>> a is not b----------------------------------True
-----------------------------------------------------------------------------------------------------
>>> a,b="PYTHON","PYTHON"
>>> print(a,type(a), id(a))----------------------------PYTHON <class 'str'> 2797963141104
>>> print(b,type(b), id(b))----------------------------PYTHON <class 'str'> 2797963141104
>>> a is b-----------------------------------------------True
>>> a is not b-------------------------------------------False
----------------------------------------------------------------
====================================
Ternary operator in Python:
====================================
=>In Python Program, the Ternary operator is " if else operator ".
=>Syntax:-
varname= expr1 if Test Cond else expr2
(OR)
varname= Val1 if Test Cond else Val2
---------------------
Explanation:
---------------------
=>Here 'if' and 'else' are the keywords
=>Here Test Cond( Relatioal Expression or Logical Expression) is evaluated either to be True
of False
=>If Test Condition Result is "True" then PVM Takes Result of Expr1 (Val1) and Placed in
Varname(LHS)
=>If Test Condition Result is "False" then PVM Takes Result of Expr2 (Val2) and Placed in
Varname(LHS)
--------------------------------------------------------------
Example:
------------------------------------------------------
#bigex1.py
a=float(input("Enter Value of a:")) # a=10
b=float(input("Enter Value of b:")) # b=50
bv= a if a>b else b
print("big({},{})={}".format(a,b,bv))
Example:
---------------
#bigex2.py
a=float(input("Enter Value of a:")) # a=10
b=float(input("Enter Value of b:")) # b=5
result="Both Value Are Equal" if (a==b) else a if(a>b) else b
print("big({},{})={}".format(a,b,result))
Example:
---------------
#bigex3.py
a=float(input("Enter Value of a:")) # a=10
b=float(input("Enter Value of b:")) # b=15
c=float(input("Enter Value of c:")) # c=10
res1="All Values are Equal" if((a==b) and (b==c) and (a==c)) else a if((a>b) and (a>c)) else b if((b>c)
and (b>a)) else c
print("big({},{},{})={}".format(a,b,c,res1))
Example:
--------------
#program for accepting two values and decide big among them by considering equality
#bigex1.py
a=int(input("Enter Value of a:"))
b=int(input("Enter value of b:"))
if(a>b):
print("big({},{})={}".format(a,b,a))
if(b>a):
print("big({},{})={}".format(a,b,b))
if(a==b):
print("both values are equal")
Example:
--------------
#moviee.py
tkt=input("Do u have ticket(yes/no):")
if(tkt=="yes"):
print("Enter into threater")
print("watch and enjoy the moviee")
print("eat...")
print("\nGoto Home and Read Python Notes")
Example:
---------
#Program for accepting a number anb decides +ve(n>0) or -ve(n<0) or zero.(n==0)
#PosNegZero.py
n=int(input("Enter Value of n:")) # n = 100 -100 0
if(n>0):
print("{} is POSSITIVE".format(n))
if(n<0):
print("{} is NEGATIVE".format(n))
if(n==0):
print("{} is ZERO".format(n))
print("Program execution completed")
=======================================================
Flow Control statements in Python
(OR)
Control Structures in Python
=======================================================
Index
-------------
=>Purpose of Flow Control statements in Python
=>Types of Flow Control statements in Python
a) Conditional orSelection or Branching statements
i) simple if statement
ii) if..else statement
iii) if..elif..else statement
iv) match case statement (Python 3.10 Version)
=>Programming Examples
b) Looping or Iterative or Repetative Statements
i) while loop and while...else loop
ii) for loop and for ...else loop
=>Programming Examples
c) Transfer Flow Control statements in Python
i) break
ii) continue
iii) pass
=>Programming Examples
#Program for accepting three integer values and find big among them
#bigthree.py
a=int(input("Enter Value of a:"))
b=int(input("Enter Value of b:"))
c=int(input("Enter Value of c:"))
if( (a==b) and (b==c) ):
print("ALL VALUES ARE EQUAL:")
else:
if((a>b) and (a>c)):
print("big({},{},{})={}".format(a,b,c,a))
else:
if((b>a) and (b>c)):
print("big({},{},{})={}".format(a,b,c,b))
else:
print("big({},{},{})={}".format(a,b,c,c))
Example:
----------------------
#Program for accepting three integer values and find big among them
#bigthree1.py
a=int(input("Enter Value of a:"))
b=int(input("Enter Value of b:"))
c=int(input("Enter Value of c:"))
if( (a==b) and (b==c) ):
print("ALL VALUES ARE EQUAL:")
if(a>b) and (a>c):
print("big({},{},{})={}".format(a,b,c,a))
if(b>a) and (b>c):
print("big({},{},{})={}".format(a,b,c,b))
if(c>a) and (c>b):
print("big({},{},{})={}".format(a,b,c,c))
Example:
------------
#Program for accepting three integer values and find big among them
#bigthree3.py
a=int(input("Enter Value of a:"))
b=int(input("Enter Value of b:"))
c=int(input("Enter Value of c:"))
if( a==b==c):
print("ALL VALUES ARE EQUAL:")
if(b<a>c):
print("big({},{},{})={}".format(a,b,c,a))
if(a<b>c):
print("big({},{},{})={}".format(a,b,c,b))
if(b<c>a):
print("big({},{},{})={}".format(a,b,c,c))
Example:
------------
#Program for accepting two integer values and find big among them
#bigtwo.py
a=int(input("Enter Value of a:")) # a=100
b=int(input("Enter Value of b:")) # b=20
if(a==b):
print("BOTH Values are equal:")
else:
if(a>b):
print("{} is bigger than {}".format(a,b))
else:
print("{} is bigger than {}".format(b,a))
Example:
------------
#Program for accepting any digit and diplay its name
#digitex1.py
d=int(input("Enter any 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:
if(d==8):
print("{} is EIGHT".format(d))
else:
if(d==9):
print("{} is NINE".format(d))
else:
print("{} is a Number".format(d))
Example:
-------------
Example:
-------------
#Program for accepting any digit and diplay its name
#digitex3.py
d=int(input("Enter any 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==4):
print("{} is FOUR:".format(d))
elif(d==3):
print("{} is THREE:".format(d))
elif(d==6):
print("{} is SIX:".format(d))
elif(d==5):
print("{} is FIVE:".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>9):
print("{} is NUMBER:".format(d))
else:
print("{} is -ve number".format(d))
Example:
-------------
==================================================
d) match case statement.
==================================================
=>here "match case" is one the new feature in Python 3.10 Version onwards
=>match case statement is recommended to take in deciding Pre-designed Conditions.
-------------------
=>Syntax:
-------------------
match(Choice Expr):
case Choice Label1:
Block of Stements-1
case Choice Label2:
Block of Stements-2
case Choice Label3:
Block of Stements-3
----------------------------
case Choice Label-n:
Block of Stements-n
case _:
default Block of Statements
-------------------------------------------------------
Other Statements in Program
-------------------------------------------------------
Explanation:
----------------------
=>here "match" and "case" are the keywords
=>"Choice Expr" represents either int or str or bool
=>If "Choice Expr" is matching with "case label1" then PVM executes Block of Staements-1 and later executes
Other statements in program.
=>If "Choice Expr" is matching with "case label2" then PVM executes Block of Staements-2 and later executes
Other statements in program.
=>In General "Choice Expr" is trying match with case label-1, case label-2,....case label-n then PVM executes
corresponding block of statements and later executes Other statements in program.
=>>If "Choice Expr" is not matching with any of the specified case labels then PVM executes Default Block of
Staements which are written 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)
Example:
------------
#FiguresArea.py
import sys
print("-"*50)
print("\tArea of Figures")
print("-"*50)
print("\t1.Area of Circle:")
print("\t2.Area of Rectangle:")
print("\t3.Area of Square:")
print("\t4.Area of Triangle-1:")
print("\t5.Area of Triangle-2:")
print("\t6.Exit:")
print("-"*50)
ch=int(input("Enter Ur Choice:"))
match(ch):
case 2:
l=float(input("Enter Length:"))
b=float(input("Enter Breadth:"))
ar=l*b
print("Area of Rectangle={}".format(ar))
print("-"*50)
case 1:
r=float(input("Enter Radious:"))
ar=3.14*r**2
print("Area of Circle={}".format(ar))
print("-"*50)
case 3:
s=float(input("Enter Side:"))
sa=s**2
print("Area of Square={}".format(sa))
print("-"*50)
case 4:
b=float(input("Enter Base:"))
h=float(input("Enter Height:"))
at=(1/2)*b*h
print("Area of Triangle={}".format(at))
print("-"*50)
case 5:
a=float(input("Enter Value of Side-1:"))
b=float(input("Enter Value of Side-2:"))
c=float(input("Enter Value of Side-3:"))
s=(a+b+c)/2
at=(s*(s-a)*(s-b)*(s-c) )**0.5
print("Area of Triangle={}".format(at))
case 6:
print("Thx for using this program")
case _:
print("Ur Selection of Operation is inavlid-Try again")
Example:
---------
#matchcaseex1.py
wd=input("Enter a week name:")
match(wd.lower()):
case "monday":
print("{} is working Day:".format(wd))
case "tuesday":
print("{} is working Day:".format(wd))
case "wednessday":
print("{} is working Day:".format(wd))
case "thursday":
print("{} is working Day:".format(wd))
case "friday":
print("{} is working Day:".format(wd))
case "saturday":
print("{} is Week End:".format(wd))
case "sunday":
print("{} is Holi Day:".format(wd))
case _:
print("{} is not a week day".format(wd))
Example:
---------
#matchcaseex2.py
wd=input("Enter a week name:")
match(wd.lower()):
case ("monday" | "tuesday" | "wednessday" | "friday" | "thursday" ):
print("{} is working Day:".format(wd))
case "saturday":
print("{} is Week End:".format(wd))
case "sunday":
print("{} is Holi Day:".format(wd))
case _:
print("{} is not a week day".format(wd))
Example:
------------------
#matchcaseex3.py
wd=input("Enter a week name:")
match(wd.upper()[0:3] ):
case ("MON" | "TUE" | "WED" | "FRI" | "THU" ):
print("{} is working Day:".format(wd))
case "SAT":
print("{} is Week End:".format(wd))
case "SUN":
print("{} is HoliDay:".format(wd))
case _:
print("{} is not a week day".format(wd))
Example:
-----------------
#matchcaseex4.py
import calendar
d={"JAN":1,"FEB":2,"MAR":3,"APR":4,"MAY":5,"JUN":6,"JUL":7,"AUG":8,"SEP":9,"OCT":10,"NOV":11,"
DEC":12}
mn=input("Enter a month name:")
match(mn.upper()[0:3] ):
case("JAN" | "FEB"|"MAR"|"APR" | "MAY"|"JUN"|"JUL"|"AUG"|"SEP"|"OCT"|"NOV"|"DEC" ):
print(calendar.month(2022, d.get(mn.upper()[0:3]) ))
case _:
print("{} is not a week day".format(wd))
Example:
---------
#non-matchcaseex5.py
import calendar
d={"JAN":1,"FEB":2,"MAR":3,"APR":4,"MAY":5,"JUN":6,"JUL":7,"AUG":8,"SEP":9,"OCT":10,"NOV
":11,"DEC":12}
mn=input("Enter a month name:")
print(mn.upper()[0:3])
if(12>=d.get(mn.upper()[0:3])>0):
print(calendar.month(2022, d.get(mn.upper()[0:3]) ))
else:
print("Invalid Month:")
Example:
---------
#non-matchcaseex6.py
import calendar
d={"JAN":1,"FEB":2,"MAR":3,"APR":4,"MAY":5,"JUN":6,"JUL":7,"AUG":8,"SEP":9,"OCT":10,"NOV
":11,"DEC":12}
mn=input("Enter a month name:")
mname=mn.upper()[0:3]
mno=d.get(mname)
if(mno==None):
print("{} is invalid month name".format(mn))
else:
print(calendar.month(2022,mno))
=======================================================
2) Looping or Iterative or Repetative Statements
=======================================================
=>The Purpose of Looping or Iterative or Repetative Statements is that Performs ceratin operation
Repeatedly for Finite Number of Times until Condition Becomes False.
=>In Python Programming, we have Two types of Looping statements. They are
=>At the writing Looping level programs, we must ensure that there must 3 parts. They are
# Program for finding Natrual Nums sum, Squares sum and cubes sum
#NatNumsSum.py
n=int(input("Enter a number:"))
if(n<=0):
print("{} is invalid input".format(n))
else:
print("="*50)
print("\tNat Nums\tSquares\t\tCubes")
print("="*50)
s,ss,cs=0,0,0
i=1
while(i<=n):
print("\t{}\t\t{}\t\t{}".format(i,i**2,i**3) )
s=s+i
ss=ss+i**2
cs=cs+i**3
i=i+1
else:
print("="*50)
print("\t{}\t\t{}\t\t{}".format(s,ss,cs) )
print("="*50)