SlideShare a Scribd company logo
Python
3.0
www.scodenetwork.com
Contact No.- 9990211148, 9990211149
What is Python ?
Python is a general purpose, dynamic, high level and interpreted programming language. It supports Object
Oriented programming approach to develop applications.
Python supports multiple programming pattern, including object oriented, imperative and functional or
procedural programming styles.
Python is not intended to work on special area such as web programming. That is why it is known as
multipurpose because it can be used with web, enterprise, 3D CAD etc.
We don't need to use data types to declare variable because it is dynamically typed so we can write a=10 to
assign an integer value in an integer variable.
Python makes the development and debugging fast because there is no compilation step included in python
development and edit-test-debug cycle is very fast.
www.scodenetwork.com
Contact no.- 9990211148, 9990211149
Compiler Vs Interpreter
Compiler Interpreter
Scans the entire program and translates it as a
whole into machine code.
Translates program one statement at a time.
It takes large amount of time to analyze the
source code but the overall execution time is
comparatively faster.
It takes less amount of time to analyze the
source code but the overall execution time is
slower.
Generates intermediate object code which
further requires linking, hence requires more
memory.
No intermediate object code is generated,
hence are memory efficient.
It generates the error message only after
scanning the whole program. Hence
debugging is comparatively hard.
Continues translating the program until the
first error is met, in which case it stops. Hence
debugging is easy.
www.scodenetwork.com
Contact no.- 9990211148, 9990211149
Python History
The implementation of Python was started in the December 1989 by Guido Van Rossum at CWI in
Netherland.
In February 1991, van Rossum published the code (labeled version 0.9.0) to alt. sources.
In 1994, Python 1.0 was released with new features like: lambda, map, filter, and reduce.
Python 2.0 added new features like: list comprehensions, garbage collection system.
On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to rectify
fundamental flaw of the language.
ABC language & Modula-3
www.scodenetwork.com
Contact no.- 9990211148, 9990211149
Python Features
Easy to Learn and Use
Expressive Language
Interpreted Language
Cross-platform Language
Free and Open Source
Object-Oriented Language
GUI Programming Support
Large Standard Library
www.scodenetwork.com
Contact no.- 9990211148, 9990211149
• Dynamically Typed
• Embedded
Flavors of Python:
1.CPython: It is the standard flavor of Python. It can be used to work
with C lanugage Applications
2. Jython or JPython: It is for Java Applications. It can run on JVM
3. IronPython: It is for C#.Net platform
4.PyPy: The main advantage of PyPy is performance will be improved because JIT compiler is
available inside PVM.
5.RubyPython For Ruby Platforms
6. AnacondaPython It is specially designed for handling large volume of data processing.
Python Applications
Web Applications
Desktop GUI Applications
Software Development
Scientific and Numeric
Business Applications
Console Based Application
Audio or Video based Applications
3D CAD Applications
Applications for Images
Enterprise Applications
Python Versions
Python Version Released Date
Python 1.0 January 1994
Python 1.5 December 31, 1997
Python 1.6 September 5, 2000
Python 2.0 October 16, 2000
Python 2.1 April 17, 2001
Python 2.2 December 21, 2001
Python 2.3 July 29, 2003
Python 2.4 November 30, 2004
Python 2.5 September 19, 2006
Python 2.6 October 1, 2008
Python 2.7 July 3, 2010
Python 3.0 December 3, 2008
Python 3.1 June 27, 2009
Python 3.2 February 20, 2011
Python 3.3 September 29, 2012
Python 3.4 March 16, 2014
Python 3.5 September 13, 2015
Python 3.6 December 23, 2016
Python 3.6.4 December 19, 2017
Python 2.X vs 3.X
DIVISION OPERATOR
PRINT FUNCTION Xrange
Error Handling
Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module, or other object. An identifier
starts with a letter A to Z or a to z, or an underscore (_) followed by zero or more letters, underscores and digits
(0 to 9). Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a case
sensitive programming language. Thus, Car and car are two different identifiers in Python.
Here are naming conventions for Python identifiers:
• Class names start with an uppercase letter. All other identifiers start with a
lowercase letter.
• Starting an identifier with a single leading underscore indicates that the
identifier is private.
• Starting an identifier with two leading underscores indicates a strongly private
identifier.
• If the identifier also ends with two trailing underscores, the identifier is a
language-defined special name.
Identifiers
1. The only allowed characters in Python are :===
• alphabet symbols(either lower case or upper case)
• digits(0 to 9)
• underscore symbol(_)
2. By mistake if we are using any other symbol like $
then we will get syntax error.
cash = 10
ca$h =20
3. Identifier should not starts with digit
123total
total123
4.Identifiers are case sensitive. Of course Python
language is case sensitive language. total=10
TOTAL=999
print(total) #10
print(TOTAL) #999
1. Alphabet Symbols (Either Upper case OR Lower case)
2. If Identifier is start with Underscore (_) then it indicates it
is private.
3. Identifier should not start with Digits.
4. Identifiers are case sensitive.
5. We cannot use reserved words as identifiers Eg:
def=10
6. There is no length limit for Python identifiers. But not
recommended to use too lengthy identifiers.
7. Dollor ($) Symbol is not allowed in Python.
Keywords in Python
Program:
Output:
Lines and Indentation
Python provides no braces to indicate blocks of code for class and function definitions or
flow control. Blocks of code are denoted by line indentation, which is rigidly enforced.
Multi-line statements
Statements in Python typically end with a new line. Python does, however, allow the use of
the line continuation character () to denote that the line should continue. For example:
Quotation in Python
Python accepts single ('), double (") and triple (''' or """) quotes to denote string
literals, as long as the same type of quote starts and ends the string.
Triple quotes are also used for multiple line comments
Variables in Python
Variables are nothing but reserved memory locations to store values. This means
when you create a variable, you reserve some space in memory.
Python variables do not need explicit declaration to reserve memory space. The
declaration happens automatically when you assign a value to a variable. The equal sign (=) is
used to assign values to variables.
Multiple Assignment in Python
Python allows you to assign a single value to several variables simultaneously. For
example:
Input and Output in Python
We use the print() function to output data to the standard output device (screen). To allow flexibility we
might want to take the input from the user. In Python, we have the input() function to allow this.
Read multiple values from the keyboard in a single
line.
split() function can take space as separator by default
.But we can pass anything as separator.
Python Data Types
Python has various standard data types that are used to define the operations possible on them and
the storage method for each of them. Data Type represent the type of data present inside a variable.
In Python we are not required to specify the type explicitly. Based on value provided,the type will be
assigned automatically.Hence Python is Dynamically Typed Language.
Python has five standard data types:
•Numbers
•String
•Boolean
•List
•Tuple
•Set
•Dictionary
• bytes
• Bytearray
• range
• None
28/07/2022
In Python everything is object
We can represent int values in the
following ways
1. Decimal form 2. Binary form
3. Octal form 4. Hexa decimal form
1. Decimal form(base-10):
It is the default number system in Python The allowed digits
are: 0 to 9 Eg: a =10
2. Binary form(Base-2):
The allowed digits are : 0 & 1 Literal value should be prefixed
with 0b or 0B
Eg: a = 0B1111 a =0B123 a=b111
3. Octal Form(Base-8):
The allowed digits are : 0 to 7 Literal value should be prefixed
with 0o or 0O.
a=0o123
a=0o786
4. Hexa Decimal Form(Base-16):
The allowed digits are : 0 to 9, a-f (both lower and upper cases
are allowed) Literal value should be prefixed with 0x or 0X
Eg: a =0XFACE a=0XBeef a =0XBeer
Python contains several inbuilt functions
1.type() -- to check the type of variable
2. id() -- to get address of object
3. print() -- to print the value
Base Conversion
1.bin(): We can use bin() to convert from any base to binary.
bin(15)
'0b1111'
bin(0o11)
'0b1001'
bin(0X10)
'0b10000'
2. oct(): We can use oct() to convert from any base to octal.
oct(10)
'0o12'
oct(0B1111)
'0o17'
oct(0X123)
'0o443'
3.hex(): We can use hex() to convert from any base to hexa decimal
hex(100)
'0x64'
hex(0B111111)
'0x3f'
hex(0o12345)
'0x14e5'
Note >>: f=1.2e3
print(f) 1200.0 instead of 'e' we can use 'E‘
The main advantage of exponential form is we can represent
big values in less memory
Complex -- Complex data type has some inbuilt attributes to retrieve
the real part and imaginary part.
a=10+1.5j
b=20+2.5j
c=a+b
c=10.5+3.6j
c.real==>10.5 c.imag==>3.6
bool data type: We can use this data type to
represent boolean values. The only allowed values for
this data type are: True and False
Internally Python represents True as 1 and False as 0
True+True==>2 ,True-False==>1
Python provide the following in-built functions for base conversions.
Python Numbers
Python supports four different numerical types:
•int (signed integers)
•long (long integers, they can also be represented in octal and
hexadecimal)
•float (floating point real values)
•complex (complex numbers)
To Delete a number to a reference we can use del
Python Numbers
eval(): eval Function take a String and
evaluate the Result.
PythonStrings
Strings in Python are identified as a contiguous set of characters represented in the quotation marks.
Python allows for either pairs of single or double quotes. Subsets of strings can be taken using the slice
operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and working their way from -
1 at the end. The plus (+) sign is the string concatenation operator and the asterisk (*) is the
repetition operator.
a = ‘Something’
b = “Something”
c = '''This "Python class very helpful“
for java students'''
Slicing of Strings: Slice means a piece [ ] operator is called slice operator,which can be used to retrieve parts of String. In Python
Strings follows zero based index. The index can be either +ve or -ve. +ve index means forward direction from Left to Right -ve
index means backward direction from Right to Left.
a = “Entertainment”
a1 = a[0]
a2 = a[-1]
a3 = a[2:5]
a4 = a[2,6,2]
a5 = a[-1]
a6 = a[-5:-1]
a7 = a[: :-1]
Note -- long Data Type is available in Python2 but not in Python3. In
Python3 long values also we can represent by using int type only.
Python Strings
Python Escape Sequence Charact
er
Use
' Single quote (')
" Double quote (")
a ASCII Bell (BEL)
b ASCII Backspace (BS)
f ASCII Formfeed (FF)
n ASCII Linefeed (LF)
r
ASCII Carriage
Return (CR)
t
ASCII Horizontal Tab
(TAB)
v
ASCII Vertical Tab
(VT)
u Unicode
x Hexcode
Escape characters are characters that are generally used to
perform certain tasks and their usage in code directs the
compiler to take a suitable action mapped to that character.
Repr():----This function returns a string in its
printable format, i.e doesn’t resolve the
escape sequences.
Python Lists
Lists are one of the most powerful tools in python. They are just like the arrays
declared in other languages. But the most powerful thing is that list need not
be always homogenous. A single list can contain strings, integers, as well as
objects. Lists can also be used for implementing stacks and queues. If we want
to represent a group of values as a single entity where insertion order required
to preserve and duplicates are allowed then we should go for list data type.
1. insertion order is preserved
2. heterogeneous objects are allowed
3. duplicates are allowed
4. Growable in nature
5. values should be enclosed within square brackets.
List Operations
Note:-list is growable in nature. i.e based on our
requirement we can increase or decrease the size.
Note: An ordered, mutable, heterogenous collection of
eleemnts is nothing but list, where duplicates also
allowed.
Python Tuples
A tuple is another sequence data type that is similar to the list. A tuple consists of a number of
values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.
The main differences between lists and tuples are: Lists are enclosed in brackets [ ] and their
elements and size can be changed, while tuples are enclosed in parentheses ( ) and cannot be
updated. Tuples can be thought of as readonly lists.
Note: tuple is the read only version of list .
Python Dictionary
In python, dictionary is similar to hash or maps in other languages. It consists of key value pairs. The value
can be accessed by unique key in the dictionary. If we want to represent a group of values as key-value pairs
then we should go for dict data type.
Duplicate keys are not allowed but values can be duplicated. If we are trying to insert an entry with duplicate
key then old value will be replaced with new value.
Note:
1. In general we can use bytes and bytearray data types to represent binary information like images,video files etc
2. In Python2 long data type is available. But in Python3 it is not available and we can represent long values also by
using int type only.
3. Python there is no char data type. Hence we can represent char values also by using str type.
Range
range Data Type represents a sequence of numbers. The elements present in range Data type
are not modifiable. i.e range Data type is immutable.
Byte Type
Python supports a range of types to store sequences. There are six sequence
types: strings, byte sequences (bytes objects), byte arrays (bytearray objects),
lists, tuples, and range objects.
Bytes and bytearray objects contain single bytes – the former is immutable while
the latter is a mutable sequence. Bytes objects can be constructed the
constructor, bytes(), and from literals; use a b prefix with normal string syntax:
b'python'. To construct byte arrays, use the bytearray() function.
Note bytes data type represens a group of byte numbers just like an array.
Byte type Return a new "bytes" object, which is an immutable sequence of small
integers in the range 0 <= x < 256, print as ASCII characters when displayed.
bytes is an immutable version of bytearray – it has the same non-mutating
methods and the same indexing and slicing behavior.
Byte Array
The only allowed values for byte data type are 0 to 256. By mistake if we are trying to provide any other values then
we will get value error.
Once we creates bytes data type value, we cannot change its values,otherwise we will get TypeError.
Note:----bytearray is exactly same as bytes data type except that its elements can be modified.
Sets
A Set is an unordered collection data type that is iterable, mutable, and has no duplicate
elements. Python’s set class represents the mathematical notion of a set.
The major advantage of using a set, as opposed to a list, is that it has a highly optimized
method for checking whether a specific element is contained in the set.
• Sets are unordered.
• Set elements are unique. Duplicate elements are not allowed.
• A set itself may be modified, but the elements contained in the set must be of an
immutable type.
Properties regarding Sets:----
1. insertion order is not preserved
2. duplicates are not allowed
3. heterogeneous objects are allowed
4. index concept is not applicable
5. It is mutable collection
6. Growable in nature
Frozen Sets Frozen sets are immutable objects that only support methods and operators
that produce a result without affecting the frozen set or sets to which they are applied.
Mutable and Immutable Data Types
In general, data types in Python can be distinguished based on whether objects of the type are mutable
or immutable. The content of objects of immutable types cannot be changed after they are created.
Only mutable objects support methods that change the object in place, such as reassignment of a
sequence slice, which will work for lists, but raise an error for tuples and strings.It is important to
understand that variables in Python are really just references to objects in memory
Some immutable
types
Some mutable types
•int, float, complex
•str
•bytes
•tuple
•frozenset
•bool
•array
•bytearray
•list
•set
•Dict
OPERATORS
Python Arithmetic Operators
Operator
+ Addition
- Subtraction
* Multiplication
/ Divison
% Modulus
** Exponent
// Floor Divison
Note:operator always performs floating point arithmetic.
. Hence it will always returns float value. But Floor division (//) can
perform both floating point
and integral arithmetic. If arguments are int type then result is int
type. If atleast one argument
is float type then result is float type
Python Relational Operators
Opera
tor
Example
== If(a==n) then True
> If(a>n) then True
< If(a<n) then True
>= If(a>=n) then True
<= If(a<=n) then True
!= If(a!=n) then True
<> If(a<>n) then True
Relational operators are symbols that perform operations on data
and return a result as true or false depending on the comparison
conditions. Thus, they are certain functionalities that do something with your variables.
Chaining of relational operators is possible. In the chaining, if all comparisons returns
True then only result is True. If atleast one comparison returns False then the result is
False
Python Assignment Operators
Eg: a+=2 ====> a = a+2
Ternary operator
Python ternary operator is also termed as conditional operator. This is
because it can evaluate a statement with a condition being true or false.
Python ternary operator
• Python ternary operaator was introduced in Python 2.5.
• If used properly, ternary operator can reduce code size and increase
readability of the code.
• There is no special keyword for ternary operator, it’s the way of writing
if-else statement that creates a ternary statement or conditional
expression.
Python Bitwise Operators
Operator
& (AND)
| (OR)
^ (XOR)
~ (Binary Ones Complement)
<< (Binary Left Shift)
>> (Binary Right Shift)
We can apply these operators bitwise. These operators are applicable only for
int and boolean types. By mistake if we are trying to apply for any other type
then we will get Error.
Note: The most significant bit acts as sign bit. 0 value represents +ve number where as 1 represents -ve value. positive numbers will be repesented
directly in the memory where as -ve numbers will be represented indirectly in 2's complement form.
Python Logical Operators
Operator
and (AND)
or (OR)
not (NOT)
For boolean types behaviour:
and ==>If both arguments are True then only result is True or ====>If atleast one arugemnt is True then result is True not
==>complement
True and False ==>False
True or False ===>True
not False ==>True x and y: ==>if x is evaluates to false return x
otherwise return y .
Note = If first argument is zero then result is zero
otherwise result is y.
x or y: If x evaluates to True then result is x otherwise
result is y
not x:
If x is evalutates to False then result is True otherwise
False
Python Membership Operators
Operator
in
not in
We can use Membership operators to check whether the given object present in the given collection.(It may be String,List,Set,Tuple
or Dict)
in -Returns True if the given object present in the specified
Collection
not in -Retruns True if the given object not present in the specified Collection
Python Identity Operators
We can use identity operators for address comparison.
There are 2 identity operators are available
1. is
2. is not
r1 is r2 returns True if both r1 and r2 are pointing to the same object
r1 is not r2 returns True if both r1 and r2 are not pointing to the same object
We can use is operator for address comparison where as == operator for
content comparison.
Python Type Casting
int(value)
float(value)
str(value)
bin(value)
oct(value)
hex(value)
bool(value)
chr(value)
ord(value)
We can convert one type value to another type.
This conversion is called Typecasting or Type coersion.
Note:
• We can convert from any type to int except complex type.
• If we want to convert str type to int type, compulsary str
should contain only integral value and should be specified in base-10
Python Program to find Type and Address of a Value:
Operator Precedence
If multiple operators present then which operator will be evaluated first is decided
by operator precedence.
Math Module in Python
A Module is collection of functions, variables and classes etc.
Math is a module that contains several functions to perform mathematical operations
If we want to use any module in Python, first we have to import that module.
Math Module Examples
Conditional and Looping
Constructs
Decision Making
Decision-making is the anticipation of conditions occurring during the execution of a program
and specified actions taken according to the conditions.
if
if condition : statement
or
if condition :
statement-1
statement-2
statement-3
If condition is true then statements will be
executed.
if-else:
if condition :
Action-1
else :
Action-2
if condition is true then Action-1
will be executed otherwise
Action-2 will be executed.
if-elif-else:
if condition1:
Action-1
elif condition2:
Action-2
elif condition3:
Action-3
elif condition4:
Action-4 else:
Default Action
Based condition the
corresponding action
will be executed.
Code examples for If, else and elif
Nested-If Statement
We can use one if or else if statement inside another if or else if statement(s).
Else operator for Both condition Elif solve this problem
Code example for Elif
Relational Operator in Decision Making
Membership Operator in Decision Making
Identical Operator in Decision Making
Looping and Iteration
A loop statement allows us to execute a statement or group of statements multiple times. The following
diagram illustrates a loop statement
If we want to execute a group of statements multiple times
then we should go for Iterative statements.
1. for loop
2. while loop
If we want to execute some action for every element
present in some sequence(it may be string or
collection)then we should go for for loop.
where sequence can be string or any collection. Body will be
executed for every element present in the sequence.
For Loop
Nested Foor Loop
While Loop
A while loop statement in Python programming language repeatedly executes a
target statement as long as a given condition is true. If we want to execute a group of statements
iteratively until some condition false,then we should go for while loop.
For Loop
It has the ability to iterate over the items of any sequence, such as a list or a string.
Range can accept 3 parameters like [range(1,10,2)] 1
is initial point, 10 is condition and 2 is step
Sometimes we can take a loop inside another loop,which
are also known as nested loops.
Nested Loops
Python allow nested looping
We can use loops to repeat code execution
Repeat code for every item in sequence ==>for loop
Repeat code as long as condition is true ==>while loop
Transfer Statements --- Break and Continue
Break -- We can use break statement inside loops to break loop execution based on some condition.
Continue -- We can use continue statement to skip current iteration and continue next iteration.
Loops with else block:
Insideloopexecution,ifbreakstatementnotexecuted,then
onlyelsepartwillbeexecuted.elsemeans loopwithoutbreak
Break and Continue
Count Number of Digits Using Loop
Prime Number Using Nested Loop
Find a Number is Palindrome or Not Find a Number is Armstrong or Not
Printing a Fibonacci Series
Pass Statement
pass is a keyword in Python. In our programming syntactically if block is required which won't do anything then we
can define that empty block with pass keyword.
|- It is an empty statement
|- It is null statement
|- It won't do anything .
Sometimes in the parent class we have to declare a function with empty body and child class responsible to
provide proper implementation. Such type of empty body we can define by using pass keyword.
String
MANIPULATION AND OPERATIONS
STRING FUNCTIONS & PROBLEMS
The most commonly used object in any project and in any programming language is String only. Hence we should be
aware of complete information about String data type.
What is a String?
Any sequence of characters within either single quotes or double quotes is considered as a String.
Comparison of Strings:
We can use comparison operators (<,<=,>,>=) and equality operators(==,!=) for strings.
Comparison will be performed based on alphabetical order.
We can also use triple quotes to use single quotes or double quotes as symbol
inside String literal.
Eg:
S = 'This is ' single quote symbol' ==>invalid
S = 'This is ' single quote symbol' ==>valid
S = "This is ' single quote symbol"====>valid
S = 'This is " double quotes symbol' ==>valid
S ='The "Python Notes" by ‘Nishant' is very helpful' ==>invalid
S = "The "Python Notes" by ‘Nishant' is very helpful"==>invalid
S = 'The "Python Notes" by ‘Nishant' is very helpful' ==>valid
S = '''The "Python Notes" by ‘NIshant' is very helpful''' ==>valid
How to access characters of a String:
We can access characters of a string by using the following ways.
1. By using index 2. By using slice operator
Python supports both +ve and -ve index.
+ve index means left to right(Forward direction)
-ve index means right to left(Backward direction)
String and its Functions
We can use the following 4 methods
For forwarding direction:
• find() --Returns index of first occurrence of the given substring. If it is not available then we will get -1.
• index() -- index() method is exactly same as find() method except that if the specified substring is not available
then we will get ValueError.
For backward direction:
• rfind()
• rindex()
Finding Substrings:
s=input("Enter main string:")
subs=input("Enter sub string:") flag=False
pos=-1
n=len(s)
while True:
pos=s.find(subs,pos+1,n)
if pos==-1:
break
print("Found at position",pos)
flag=True
if flag==False:
print("Not Found")
startswith() and endswith()
To check type of characters present in a string:
Python contains the following methods for this purpose.
1) isalnum(): Returns True if all characters are alphanumeric( a to z , A to Z ,0
to9 )
2) isalpha(): Returns True if all characters are only alphabet symbols(a to
z,A to Z)
3) isdigit(): Returns True if all characters are digits only( 0 to 9)
4) islower(): Returns True if all characters are lower case alphabet symbols
5) isupper(): Returns True if all characters are upper case aplhabet
symbols
6) istitle(): Returns True if string is in title case
7) isspace(): Returns True if string contains only spaces
Some string Functions
strip(), lstrip(), rstrip()min() and max() ,swapcase and split
Formatting the Strings:
We can format the strings with variable values by using replacement operator {} and format() method.
Program to calculate length of string
String code Example
Program to make a new string from 1st 2 and last 2
characters of a string
List
LISTS ARE ONE OF THE MOST POWERFUL TOOLS IN
PYTHON. THEY ARE JUST LIKE THE ARRAYS DECLARED
IN OTHER LANGUAGES. BUT THE MOST POWERFUL
THING IS THAT LIST NEED NOT BE ALWAYS
HOMOGENOUS.
Manipulation and Operations
Program to get the largest number from a list.
Program to get List from user
Program to count the number of strings where the string length is 2 or
more and the first and last character are same from a given list of strings.
List Code Examples
Program to remove duplicate values from list
Program to sorting a list Program to convert list to str
Tuple
A TUPLE IS ANOTHER SEQUENCE DATA TYPE THAT IS
SIMILAR TO THE LIST. A TUPLE CONSISTS OF A
NUMBER OF VALUES SEPARATED BY COMMAS. UNLIKE
LISTS, HOWEVER, TUPLES ARE ENCLOSED WITHIN
PARENTHESES.
Tuple manipulations and operations.
*Tuple is a immutable data type. So it does not support all the operations like list or
other muttable data types
Tuple manipulations and operations.
*Tuple is a immutable data type. So it does not support all the operations like list or
other muttable data types
Program to unpack a tuple in variables.
Program to create a tuple and sort it.
tup=()
Program to count element based on data type
Set
A SET CONTAINS AN UNORDERED COLLECTION OF
UNIQUE AND IMMUTABLE OBJECTS. THE SET DATA
TYPE IS, AS THE NAME IMPLIES, A PYTHON
IMPLEMENTATION OF THE SETS AS THEY ARE KNOWN
FROM MATHEMATICS.
Operations and Manipulation
Program to test whether every element in S is in T and every element in T is in S.
Program create a Shallow copy of a set
Program to create a frozenset
Program to find maximum and minimum value of set
Dictionary
IN PYTHON, THE DICTIONARY IS SIMILAR TO HASH OR
MAPS IN OTHER LANGUAGES. IT CONSISTS OF KEY-
VALUE PAIRS. THE VALUE CAN BE ACCESSED BY A
UNIQUE KEY IN THE DICTIONARY.
Operation and manipulation
Program to concatenate dictionaries to form a new one
Program to generate and print a dictionary that contains a number (between 1 and n) in the form (x, x*x).
Program to map two lists into dictionary
Program to sort a dictionary by key
Test series
 PROGRAM TO COUNT OCCURRENCE OF A CHARACTER IN A STRING
 PROGRAM TO COUNT THE NUMBER OF STRINGS WHERE THE STRING
LENGTH IS 2 OR MORE AND THE FIRST AND LAST CHARACTER ARE SAME
FROM A GIVEN LIST OF STRINGS.
 PROGRAM TO COUNT ELEMENT OF DIFFERENT DATA TYPE
 PROGRAM TO CREATE A TUPLE AT RUN TIME VIA USER INPUT
 PROGRAM TO SHORT A TUPLE OF INTEGER ELEMENT VIA CODE
Functions in Python
If a group of statements is repeatedly required then it is not recommended to write these
statements everytime seperately.We have to define these statements as a single unit and we
can call that unit any number of times based on our requirement without rewriting. This unit
is nothing but function.
The main advantage of functions is code Reusability.
Note: In other languages functions are known as methods,procedures,subroutines etc .
Python supports 2 types of functions
1. Built in Functions 2. User Defined Functions
Functions and its Syntax
Note: While creating functions we
can use 2 keywords
1. def (mandatory)
2. return (optional)
Parameters
Parameters are inputs to the function. If a function contains parameters,then
at the time of calling,compulsory we should provide values
otherwise,otherwise we will get error.
Return Statement:-
Function can take input values as parameters and executes business logic, and
returns output to the caller with return statement.
Example for Return statement Returning multiple values from a function:
In other languages like C,C++ and Java, function can return
atmost one value. But in Python, a function can return any
number of values.
Arguments and Types of Functions:- 1 Positional Argument
These are the arguments passed to function in correct positional
order.
The number of arguments and position of arguments must be
matched. If we change the order then result may be changed.
If we change the number of arguments then we will get error.
Note  If three actual arguments given and there are
only two formal parameter allowed then it show an error
Default parameter function
Keyword Functions
We can pass argument values by keyword i.e by parameter
name
Here the order of arguments is not important but number of
arguments must be matched.
We can use both positional and keyword arguments
simultaneously. But first we have to take positional arguments
and then keyword arguments,otherwise we will get syntax
error.
Sometimes we can provide default values for
our positional arguments.
If we are not passing any name then only default value will
be considered.
Variable length parameter
1. * indicate that a variable can store multiple values
2. ** indicate that a variable can store multiple values with key
Note: We can mix variable length arguments with positional arguments.
After variable length argument,if we are taking any other arguments then we should provide
values as keyword arguments.
Sometimes we can pass variable number of arguments to our function,such type of
arguments are called variable length arguments.
Function and its behaviour
d
Local and Global
Global Variables
The variables which are declared
outside of function are called global
variables.These variables can be
accessed in all functions of that
module.
Local Variables:
The variables which are declared inside a
function are called local variables. Local
variables are available only for the
function in which we declared it.i.e from
outside of function we cannot access.
Global keyword:
We use global keyword for the2 purposes:
1. To declare global variable inside function
2. To make global variable available to
the function so that we can perform
required modifications
NoteIf global variable and local variable having the same name
then we can access global variable inside a function as follows
Function Recurssive Calling
A function that calls itself is known as Recursive Function.The main advantages of recursive functions are:
1. We can reduce length of the code and improves readability
2. We can solve complex problems very easily.
Functions Anonymous
Sometimes we can declare a function without any name,such type of nameless functions are called anonymous functions or lambda
functions. The main purpose of anonymous function is just for instant use(i.e for one time usage).
lambda Function: -- By using Lambda Functions we can write very concise code so that readability of the program will be improved.
Lambda Function internally returns expression value and we are not required to write return statement explicitly.
Sometimes we can pass a function as an argument to another function. In such cases lambda functions are best choice.
filter() function:-- We can use filter() function to filter values from the given sequence based on some condition.
filter(function,sequence) where function argument is responsible to perform conditional check
sequence can be list or tuple or string.
map() function: --For every element present in the given sequence,apply some functionality and generate new
element with the required modification. For this requirement we should go for map() function.
Eg: For every element present in the list perform double and generate new list of doubles.
reduce() function:-- reduce() function reduces sequence of elements into a single element by applying
the specified function. reduce() function present in functools module and hence we should write import
statement.
Examples with Lambda, Map and Reduce
In Python every thing is treated as object.
Even functions also internally treated as
objects only.
Function insidefunction
Function Aliasing
For the existing function we can give another
name, which is nothing but function aliasing.
We can declare a function inside another function,
such type of functions are called Nested functions.
Closure function
If a function have an inner function and
return it then it is called closure.
Note: We can pass function as argument to
another function
Eg: filter(function,sequence)
map(function,sequence)
reduce(function,sequence)
Square of the elements
Multiply of all no. Of tuple
Reverse a string
Reverse Using Recursion
Calculate block & small letters
Find unique Elements from List
Reverse a number
Reverse a number using recursion
Function Decorators
Decorator is a function which can take a function as argument and extend its functionality and
returns modified function with extended functionality.
But we want to modify this function to provide different message if name is Sam. We can do this without touching wish()
function by using decorator.
@ is use to call
decorator function
More With Decorators
Using Decorator without @ With Condition
Decorator Chaining
We can define multiple decorators for the same function and all these decorators will form
Decorator Chaining.
Generators
Generator is a function which is responsible to generate a sequence of values. We can write generator
functions just like ordinary functions, but it uses yield keyword to return values.
Genrator with reverse ordering
Fibonacci with Python
More with Generators
Advantages of Generator Functions:
1. When compared with class level iterators, generators are very easy to use
2. Improves memory utilization and performance.
3. Generators are best suitable for reading data from large number of large files
4. Generators work great for web scraping and crawling.
Generators vs Normal Collections wrt Memory Utilization:
Normal Collection:
l=[x*x for x in range(10000000000000000)] print(l[0])
We will get MemoryError in this case because all these values are required to store in the memory.
Generators:
g=(x*x for x in range(10000000000000000)) print(next(g))
Output: 0 We won't get any MemoryError because the values won't be stored at the beginning
Procedural vs Modular
Programming
PROCEDURAL PROGRAMMING INVOLVES FOLLOWING AN ALGORITHM
OR A PROCEDURE TO IMPLEMENT ON YOUR SOFTWARE. THE NUMBER
CRUNCHING SOFTWARES ARE GENERALLY BASED ON PROCEDURAL
PROGRAMMING.
WHEREAS MODULAR PROGRAMMING INVOLVING DIVIDING YOUR
OBJECTIVE INTO MODULES AND THEN PIPELINING THE MODULES TO
OBTAIN THE DEFINED OUTPUT. MODULES ARE MADE ON THE BASIS OF
SIMILARITY BETWEEN THE FUNCTIONS.
Modules
A module is a file containing Python definitions and statements. A module can define functions, classes and variables. A module
can also include runnable code. Grouping related code into a module makes the code easier to understand and use.
A group of functions, variables and classes saved to a file, which is nothing but module. Every Python file (.py) acts as a module.
Creating any Module step by step:
1 Create a py file with functions and variables.
2 If we want to use members of module in our
program then we should import that module.
import modulename
3We can access members by using module name.
modulename.variable
modulename.function()
Note: whenever we are using a module in our program, for that module compiled file will be generated and stored in the hard disk
permanently.
from ... import:
We can import particular members of module by using from ... import . The main advantage of this is we can access members
directly without using module name.
We can import all members of a module as follows
from NIshant import *
Modules and More
Various possibilties of import:
• import modulename
• import module1,module2,module3
• import module1 as m
• import module1 as m1,module2 as m2,module3
• from module import member
• from module importmember1,member2,memebr3
• from module import memeber1 as x
• from module import *
Note  Once we defined as alias name,we should use alias
name only and we should not use original name.
Reloading a Module:
By default module will be loaded only once eventhough we
are importing multiple multiple times
test module will be loaded only once eventhough we are importing multiple times.
The problem in this approach is after loading a module if it is updated outside then updated version of module1 is
not available to our program.
We can solve this problem by reloading module explicitly based on our requirement. We can reload by using
reload() function of imp module.
The main advantage of explicit module reloading is we can ensure that updated version is always available to our program.
Finding members of module by using dir() function:
Python provides inbuilt function dir() to list out all members of current module or a specified module.
dir() ===>To list out all members of current module dir(moduleName)==>To list out all members of specified module
Built-in Modules
There is a wide range available of built-in modules in python.
The Special variable __name__:
For every Python program , a special variable __name__ will be added internally. This variable stores information
regarding whether the program is executed as an individual program or as a module.
If the program executed as an individual program then the value of this variable is __main__ If the program executed as a
module from some other program then the value of this variable is the name of module where it is defined.
Hence by using this __name__ variable we can identify whether the program executed directly or as a module.
More on Datetime Modules
Name and Main Concept
Working with Modules
There are so many modules present in python, like math module. Now we discuss random module.
Packages and its structure
Summary diagram of library,packages,modules which contains functions,classes and variables
All underscores in python
In python there are underscores act differently so we study all cases related to underscores.
OOPs in Python
OOPs (Object Oriented Programming) is basic concept of programming language which is widely
use in C++, PHP, ASP.net languages. It is Problem Solving Approach which is carried out using
Object. This is one of influential development used in computer Programming. Main Purpose of
Object Oriented Programming is to simplify a design, programming.
Why we use OPPs.
In Procedural Programming, Program is divided into small parts called Function. Most
of the variables are Global in nature which can be accessed freely from any function
and Data can flow from function to function because of which Data is not Secure
whereas in OOPs Data cannot Move easily from function to function it can make Data
secure using access specifier like Private and Protected because of which Data is
Secure as compare to Procedural Programming. Procedural Programming give the
importance to procedure instead of Data unlike OOPs give more preference to Data
in Place of Procedure.
There is one major exception to that statement. If you want to create a customized data type (such as a Complex or Fraction
number type), and then use it in multiple programs, OOP can be very helpful.
Looked at one way, OOP is actually the creation of customized data types, and therefore, in theory, can be useful even in very
simple environments.
Generally, though, OOP is most useful in one of two situations:
In very complex programs.
In applications that interact with a GUI, network, or event-based programming system.
Procedural vs OOPs
POPs OOPs
In POP, program is divided into small
parts called functions.
In OOP, program is divided into parts
called objects.
In POP, Importance is not given to
data but to functions as well as
sequence of actions to be done.
In OOP, Importance is given to the data
rather than procedures or functions
because it works as a real world.
POP does not have any access
specifier.
OOP has access specifiers named Public,
Private, Protected, etc.
POP does not have any proper way
for hiding data so it is less secure.
OOP provides Data Hiding so provides
more security.
In POP, Overloading is not possible. In OOP, overloading is possible in the form
of Function Overloading and Operator
Overloading.
What is an Object?
An object is nothing but a self-contained component
which consists of methods and properties to make a
particular type of data useful.
An object is a real world entity. Pysical existence of a
class is nothing but object. We can create any number of
objects for a class.
From a programming point of view, an object can be a
data structure, a variable or a function. It has a memory
location allocated.
The object is designed as class hierarchies.
An object contain two things attributes(data, property)
and behavior(task).
Example:= If Human is an object then Attributes are like
Name,height,weight,hobbies etc and Behaviours are
walk,talk,eat,sleep etc.
So as an object I know something and on the basis
of know something then I do something.
OOPs Concept
What is Class?
A class is a blueprint or prototype that defines the
variables and the methods (functions) common to all
objects of a certain kind. In Python every thing is an
object. To create objects we required some Model
or Plan or Blue print, which is nothing but class. We can
write a class to represent properties (attributes)
and actions (behaviour) of object. Properties can be
represented by variables. Actions can be represented
by Methods. Hence class contains both variables and
methods. Object is a instance of class.
1. Instance Methods
2. Class Methods
3. Static Methods
28/07/2022
Python ---Constructor
A constructor is a special type of method (function) which is used to initialize the instance
members of the class.
1) Constructor is used for Initializing the values to the data members of the Class.
1) Constructor is that whose name is same as name of class.
2) Constructor gets Automatically called when an object of class is created.
3) Constructors never have a Return Type even void.
4) Constructor are of Default(Non Parameterized), Parameterized and Copy Constructors.
2) Constructor is optional and if we are not providing any constructor then python will provide
default constructor.
3) Constructor definition is executed when we create the object of this class. Constructors also
verify that there are enough
resources for the object to perform any start-up task.
 Constructor is a special method in python.
 The name of the constructor should be __init__(self)
 Constructor will be executed automatically at the time of object creation.
 The main purpose of constructor is to declare and initialize instance variables.
 Per object constructor will be exeucted only once.
 Constructor can take atleast one argument(atleast self)
Heap
Memory
All objects
Address
In python, the method __init__ simulates the constructor of the class. This method is
called when the class is instantiated. We can pass any number of arguments at the time of
creating the class object, depending upon __init__ definition. It is mostly used to initialize
the class attributes. Every class must have a constructor, even if it simply relies on the
default constructor.
Along with the other attributes, a python class also contains some
built-in class attributes which provide information about the class.
Inbuilt Class Attrributes and Functions
SN Attribute Description
1 __dict__ It provides the
dictionary
containing the
information about
the class
namespace.
2 __doc__ It contains a string
which has the class
documentation
3 __name__ It is used to access
the class name.
4 __module__ It is used to access
the module in
which, this class is
defined.
5 __bases__ It contains a tuple
including all base
classes.
Inbuilt class functions--The in-built
functions defined in the class are
described in the following table
SN Function Description
1 getattr(obj,name,d
efault)
It is used to access
the attribute of the
object.
2 setattr(obj,
name,value)
It is used to set a
particular value to
the specific
attribute of an
object.
3 delattr(obj, name) It is used to delete
a specific attribute.
4 hasattr(obj, name) It returns true if
the object contains
some specific
attribute
Constructor vs Method
Types of Variables:
Inside Python class 3 types of variables are allowed.
1. Instance Variables (Object Level Variables)
2. Static Variables (Class Level Variables)
3. Local variables (Method Level Variables)
1. Instance Variables:
If the value of a variable is varied from object to object,
then such type of variables are called instance variables.
For every object a separate copy of instance variables will
be created.
Where we can declare Instance variables:
1. Inside Constructor by using self variable
2. Inside Instance Method by using self variable
3. Outside of the class by using object reference
variable
Class Variables
28/07/2022
Instance Variables(object level variable): -
1. Inside Constructor by using self variable: We can declare instance variables inside a constructor by using self keyword. Once
we creates object, automatically these variables will be added to the object.
2. Inside Instance Method by using self variable: We can also declare instance variables inside instance method by
using self variable. If any instance variable declared inside instance method, that instance variable will be
added once we call taht method.
3. Outside of the class by using object reference variable: We can also add instance variables outside of a class to
a particular object.
How to access Instance variables:
We can access instance variables with in the class by using self variable and outside of the class by using object reference.
How to delete instance variable from the object:
1. Within a class we can delete instance variable as follows
del self.variableName
2. From outside of class we can delete instance variables as follows
del objectreference.variableName
If we change the values of instance variables of one object then those changes won't be reflected to the remaining objects,
because for every object we are separate copy of instance variables are available.
Reference Variable
Static Variable(Class Level Variable)
If the value of a variable is not varied from object to object, such type of variables we have to declare with
in the class directly but outside of methods. Such type of variables are called Static variables.
For total class only one copy of static variable will be created and shared by all objects of that class.
We can access static variables either by class name or by object reference. But recommended to use class
name.
If we change the value of static variable by using either self or object reference variable,then the value of static variable won't be
changed,just a new instance variable with thatname will be added to that particular object.
Local Variable
• Sometimes to meet temporary requirements of programmer,we can declare variables inside a method
directly,such type of variables are called local variable or temporary variables.
• Local variables will be created at the time of method execution and destroyed once method completes.
• Local variables of a method cannot be accessed from outside of method.
Method and its working
Types of Methods:
Inside Python class 3 types of methods are allowed . Instance Methods , Class Methods and Static Methods
1. Instance Methods: Inside method implementation if we are using instance variables then such type of
methods are called instance methods. Inside instance method declaration,we have to pass self variable.
2. Class Methods:
Inside method implementation if we are using only class
variables (static variables), then such type of methods we
should declare as class method.
We can declare class method explicitly by using
@classmethod decorator. For class method we should
provide cls variable at the time of declaration.
We can call classmethod by using classname or object
reference variable.
ClassMethod--The @classmethod decorator, is a builtin function decorator that is an expression that gets evaluated
after your function is defined. The result of that evaluation shadows your function definition.
A class method receives the class as implicit first argument, just like an instance method receives the instance.
A class method is a method which is bound to the class and not the object of the class.
They have the access to the state of the class as it takes a class parameter that points to the class and not the object
instance.
It can modify a class state that would apply across all the instances of the class. For example it can modify a class
variable that will be applicable to all the instances.
Static Method-- A static method does not receive an implicit first argument.
A static method is also a method which is bound to the class and not the object of the class.
A static method can’t access or modify class state.
It is present in a class because it makes sense for the method to be present in class.
Class Method Vs Static Method
A class method takes cls as first parameter while a static method needs no specific parameters.
A class method can access or modify class state while a static method can’t access or modify it.
In general, static methods know nothing about class state. They are utility type methods that take some parameters and
work upon those parameters. On the other hand class methods must have class as parameter.
We use @classmethod decorator in python to create a class method and we use @staticmethod decorator to create a
static method in python.
Class Method and Static Method
Static Method
In general these methods are general utility methods. Inside these methods we won't use
any instance or class variables.
Here we won't provide self or cls arguments at the time of declaration.
We can declare static method explicitly by using @staticmethod decorator.
We can access static methods by using classname or object reference.
Note: In general we can use only instance and static methods.Inside static method we can
access
• class level variables by using class name.
• class methods are most rarely used methods in python.
Inner Class or Nested class
OOPs Concepts --- Polymorphism
Poly means many. Morphs means forms. Polymorphism means 'Many Forms'.
Polymorphism means same name with different forms(behaviour). E.g. Mobile.
Now there are various division for Polymorphism.
Polymorphism:
• Overloading
• Operator Overloading.
• Method Overloading.
• Constructor Overloading.
• Overriding
• Method Overriding.
• Constructor Overriding.
Overloading and its Types
In Overloading, there is a method, operator and constructor with same name but act differently in
multiple situation.
Example:-- If Bank is a class, deposit and withdrawal is a entity so there are multiple ways to
perform it like cash,
Check and DD etc.
So, In simple way same name with different arguments.
1. Operator Overloading: In Java It never exist.
2. In Python, we achieve Operator Overloading easily.e.g. 6+3, “a”+”b”, 9*2 and “n”*23.
3. It always achieve by using magic(Dunder ) function. And every operator in python has magic
method. And return
type of every magic method is output.
Method and Constructure Overloading(Early /Compile Time Binding)
If 2 methods having same name but different type of arguments then those methods are said to be overloaded methods.
Note: In python, there is no need to define type for anyone explicitly
so how overloading is not available in python.
Basically, in Python overloading concept is not required.
So, we not worry about different types of argments we worry about ,to pass number of arguments.
So for this we have, Default Arguments and Variable length arguments. We also perform overloading with constructors.
Method Overriding(Late/RunTime Binding):
What ever members available in the parent class are by default available to the child class through inheritance. If the child class
not satisfied with parent class implementation then child class is allowed to redefine that method in the child class based on its
requirement. This concept is called overriding. Overriding concept applicable for both methods and constructors.
Method overriding is a concept of object oriented programming that allows us to change the implementation of a function in
the child class that is defined in the parent class. It is the ability of a child class to change the implementation of any method
which is already provided by one of its parent class(ancestors).
Following conditions must be met for overriding a function:
Inheritance should be there. Function overriding cannot be done within a class. We need to derive a child class from a parent
class.
The function that is redefined in the child class should have the same signature as in the parent class i.e. same number of
parameters.
What is inheritance?
Inheritance is used to extend of parent class to its child class. Python can support single level,
multi level, hierarchal and multiple inheritance.
Inheritance in Python
Single Level Inheritance
• Single Parent and Single child
Multi level Inheritance
• One parent but multiple child at diff.
level.
Heirarical Inheritance
• One Parent but multiple child at same
level.
Multiple Inheritance
• MultipleParents but one single child.
At a fairly abstract level, super() provides the
access to those methods of the super-class (parent
class) which have been overridden in a sub-class
(child class) that inherits from it. With the help of
super(), from child class we can call parent class
members. The main motive of super is code
reusability.
Notes: From child class, by using super we cannot call
parent class instance variable we should use self only.
From child class by using super(), we can call parent class
static variable.
Hybrid Inheritance --- (Single + Multiple + Multilevel+Heirarical)
So for this there is a concept of MRO(Method Resolution Order)
• If we have Parent class and child class with same method name.
• So, When we call object then always first method excecute which
present in child and if not present in child then go to parent class.
• For A-- (A- obj)
• For B-- (B-A-obj)
• For C-- (C-A-obj)
• For D– (D-C-B-A-obj)
C3 Algo -- MRO
obj
B
A C
X Y
P
mro(P) = P,X,Y,C,A,B,O
So,here we see that mro for P not actually right.Due to hybrid
Inheritance and there is multiple level present so here for
Calculating MRO we use C3 Algorithm.
Mro(P) = [class(P) + merge(mro(Parents) at samelevel),parentlist]
Mro(P) = P+Merge(mro(x),mro(y),mro(c),XYC). 1 E.g.
Mro(P) = P+Merge(XABo,YBCo,Co,XYC).  step2.
Now here, first level is done now move toward next level.
For this we have to know about head and tail.
e.g.– If we have a list like ABCDEF so in this.
Head --- A
Tail --- BCDEF
For next level always remember one statement.
Mro(P) = P+X+Merge(ABo,YBCo,Co,YC).  step3. remove X
Mro(P) = P+X+A+Merge(Bo,YBCo,Co,YC).  step4. remove A
Now For B, So B is present in head and tail both then leave that list.
Mro(P) = P+X+A+Y+Merge(Bo,BCo,Co,C).  step5. remove Y
Mro(P) = P+X+A+Y+B+Merge(o,Co,Co,C).  step6. remove B
Mro(P) = P+X+A+Y+B+C+Merge(o,o,o).  step7 . remove C
Program to convert integer to roman
Program to convert roman to integer
Program to make possible unique subset
Program to find a pair of elements (indices of the two numbers)
from a given array whose sum equals a specific target number.
Python program to find the three elements that sum to zero from a set
(array) of n real numbers.
Program to implement pow(x, n).
Accessing parent constructor using super()
Passing values to parent constructor using base class name
File Handling
Python too supports file handling and allows users to handle files i.e., to read and write files, along with
many other file handling options, to operate on files.Python treats file differently as text or binary and this is
important. Each line of code includes a sequence of characters and they form text file.
As the part of programming requirement, we have to store our data permanently for future purpose. For
this requirement we should go for files.
Files are very common permanent storage areas to store our data.
And for Temporary storage we use List,Tuple and Dictionary etc. (Heap)
So Permanent storage are Files and Database.(Memory).
Types of Files:
There are 2 types of files
1. Text Files: Usually we can use text files to store character data eg: abc.txt
2. Binary Files: Usually we can use binary files to store binary data like
images,video files, audio files etc.
28/07/2022
File Handling
Opening a File:
Before performing any operation (like read or write) on the file,first we have to open that file.For this we should use Python's inbuilt
function open() .But at the time of open, we have to specify mode,which represents the purpose of opening file. e.g. f =
open(filename, mode)
The allowed modes in Python are
1. r open an existing file for read operation. The file pointer is positioned at the beginning of the file.If the specified file
does not exist then we will get FileNotFoundError.This is default mode.
2. w open an existing file for write operation. If the file already contains some data then it will be overridden. If the
specified file is not already avaialble then this mode will create that file.
3. a  open an existing file for append operation. It won't override existing data.If the specified file is not already avaialble
then this mode will create a new file.
4. r+  To read and write data into the file. The previous data in the file will not be deleted.The file pointer is placed at the
beginning of the file.
5. w+  To write and read data. It will override existing data.
6. a+ To append and read data from the file.It wont override existing data.
7. x  To open a file in exclusive creation mode for write operation. If the file already exists then we will get
FileExistsError.
Note: All the above modes are applicable for text files. If the above modes suffixed with 'b' then these represents for binary files. Eg: rb,wb,ab,r+b,w+b,a+b,xb
28/07/2022
File Handling
Closing a File:
After completing our operations on the file,it is highly recommended to close the file. For this we have to use close()
function. f.close()
Various properties of File Object:
Once we opend a file and we got file object,we can get various details related to that file by using its properties.
name Name of opened file
mode Mode in which the file is opened
closed  Returns boolean value indicates that file is closed or not
readable() Returns boolean value indicates that whether file is readable or not
writable()Returns boolean value indicates that whether file is writable or not.
Writing data to text files:
We can write character data to the text files by using the following 2 methods.
• write(str) -- while writing data by using write() methods, compulsory we have to provide line
seperator(n),otherwise total data should be written to a single line.
• writelines(list of lines)
Reading Character Data from text files:
We can read character data from text file by using the following read methods.
read() To read total data from the file.
read(n)To read 'n' characters from the file
readline() To read only one line
readlines()To read all lines into a list
The with statement:
The with statement can be used while opening a file.We can use this to group
file operation statements within a block. The advantage of with statement is it
will take care closing of file,after completing all operations automatically even
in the case of exceptions also, and we are not required to close explicitly.
28/07/2022
File Handling Operations
tell() We can use tell() method to return current position of the cursor(file pointer) from beginning of the file.
The position(index) of first character in files is zero just like string index.
Seek():We can use seek() method to move cursor(file pointer) to specified location. E.g.f.seek(offset, fromwhere)
offset represents the number of positions .
The allowed values for second attribute(from where) are
0---->From beginning of file(default value)
1---->From current position
2--->From end of the file # Note: Python 2 supports all 3 values but Python 3 supports only zero.
How to check a particular file exists or not?
We can use os library to get information about files in our computer. os module has path sub module,which contains isFile() function to check whether a
particular file exists or not? os.path.isfile(fname).
Handling csv files: CSV==>Comma seperated values
As the part of programming,it is very common requirement to write and read data wrt csv files. Python provides csv module to handle csv files.
Zipping and Unzipping Files:
It is very common requirement to zip and unzip files. The main advantages are:
1. To improve memory utilization
2. We can reduce transport time
3. We can improve performance.
To perform zip and unzip operations, Python contains one in-bulit module zip file. This module contains a class : ZipFile
OS Module for File Handling.
File Handling Theory
FileHandling Directory Working
It is very common requirement to perform operations for directories like
1. To know current working directory.
2. To create a new directory.
3. To remove an existing directory.
4. To rename a directory.
5. To list contents of the directory etc.
os.walk(path,topdown=True,onerror=None,followlinks=False)
It returns an Iterator object whose contents can be displayed by using for loop
path-->Directory path. cwd means .
topdown=True --->Travel from top to bottom
onerror=None --->on error detected which function has to execute.
followlinks=True -->To visit directories pointed by symbolic links.
Note: To display contents of particular directory,we have to provide that directory name as argument to walk() function.
os.walk("directoryname")
What is the difference between listdir() and walk() functions?
In the case of listdir(), we will get contents of specified directory but not sub directory contents. But in the case of walk() function we will get
contents of specified directory and its sub directories also.
Running Other programs from Python program:
os module contains system() function to run programs and commands. It is exactly same as system() function in C language.
os.system("commad string") The argument is any command which is executing from DOS.
OS To perform these operations,Python provides inbuilt
module os,which contains several functions to perform
directory related operations.
The above program display contents of current working
directory but not contents of sub directories.
If we want the contents of a directory including sub
directories then we should go for walk() function.
Program to create or open a
file.
OS Stats
Pickling and Unpickling the object
Sometimes we have to write total state of object to the file and
we have to read total object from the file.
The process of writing state of object to the file is called
pickling and the process of reading state of an object from the
file is called unpickling.
We can implement pickling and unpickling by using pickle
module of Python.
pickle module contains dump() function to perform pickling.
pickle.dump(object,file)
pickle module contains load() function to perform unpickling
obj=pickle.load(file)
Program to write a file
Program to write multiple lines in a file
Program to read a file
File seeking program to point a cusrsor on a specific charactor
Program to remove ‘n’ charactor
Program to copy content of a file in another file
Task: Write a program to create your profile in a text file
Your name, address, contact no, dob, father’s name, mother’s name, course, branch, year,
semester
 All information should be input at runtime by user
 All information should be in well format
 All information should be display immediately after writing
 File name should be entered by user at runtime
 File extension is your own choice
Program to delete a file
Program to rename a file
Directory Operation in Python
Exceptions Handling
IN ANY PROGRAMMING LANGUAGE THERE ARE 2 TYPES OF ERRORS ARE POSS IBLE.
1. SYNTAX ERRORS THE ERRORS WHICH OCCURS BECAUSE OF INVALID SYNTAX
ARE CALLED SYNTAX ERRORS
2. RUNTIME ERRORS  ALSO KNOWN AS EXCEPTIONS. WHILE EXECUTING THE PROGRAM IF
SOMETHING GOES WRONG BECAUSE OF END USER INPUT OR PROGRAMMING LO GIC OR MEMORY
PROBLEMS ETC THEN WE WILL GET RUNTIME ERRORS. EG: PRINT(10/0) ==>ZERODIVISIONERROR :
DIVISION BY ZERO.
N O T E : E X C E P T IO N H A N D LIN G C O N C E P T A P P LIC A B LE F O R R U N T IM E E R R O R S B U T N O T F O R S Y N TA X E R R O R S
WHAT IS EXCEPTION?
AN UNWANTED AND UNEXPECTED EVENT THAT DISTURBS NORMAL FLOW OF PR OGRAM IS CALLED
EXCEPTION.
THE MAIN OBJECTIVE OF EXCEPTION HANDLING IS GRACEFUL TERMINATIO N OF THE PROGRAM. EXCEPTION
HANDLING DOES NOT MEAN REPAIRING EXCEPTION. WE HAVE TO DEFINE ALTERNATIVE WAY TO CONTINUE
REST OF THE PROGRAM NORMALLY.
Default Exception Handing in Python:
Every exception in Python is an object. For every exception type the corresponding classes are available.
Whevever an exception occurs PVM will create the corresponding exception object and will check for handling code. If
handling code is not available then Python interpreter terminates the program abnormally and prints corresponding
exception information to the console. The rest of the program won't be executed.
Every Exception in Python is a class. All exception classes are child classes of BaseException.i.e every exception class
extends BaseException either directly or indirectly. Hence BaseException acts as root for Python Exception Hierarchy.
Customized Exception Handling by using try-except:
It is highly recommended to handle exceptions. The code which may raise exception is called risky code and we have to
take risky code inside try block. The corresponding handling code we have to take inside except block.
1. within the try block if anywhere exception raised then rest of the try block wont be executed eventhough we handled
that exception. Hence we have to take only risky code inside try block and length of the try block should be as less as
possible.
2. In addition to try block,there may be a chance of raising exceptions inside except and finally blocks also.
3. If any statement which is not part of try block raises an exception then it is always abnormal termination.
Exception Hierarchy
Control Flow of try and execpt
Try with multiple catch
The way of handling exception is varied from exception to exception. Hence for every exception type a
seperate except block we have to provide. i.e try with multiple except blocks is possible and recommended
to use.
If try with multiple except blocks available then based on raised exception the corresponding except block
will be executed.
If try with multiple except blocks available then the order of these except blocks is important .Python
interpreter will always consider from top to bottom until matched except block identified.
Single except block that can handle multiple exceptions:
We can write a single except block that can handle multiple different types of exceptions.
except (Exception1,Exception2,exception3,..): or except (Exception1,Exception2,exception3,..) as msg :
Parenthesis are mandatory and this group of exceptions internally considered as tuple.
Default except block:
We can use default except block to handle any type of exceptions. In default except block generally we can print
normal error messages.
***Note: If try with multiple except blocks available then default except block should be last,otherwise we will get
SyntaxError.
Finally block
1. It is not recommended to maintain clean up code(Resource Deallocating Code or Resource Releasing
code) inside try
block because there is no guarentee for the execution of every statement inside try block always.
2. It is not recommended to maintain clean up code inside except block, because if there is no exception
then except block
won't be executed.
Hence we required some place to maintain clean up code which should be executed always irrespective of
whether exception raised or not raised and whether exception handled or not handled. Such type of best
place is nothing but finally block.
The speciality of finally block is it will be executed always whether exception raised or not raised and
whether exception handled or not handled.
*** Note: There is only one situation where finally block won't be executed ie whenever we are using
os._exit(0) function.
Whenever we are using os._exit(0) function then Python Virtual Machine itself will be shutdown.In this
particular case finally won't be executed.
Finally Control Flow
Nested Block
else block with try-except-finally:
We can use else block with try-except-finally blocks. else block will be executed if and only if there are no exceptions inside
try block.
Without catch block else not working PVM not consider it.
Combination of try-except and Finally
Combination of Try-except-else-finally
User defined Exception
Types of Exceptions: 1. Predefined Exceptions 2. User Definded Exceptions
1. Predefined Exceptions:
Also known as in-built exceptions
The exceptions which are raised automatically by Python virtual machine whenver a particular event occurs, are called pre defined exceptions. Eg 1: Whenev
we are trying to perform Division by zero, automatically Python will raise ZeroDivisionError. print(10/0) Eg 2: Whenever we are trying to convert input
value to int type and if input value is not int value then Python will raise ValueError automatically.
x=int("ten")===>ValueError
2. User Defined Exceptions:
Also known as Customized Exceptions or Programatic Exceptions
Some time we have to define and raise exceptions explicitly to indicate that something goes wrong ,such type of exceptions are called User Defined Exceptio
or Customized Exceptions
Programmer is responsible to define these exceptions and Python not having any idea about these. Hence we have to raise explicitly based on our requiremen
using "raise" keyword.
Eg: InSufficientFundsException , InvalidInputException ,TooYoungException ,TooOldException.
How to Define and Raise Customized Exceptions:
Every exception in Python is a class that extends Exception class either directly or indirectly.
Syntax: class classname(predefined exception class name):
def __init__(self,arg):
self.msg=arg
Communication with
Network Server
An overview to Protocols and Ports
HTTP, SMTP, IMAP, FTP are high level protocols which are working on TCP and UDP
TCP and UDP are low level protocols
UDP use in video streaming, VOIP and Online games
HTTP
Web Server
SMTP & IMAP
Email Server
FTP
File Server
VOIP - Voice over internet protocol
UDP – User datagram protocol
IMAP – Internet message access protocol
Email Server
File Server
Web browser controlling
GUI
Programming
with Tkinter
Tkinter Widgets
Widgets Description
Button The Button widget is used to display buttons in your application
Canvas The Canvas widget is used to draw shapes, such as lines, ovals,
polygons and rectangles, in your application.
Checkbutton The Checkbutton widget is used to display a number of options as
checkboxes. The user can select multiple options at a time.
Entry The Entry widget is used to display a single-line text field for
accepting values from a user.
Frame The Frame widget is used as a container widget to organize other
widgets.
Label The Label widget is used to provide a single-line caption for other
widgets. It can also contain images.
Listbox The Listbox widget is used to provide a list of options to a user.
Menu The Menu widget is used to provide various commands to a user.
These commands are contained inside Menubutton.
Tkinter Widgets
Widgets Description
Message The Message widget is used to display multiline text fields for
accepting values from a user.
Radiobutton The Radiobutton widget is used to display a number of options as
radio buttons.
Text The Text widget is used to display text in multiple lines.
tkMessageBox This module is used to display message boxes in your applications.
Creating a tkinter button
Creating a tkinter entry with label widget
Task- Creating a login screen using tkinter
Creating radio button and check boxes
Creating a Layout Using Grid
Display values from Radio Button and Check box
python ppt | Python Course In Ghaziabad | Scode Network Institute
python ppt | Python Course In Ghaziabad | Scode Network Institute
Display values from Entry box on labels
python ppt | Python Course In Ghaziabad | Scode Network Institute
Creating Menus
Creating a listbox
Getting Values from List
Getting Values from Option Menu
Creating Dynamic Tkinter Widgets
Creating Button with Image
Creating Button with Image + Text
Creating Listbox With Scroll Bar
Creating Slider
Creating a text Message
Creating a Counter
Creating a Digital Clock
Creating a Animated Label
Creating an Image
Creating Shapes on Tkinter
GUI calculator in python
GUI calculator in python
GUI calculator in python
Database in
Python
PLAY WITH SQLITE DATABASE
 CREATING & CONNECTING DB
 CREATING TABLES
 INSERTION, DELETION, UPDATION AND FETCHING RECORD.
Database Connectivity
Storage Areas As the Part of our Applications, we required to store our Data like Customers Information, Billing
Information, Calls Information etc.To store this Data, we required Storage Areas. There are 2 types of Storage Areas.
1) Temporary Storage Areas 2) Permanent Storage Areas
1.Temporary Storage Areas:
These are the Memory Areas where Data will be stored temporarily. Eg: Python objects like List, Tuple, Dictionary.
Once Python program completes its execution then these objects will be destroyed automatically and data will be
lost. 2.
2.Permanent Storage Areas:
Also known as Persistent Storage Areas. Here we can store Data permanently. Eg: File Systems, Databases, Data
warehouses,
Big Data Technologies etc
File Systems:
File Systems can be provided by Local operating System. File Systems are best suitable to store very less Amount of
Information.
Limitations:
1) We cannot store huge Amount of Information.
2) There is no Query Language support and hence operations will become very complex.
3) There is no Security for Data.
4) There is no Mechanism to prevent duplicate Data. Hence there may be a chance of Data Inconsistency Problems.
To overcome the above Problems of File Systems, we should go for Databases.
Python DataBase
Databases:
1) We can store Huge Amount of Information in the Databases.
2) Query Language Support is available for every Database and hence we can perform Database Operations very easily.
3) To access Data present in the Database, compulsory username and pwd must be required. Hence Data is secured.
4) Inside Database Data will be stored in the form of Tables. While developing Database Table Schemas, Database Admin
follow various Normalization Techniques and can implement various Constraints like Unique Key Constrains, Primary Key
Constraints etc which prevent Data Duplication. Hence there is no chance of Data Inconsistency Problems.
Limitations of Databases:
1) Database cannot hold very Huge Amount of Information like Terabytes of Data.
2) Database can provide support only for Structured Data (Tabular Data OR Relational Data) and cannot provide support for
Semi Structured Data (like XML Files) and Unstructured Data (like Video Files, Audio Files, Images etc)
To overcome these Problems we should go for more Advanced Storage Areas like Big Data Technologies, Data warehouses etc.
Note: The following is the list of all important methods which can be used for python database programming.
connect() cursor() execute() executescript() executemany() commit() rollback() fetchone() fetchall() fetchmany(n) fetch() close()
Creating and Connecting with DB
Creating table on DB
Insert record into table
Fetch record from table
Update and delete record from table
Output will appear after
executing fetch command
Threading in
Python
 THREAD
 MULTI THREADING
What is a Thread?
A thread is an entity within a process that can be scheduled for execution. Also, it is the smallest unit of
processing that can be performed in an OS. It is also consider as independent part of a process. Also called flow
of executuion.
A thread contains all this information in a Thread Control Block (TCB):
Threading and its Concept
What is MultiThreading?
It is the concept, which is used by operating system to perform the Multi Tasking within the system.
Multi Tasking means executing several task simultaneously. In this, there are two types of Multi Tasking present.
1. Process based Multi Tasking. 2. Thread based Multi Tasking.
Multithreading is defined as the
ability of a processor to execute
multiple threads concurrently.
Example related to multi tasking like at same
time students concentrate on lectures and also
operates its mobile and also look here and
there.
Types of Multi Threading
1. Process based Multi Tasking:
Executing several tasks simmultaneously where each task is a seperate independent process is called process based multi tasking. In this,
all tasks entirely differen from each other means there is no relation between them. It is very much suitable as OS level. And also appear
for application level sometimes.
Eg: while typing python program in the editor we can listen mp3 audio songs from the same system. At the same time we can download a
file from the internet. All these taks are executing simultaneously and independent of each other. Hence it is process based multi
tasking.
2. Thread based MultiTasking:
Executing several tasks simultaneously where each task is a seperate independent part of the same program, is called Thread based multi
tasking, and each independent part is called a Thread. In this, every part is different but belong towards one program.
Note: Whether it is process based or thread based, the main advantage of multi tasking is to improve performance of the system
by reducing response time.
The main important application areas of multi threading are:
1. To implement Multimedia graphics , 2. To develop animations ,3. To develop games, 4. To develop web and appln servers.
Everytime we try to execute bulk instructions simultaneously,not one by one. Python provides one inbuilt module "threading" to provide
support for developing threads. Hence developing multi threaded Programs is very easy in python.
Every Python Program by default contains one thread which is nothing but MainThread.
Thread Creation
The ways of Creating Thread in Python:
We can create a thread in Python by using 3 ways :
1. Creating a Thread without using any class(Functional way).
2. Creating a Thread by extending Thread class(OOP).
3. Creating a Thread without extending Thread class(OOP).
Note:Thread is a pre defined class present in threading module which can be used to create our own Threads.
Main thread is responsible to create and start child thread. Once child started then both act independently.
Setting and Getting Name of a Thread:
Every thread in python has name. It may be default name generated by Python or Customized Name provided by
programmer. We can get and set name of thread by using the following Thread class methods.
t.getName() ,t.name----------Returns Name of Thread.
t.setName(newName) ,t.name = “xyz”-- To set our own name.
Note: Every Thread has implicit variable "name" to represent name of Thread.
• Thread Identification Number(ident): For every thread internally a unique identification number is available.
• active_count(): This function returns the number of active threads currently running.
• enumerate() function: This function returns a list of all active threads currently running.
• isAlive(): method checks whether a thread is still executing or not.
• join() method: If a thread wants to wait until completing some other thread then we should go for join() method.e..gparty
28/07/2022
Multi ThreadingThread Control Block (TCB)
Thread Identifier: Unique id (TID) is assigned to every new thread.
Stack pointer: Points to thread’s stack in the process. Stack contains the local variables under thread’s scope.
Program counter: A register which stores the address of the instruction currently being executed by thread.
Thread state: can be running, ready, waiting, start or done.
Thread’s register set: registers assigned to thread for computations.
Parent process Pointer: A pointer to the Process control block (PCB) of the process that the thread lives on.
Daemon Threads:
The threads which are running in the background are called Daemon Threads. The main objective of Daemon Threads
is to provide support for Non Daemon Threads( like main thread).e.g. Garbage Collection.
Whenever Main Thread runs with low memory, immediately PVM runs Garbage Collector to destroy useless objects
and to provide free memory,so that Main Thread can continue its execution without having any memory problems.
We can check whether thread is Daemon or not by using t.isDaemon() method of Thread class or by using daemon
property.
Nature of Daemon Thread--We can change Daemon nature by using setDaemon() method of Thread class.
t.setDaemon(True) But we can use this method before starting of Thread.i.e once thread started,we cannot change its
Daemon nature,otherwise we will get RuntimeException:cannot set daemon status of active thread.
Default Nature:
By default Main Thread is always non-daemon.But for the remaining threads Daemon nature will be inherited from
parent to child.i.e if the Parent Thread is Daemon then child thread is also Daemon and if the Parent Thread is Non
Daemon then ChildThread is also Non Daemon. But if we want to make child opposite to parent it possible
28/07/2022
Synchronization with Threads
If multiple threads are executing simultaneously then there may be a chance of data inconsistency problems.
Thread synchronization is defined as a mechanism which ensures that two or more concurrent threads do not
simultaneously execute some particular program segment known as critical section.
Critical section refers to the parts of the program where the shared resource is accessed.
Synchronization means at a time only one Thread
The main application areas of synchronization are
1. Online Reservation system 2. Funds Transfer from joint accounts etc
In Python, we can implement synchronization by using the following
1. Lock 2. RLock 3. Semaphore
Concurrent accesses to shared resource can lead to race condition.
A race condition occurs when two or more threads can access shared data and they try to change it at the same time.
As a result, the values of variables may be unpredictable and vary depending on the timings of context switches of
the processes.
Synchronization By using Lock concept:
Locks are the most fundamental synchronization mechanism provided by threading module. We can create Lock
object as follows l=Lock()
The Lock object can be hold by only one thread at a time.If any other thread required the same lock then it will wait
until thread releases lock.(similar to common wash rooms,public telephone booth etc)
A Thread can acquire the lock by using acquire() method. l.acquire() and using release() method. l.release()
Note: To call release() method compulsory thread should be owner of that lock.i.e thread should has the lock
already,otherwise we will get Runtime Exception saying .
28/07/2022
Synchronization with threads
Problem with Simple Lock:
The standard Lock object does not care which thread is currently holding that lock.If the lock is held and any thread attempts
to acquire lock, then it will be blocked,even the same thread is already holding that lock.
If the Thread calls recursive functions or nested access to resources,then the thread may trying to acquire the same lock again
and again,which may block our thread.
RLOCK
To overcome this problem, we should go for RLock(Reentrant Lock). Reentrant means the thread can acquire the same lock
again and again.If the lock is held by other threads then only the thread will be blocked. Reentrant facility is available only
for owner thread but not for other threads.
This RLock keeps track of recursion level and hence for every acquire() call compulsory release() call should be available. i.e
the number of acquire() calls and release() calls should be matched then only lock will be released.
1. Only owner thread can acquire the lock multiple times
2. The number of acquire() calls and release() calls should be matched.
Difference between Lock and RLock
Lock:
1. Lock object can be acquired by only one thread at a time.Even owner thread also cannot acquire multiple times. 2. Not
suitable to execute recursive functions and nested access calls 3. In this case Lock object will takes care only Locked or
unlocked and it never takes care about owner thread and recursion level.
RLock:
1. RLock object can be acquired by only one thread at a time, but owner thread can acquire same lock object multiple times.
2. Best suitable to execute recursive functions and nested access calls 3. In this case RLock object will takes care whether
Locked or unlocked and owner thread information, recursiion level.
Synchronization with Lock
Locks are the most fundamental synchronization mechanism provided by threading module. We can create
Lock object as follows l=Lock()
The Lock object can be hold by only one thread at a time.If any other thread required the same lock then it
will wait until thread releases lock.(e.g==public property)
A Thread can acquire the lock by using acquire() method.==== l.acquire()
A Thread can release the lock by using release() method. ==== l.release()
Note: To call release() method compulsory thread should be owner of that lock.i.e thread should has the lock
already,otherwise we will get Runtime Exception saying RuntimeError: release unlocked lock
Simple threading program
Simple threading program
python ppt | Python Course In Ghaziabad | Scode Network Institute
python ppt | Python Course In Ghaziabad | Scode Network Institute
Character classes: We can use character classes to search a group of
characters
1. [abc]===>Either a or b or c
2. [^abc] ===>Except a and b and c
3. [a-z]==>Any Lower case alphabet symbol
4. [A-Z]===>Any upper case alphabet symbol
5. [a-zA-Z]==>Any alphabet symbol
6. [0-9] Any digit from 0 to 9
7. [a-zA-Z0-9]==>Any alphanumeric character
8. [^a-zA-Z0-9]==>Except alphanumeric characters(Special Characters)
Regular Expression
Pre defined Character classes:
• s --Space character
• S --Any character except space character
• d --Any digit from 0 to 9
• D --Any character except digit
• w --Any word character [a-zA-Z0-9]
• W --Any character except word character (Special Characters) [^a-zA-Z0-9].
• “.” --Any character including special characters
Qunatifiers: Means Quantity
We can use quantifiers to specify the number of
occurrences to match.
a Exactly one 'a'
a+ Atleast one 'a'
a* Any number of a's including zero number
a? Atmost one 'a' ie either zero number or one no.
a{m} Exactly m number of a's
a{m,n} Min m number of a's and Max n no. of a's
^x It will check whether target string starts with x or not
x$ It will check whether target string ends with x or not
28/07/2022
Regular Expression-Introduction
Regular expression is a sequence of character(s) mainly used to find and replace patterns in a string or file. Regular expressions
(called REs, or regexes, or regex patterns) are essentially a tiny, highly specialized programming language embedded inside Python
and made available through the re module. Using this little language, you specify the rules for the set of possible strings that you
want to match; this set might contain English sentences, or e-mail addresses, or anything you like.
If we want to represent a group of Strings according to a particular format/pattern then we should go for Regular Expressions. i.e
Regualr Expressions is a declarative mechanism to represent a group of Strings accroding to particular format/pattern.
Regular expressions use two types of characters:
a) Meta characters: As the name suggests, these characters have a special meaning, similar to * in wild card.
e.g. -- . ^ $ * + ? { } [ ]  | ( )
b) Literals (like a,b,1,2…)
In Python, we have module “re” that helps with regular expressions. So you need to import library re before you can use regular
expressions in Python.
Applications
1. To develop validation frameworks/validation logic
2. To develop Pattern matching applications (ctrl-f in windows, grep in UNIX etc)
3. To develop Translators like compilers, interpreters etc
4. To develop digital circuits
5. To develop communication protocols like TCP/IP, UDP etc.
Functions-----
1. compile() re module contains compile() function to compile a pattern into RegexObject.
2. finditer(): Returns an Iterator object which yields Match object for every Match.
start()--Returns start index of the match 2. end()--Returns end+1 index of the match 3. group()--Returns the matched string
28/07/2022
Regular Expression-Functions
Methods of Regular Expressions?
The ‘re’ package provides multiple methods to perform queries on an input string. Here are the most commonly used methods,
• re.match()---We can use match function to check the given pattern at beginning of target string. If the match is available
then we will get Match object, otherwise we will get None.
• re.fullmatch()---We can use fullmatch() function to match a pattern to all of target string. i.e complete string should be
matched according to given pattern. If complete string matched then this function returns Match object
otherwise it returns None.
• re.search()--- We can use search() function to search the given pattern in the target string. If the match is available then it
returns the Match object which represents first occurrence of the match. If the match is not available then it
returns None
• re.findall()---To find all occurrences of the match. This function returns a list object which contains all occurrences.
• re.split()--- If we want to split the given target string according to a particular pattern then we should go for split() function
• re.sub()---In the target string every matched pattern will be replaced with provided replacement.
• re.subn()--- This function returns a tuple where first element is result string and second element is number of replacements.
• re.finditer()---Returns the iterator yielding a match object for each match. On each match object we can call start(), end()
and group() functions.
• re.compile()---
• ^ symbol--We can use ^ symbol to check whether the given target string starts with our provided pattern or not. if the target
string starts with Learn then it will return Match object,otherwise returns None.
• $ symbol--We can use $ symbol to check whether the given target string ends with our provided pattern or not

More Related Content

What's hot (20)

PPTX
Data Structures in Python
Devashish Kumar
 
PDF
Introduction to python programming
Srinivas Narasegouda
 
PPTX
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Maulik Borsaniya
 
PPTX
Introduction to python
AnirudhaGaikwad4
 
PDF
Variables & Data Types In Python | Edureka
Edureka!
 
PPTX
Python
Aashish Jain
 
PDF
Python Intro
Tim Penhey
 
PDF
Let’s Learn Python An introduction to Python
Jaganadh Gopinadhan
 
PPTX
Introduction to-python
Aakashdata
 
PDF
Numeric Data types in Python
jyostna bodapati
 
PPTX
Python
SHIVAM VERMA
 
PDF
Introduction to python
Agung Wahyudi
 
PPTX
Python programming
Ashwin Kumar Ramasamy
 
PPSX
Programming with Python
Rasan Samarasinghe
 
PDF
Python Tutorial | Python Tutorial for Beginners | Python Training | Edureka
Edureka!
 
PDF
Python introduction
Jignesh Kariya
 
PPTX
Python training
Kunalchauhan76
 
PDF
Learn Python Programming | Python Programming - Step by Step | Python for Beg...
Edureka!
 
PPTX
Why Python?
Adam Pah
 
PDF
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
Edureka!
 
Data Structures in Python
Devashish Kumar
 
Introduction to python programming
Srinivas Narasegouda
 
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Maulik Borsaniya
 
Introduction to python
AnirudhaGaikwad4
 
Variables & Data Types In Python | Edureka
Edureka!
 
Python
Aashish Jain
 
Python Intro
Tim Penhey
 
Let’s Learn Python An introduction to Python
Jaganadh Gopinadhan
 
Introduction to-python
Aakashdata
 
Numeric Data types in Python
jyostna bodapati
 
Python
SHIVAM VERMA
 
Introduction to python
Agung Wahyudi
 
Python programming
Ashwin Kumar Ramasamy
 
Programming with Python
Rasan Samarasinghe
 
Python Tutorial | Python Tutorial for Beginners | Python Training | Edureka
Edureka!
 
Python introduction
Jignesh Kariya
 
Python training
Kunalchauhan76
 
Learn Python Programming | Python Programming - Step by Step | Python for Beg...
Edureka!
 
Why Python?
Adam Pah
 
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
Edureka!
 

Similar to python ppt | Python Course In Ghaziabad | Scode Network Institute (20)

PDF
python course ppt pdf
Scode Network Institute
 
PPTX
Introduction to python
MaheshPandit16
 
PPTX
python_class.pptx
chandankumar943868
 
PPTX
Python Programming 1.pptx
Francis Densil Raj
 
PPT
python introduction all the students.ppt
ArunkumarM192050
 
PPTX
presentation_python_7_1569170870_375360.pptx
ansariparveen06
 
PPT
Python - Module 1.ppt
jaba kumar
 
PPTX
Python Programming for problem solving.pptx
NishaM41
 
PPTX
python
ultragamer6
 
PPTX
Python Programming-1.pptx of python by computer
sharanyarashmir5
 
PDF
python-online&offline-training-in-kphb-hyderabad (1) (1).pdf
KosmikTech1
 
PPTX
Chapter 1-Introduction and syntax of python programming.pptx
atharvdeshpande20
 
PDF
PART - 1 Python Introduction- Variables- Data types - Numeric- String- Boole...
manikamr074
 
PDF
Python-01| Fundamentals
Mohd Sajjad
 
PPTX
UNIT 1 .pptx
Prachi Gawande
 
PDF
Python Programming
Saravanan T.M
 
PPTX
2. Getting Started with Python second lesson .pptx
Primary2Primary2
 
PPTX
Python basics
Manisha Gholve
 
PDF
Sessisgytcfgggggggggggggggggggggggggggggggg
pawankamal3
 
python course ppt pdf
Scode Network Institute
 
Introduction to python
MaheshPandit16
 
python_class.pptx
chandankumar943868
 
Python Programming 1.pptx
Francis Densil Raj
 
python introduction all the students.ppt
ArunkumarM192050
 
presentation_python_7_1569170870_375360.pptx
ansariparveen06
 
Python - Module 1.ppt
jaba kumar
 
Python Programming for problem solving.pptx
NishaM41
 
python
ultragamer6
 
Python Programming-1.pptx of python by computer
sharanyarashmir5
 
python-online&offline-training-in-kphb-hyderabad (1) (1).pdf
KosmikTech1
 
Chapter 1-Introduction and syntax of python programming.pptx
atharvdeshpande20
 
PART - 1 Python Introduction- Variables- Data types - Numeric- String- Boole...
manikamr074
 
Python-01| Fundamentals
Mohd Sajjad
 
UNIT 1 .pptx
Prachi Gawande
 
Python Programming
Saravanan T.M
 
2. Getting Started with Python second lesson .pptx
Primary2Primary2
 
Python basics
Manisha Gholve
 
Sessisgytcfgggggggggggggggggggggggggggggggg
pawankamal3
 

More from Scode Network Institute (7)

PDF
What is Computer network
Scode Network Institute
 
PPTX
digital marketing ppt.pptx
Scode Network Institute
 
PDF
What is a Computer Network
Scode Network Institute
 
PPTX
introduction of ethical hacking. (ppt)
Scode Network Institute
 
PPTX
introduction of ethical hacking. ppt
Scode Network Institute
 
PDF
cyber_security_syllabus .pdf | scode network institute
Scode Network Institute
 
PDF
Certified_Ethical_Hacker_Training ppt.pdf
Scode Network Institute
 
What is Computer network
Scode Network Institute
 
digital marketing ppt.pptx
Scode Network Institute
 
What is a Computer Network
Scode Network Institute
 
introduction of ethical hacking. (ppt)
Scode Network Institute
 
introduction of ethical hacking. ppt
Scode Network Institute
 
cyber_security_syllabus .pdf | scode network institute
Scode Network Institute
 
Certified_Ethical_Hacker_Training ppt.pdf
Scode Network Institute
 

Recently uploaded (20)

PDF
Week 2 - Irish Natural Heritage Powerpoint.pdf
swainealan
 
PDF
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
PDF
Android Programming - Basics of Mobile App, App tools and Android Basics
Kavitha P.V
 
PDF
Mahidol_Change_Agent_Note_2025-06-27-29_MUSEF
Tassanee Lerksuthirat
 
PDF
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
PPTX
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
PDF
Council of Chalcedon Re-Examined
Smiling Lungs
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PDF
STATEMENT-BY-THE-HON.-MINISTER-FOR-HEALTH-ON-THE-COVID-19-OUTBREAK-AT-UG_revi...
nservice241
 
PDF
Introduction presentation of the patentbutler tool
MIPLM
 
PPTX
Difference between write and update in odoo 18
Celine George
 
PPTX
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
PDF
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PPTX
How to Create a Customer From Website in Odoo 18.pptx
Celine George
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PPTX
EDUCATIONAL MEDIA/ TEACHING AUDIO VISUAL AIDS
Sonali Gupta
 
PPTX
How to Send Email From Odoo 18 Website - Odoo Slides
Celine George
 
PDF
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
PPTX
DIGITAL CITIZENSHIP TOPIC TLE 8 MATATAG CURRICULUM
ROBERTAUGUSTINEFRANC
 
Week 2 - Irish Natural Heritage Powerpoint.pdf
swainealan
 
Characteristics, Strengths and Weaknesses of Quantitative Research.pdf
Thelma Villaflores
 
Android Programming - Basics of Mobile App, App tools and Android Basics
Kavitha P.V
 
Mahidol_Change_Agent_Note_2025-06-27-29_MUSEF
Tassanee Lerksuthirat
 
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
How to Create Odoo JS Dialog_Popup in Odoo 18
Celine George
 
Council of Chalcedon Re-Examined
Smiling Lungs
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
STATEMENT-BY-THE-HON.-MINISTER-FOR-HEALTH-ON-THE-COVID-19-OUTBREAK-AT-UG_revi...
nservice241
 
Introduction presentation of the patentbutler tool
MIPLM
 
Difference between write and update in odoo 18
Celine George
 
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
How to Create a Customer From Website in Odoo 18.pptx
Celine George
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
EDUCATIONAL MEDIA/ TEACHING AUDIO VISUAL AIDS
Sonali Gupta
 
How to Send Email From Odoo 18 Website - Odoo Slides
Celine George
 
Exploring the Different Types of Experimental Research
Thelma Villaflores
 
DIGITAL CITIZENSHIP TOPIC TLE 8 MATATAG CURRICULUM
ROBERTAUGUSTINEFRANC
 

python ppt | Python Course In Ghaziabad | Scode Network Institute

  • 2. What is Python ? Python is a general purpose, dynamic, high level and interpreted programming language. It supports Object Oriented programming approach to develop applications. Python supports multiple programming pattern, including object oriented, imperative and functional or procedural programming styles. Python is not intended to work on special area such as web programming. That is why it is known as multipurpose because it can be used with web, enterprise, 3D CAD etc. We don't need to use data types to declare variable because it is dynamically typed so we can write a=10 to assign an integer value in an integer variable. Python makes the development and debugging fast because there is no compilation step included in python development and edit-test-debug cycle is very fast.
  • 4. Compiler Vs Interpreter Compiler Interpreter Scans the entire program and translates it as a whole into machine code. Translates program one statement at a time. It takes large amount of time to analyze the source code but the overall execution time is comparatively faster. It takes less amount of time to analyze the source code but the overall execution time is slower. Generates intermediate object code which further requires linking, hence requires more memory. No intermediate object code is generated, hence are memory efficient. It generates the error message only after scanning the whole program. Hence debugging is comparatively hard. Continues translating the program until the first error is met, in which case it stops. Hence debugging is easy. www.scodenetwork.com Contact no.- 9990211148, 9990211149
  • 5. Python History The implementation of Python was started in the December 1989 by Guido Van Rossum at CWI in Netherland. In February 1991, van Rossum published the code (labeled version 0.9.0) to alt. sources. In 1994, Python 1.0 was released with new features like: lambda, map, filter, and reduce. Python 2.0 added new features like: list comprehensions, garbage collection system. On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to rectify fundamental flaw of the language. ABC language & Modula-3 www.scodenetwork.com Contact no.- 9990211148, 9990211149
  • 6. Python Features Easy to Learn and Use Expressive Language Interpreted Language Cross-platform Language Free and Open Source Object-Oriented Language GUI Programming Support Large Standard Library www.scodenetwork.com Contact no.- 9990211148, 9990211149
  • 7. • Dynamically Typed • Embedded Flavors of Python: 1.CPython: It is the standard flavor of Python. It can be used to work with C lanugage Applications 2. Jython or JPython: It is for Java Applications. It can run on JVM 3. IronPython: It is for C#.Net platform 4.PyPy: The main advantage of PyPy is performance will be improved because JIT compiler is available inside PVM. 5.RubyPython For Ruby Platforms 6. AnacondaPython It is specially designed for handling large volume of data processing.
  • 8. Python Applications Web Applications Desktop GUI Applications Software Development Scientific and Numeric Business Applications Console Based Application Audio or Video based Applications 3D CAD Applications Applications for Images Enterprise Applications
  • 9. Python Versions Python Version Released Date Python 1.0 January 1994 Python 1.5 December 31, 1997 Python 1.6 September 5, 2000 Python 2.0 October 16, 2000 Python 2.1 April 17, 2001 Python 2.2 December 21, 2001 Python 2.3 July 29, 2003 Python 2.4 November 30, 2004 Python 2.5 September 19, 2006 Python 2.6 October 1, 2008 Python 2.7 July 3, 2010 Python 3.0 December 3, 2008 Python 3.1 June 27, 2009 Python 3.2 February 20, 2011 Python 3.3 September 29, 2012 Python 3.4 March 16, 2014 Python 3.5 September 13, 2015 Python 3.6 December 23, 2016 Python 3.6.4 December 19, 2017
  • 10. Python 2.X vs 3.X DIVISION OPERATOR PRINT FUNCTION Xrange Error Handling
  • 11. Python Identifiers A Python identifier is a name used to identify a variable, function, class, module, or other object. An identifier starts with a letter A to Z or a to z, or an underscore (_) followed by zero or more letters, underscores and digits (0 to 9). Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a case sensitive programming language. Thus, Car and car are two different identifiers in Python. Here are naming conventions for Python identifiers: • Class names start with an uppercase letter. All other identifiers start with a lowercase letter. • Starting an identifier with a single leading underscore indicates that the identifier is private. • Starting an identifier with two leading underscores indicates a strongly private identifier. • If the identifier also ends with two trailing underscores, the identifier is a language-defined special name.
  • 12. Identifiers 1. The only allowed characters in Python are :=== • alphabet symbols(either lower case or upper case) • digits(0 to 9) • underscore symbol(_) 2. By mistake if we are using any other symbol like $ then we will get syntax error. cash = 10 ca$h =20 3. Identifier should not starts with digit 123total total123 4.Identifiers are case sensitive. Of course Python language is case sensitive language. total=10 TOTAL=999 print(total) #10 print(TOTAL) #999 1. Alphabet Symbols (Either Upper case OR Lower case) 2. If Identifier is start with Underscore (_) then it indicates it is private. 3. Identifier should not start with Digits. 4. Identifiers are case sensitive. 5. We cannot use reserved words as identifiers Eg: def=10 6. There is no length limit for Python identifiers. But not recommended to use too lengthy identifiers. 7. Dollor ($) Symbol is not allowed in Python.
  • 14. Lines and Indentation Python provides no braces to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by line indentation, which is rigidly enforced. Multi-line statements Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character () to denote that the line should continue. For example:
  • 15. Quotation in Python Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the same type of quote starts and ends the string. Triple quotes are also used for multiple line comments
  • 16. Variables in Python Variables are nothing but reserved memory locations to store values. This means when you create a variable, you reserve some space in memory. Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.
  • 17. Multiple Assignment in Python Python allows you to assign a single value to several variables simultaneously. For example:
  • 18. Input and Output in Python We use the print() function to output data to the standard output device (screen). To allow flexibility we might want to take the input from the user. In Python, we have the input() function to allow this. Read multiple values from the keyboard in a single line. split() function can take space as separator by default .But we can pass anything as separator.
  • 19. Python Data Types Python has various standard data types that are used to define the operations possible on them and the storage method for each of them. Data Type represent the type of data present inside a variable. In Python we are not required to specify the type explicitly. Based on value provided,the type will be assigned automatically.Hence Python is Dynamically Typed Language. Python has five standard data types: •Numbers •String •Boolean •List •Tuple •Set •Dictionary • bytes • Bytearray • range • None
  • 20. 28/07/2022 In Python everything is object We can represent int values in the following ways 1. Decimal form 2. Binary form 3. Octal form 4. Hexa decimal form 1. Decimal form(base-10): It is the default number system in Python The allowed digits are: 0 to 9 Eg: a =10 2. Binary form(Base-2): The allowed digits are : 0 & 1 Literal value should be prefixed with 0b or 0B Eg: a = 0B1111 a =0B123 a=b111 3. Octal Form(Base-8): The allowed digits are : 0 to 7 Literal value should be prefixed with 0o or 0O. a=0o123 a=0o786 4. Hexa Decimal Form(Base-16): The allowed digits are : 0 to 9, a-f (both lower and upper cases are allowed) Literal value should be prefixed with 0x or 0X Eg: a =0XFACE a=0XBeef a =0XBeer Python contains several inbuilt functions 1.type() -- to check the type of variable 2. id() -- to get address of object 3. print() -- to print the value
  • 21. Base Conversion 1.bin(): We can use bin() to convert from any base to binary. bin(15) '0b1111' bin(0o11) '0b1001' bin(0X10) '0b10000' 2. oct(): We can use oct() to convert from any base to octal. oct(10) '0o12' oct(0B1111) '0o17' oct(0X123) '0o443' 3.hex(): We can use hex() to convert from any base to hexa decimal hex(100) '0x64' hex(0B111111) '0x3f' hex(0o12345) '0x14e5' Note >>: f=1.2e3 print(f) 1200.0 instead of 'e' we can use 'E‘ The main advantage of exponential form is we can represent big values in less memory Complex -- Complex data type has some inbuilt attributes to retrieve the real part and imaginary part. a=10+1.5j b=20+2.5j c=a+b c=10.5+3.6j c.real==>10.5 c.imag==>3.6 bool data type: We can use this data type to represent boolean values. The only allowed values for this data type are: True and False Internally Python represents True as 1 and False as 0 True+True==>2 ,True-False==>1 Python provide the following in-built functions for base conversions.
  • 22. Python Numbers Python supports four different numerical types: •int (signed integers) •long (long integers, they can also be represented in octal and hexadecimal) •float (floating point real values) •complex (complex numbers) To Delete a number to a reference we can use del
  • 23. Python Numbers eval(): eval Function take a String and evaluate the Result.
  • 24. PythonStrings Strings in Python are identified as a contiguous set of characters represented in the quotation marks. Python allows for either pairs of single or double quotes. Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and working their way from - 1 at the end. The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator. a = ‘Something’ b = “Something” c = '''This "Python class very helpful“ for java students''' Slicing of Strings: Slice means a piece [ ] operator is called slice operator,which can be used to retrieve parts of String. In Python Strings follows zero based index. The index can be either +ve or -ve. +ve index means forward direction from Left to Right -ve index means backward direction from Right to Left. a = “Entertainment” a1 = a[0] a2 = a[-1] a3 = a[2:5] a4 = a[2,6,2] a5 = a[-1] a6 = a[-5:-1] a7 = a[: :-1] Note -- long Data Type is available in Python2 but not in Python3. In Python3 long values also we can represent by using int type only.
  • 26. Python Escape Sequence Charact er Use ' Single quote (') " Double quote (") a ASCII Bell (BEL) b ASCII Backspace (BS) f ASCII Formfeed (FF) n ASCII Linefeed (LF) r ASCII Carriage Return (CR) t ASCII Horizontal Tab (TAB) v ASCII Vertical Tab (VT) u Unicode x Hexcode Escape characters are characters that are generally used to perform certain tasks and their usage in code directs the compiler to take a suitable action mapped to that character. Repr():----This function returns a string in its printable format, i.e doesn’t resolve the escape sequences.
  • 27. Python Lists Lists are one of the most powerful tools in python. They are just like the arrays declared in other languages. But the most powerful thing is that list need not be always homogenous. A single list can contain strings, integers, as well as objects. Lists can also be used for implementing stacks and queues. If we want to represent a group of values as a single entity where insertion order required to preserve and duplicates are allowed then we should go for list data type. 1. insertion order is preserved 2. heterogeneous objects are allowed 3. duplicates are allowed 4. Growable in nature 5. values should be enclosed within square brackets.
  • 28. List Operations Note:-list is growable in nature. i.e based on our requirement we can increase or decrease the size. Note: An ordered, mutable, heterogenous collection of eleemnts is nothing but list, where duplicates also allowed.
  • 29. Python Tuples A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses. The main differences between lists and tuples are: Lists are enclosed in brackets [ ] and their elements and size can be changed, while tuples are enclosed in parentheses ( ) and cannot be updated. Tuples can be thought of as readonly lists. Note: tuple is the read only version of list .
  • 30. Python Dictionary In python, dictionary is similar to hash or maps in other languages. It consists of key value pairs. The value can be accessed by unique key in the dictionary. If we want to represent a group of values as key-value pairs then we should go for dict data type. Duplicate keys are not allowed but values can be duplicated. If we are trying to insert an entry with duplicate key then old value will be replaced with new value. Note: 1. In general we can use bytes and bytearray data types to represent binary information like images,video files etc 2. In Python2 long data type is available. But in Python3 it is not available and we can represent long values also by using int type only. 3. Python there is no char data type. Hence we can represent char values also by using str type.
  • 31. Range range Data Type represents a sequence of numbers. The elements present in range Data type are not modifiable. i.e range Data type is immutable.
  • 32. Byte Type Python supports a range of types to store sequences. There are six sequence types: strings, byte sequences (bytes objects), byte arrays (bytearray objects), lists, tuples, and range objects. Bytes and bytearray objects contain single bytes – the former is immutable while the latter is a mutable sequence. Bytes objects can be constructed the constructor, bytes(), and from literals; use a b prefix with normal string syntax: b'python'. To construct byte arrays, use the bytearray() function. Note bytes data type represens a group of byte numbers just like an array. Byte type Return a new "bytes" object, which is an immutable sequence of small integers in the range 0 <= x < 256, print as ASCII characters when displayed. bytes is an immutable version of bytearray – it has the same non-mutating methods and the same indexing and slicing behavior.
  • 33. Byte Array The only allowed values for byte data type are 0 to 256. By mistake if we are trying to provide any other values then we will get value error. Once we creates bytes data type value, we cannot change its values,otherwise we will get TypeError. Note:----bytearray is exactly same as bytes data type except that its elements can be modified.
  • 34. Sets A Set is an unordered collection data type that is iterable, mutable, and has no duplicate elements. Python’s set class represents the mathematical notion of a set. The major advantage of using a set, as opposed to a list, is that it has a highly optimized method for checking whether a specific element is contained in the set. • Sets are unordered. • Set elements are unique. Duplicate elements are not allowed. • A set itself may be modified, but the elements contained in the set must be of an immutable type. Properties regarding Sets:---- 1. insertion order is not preserved 2. duplicates are not allowed 3. heterogeneous objects are allowed 4. index concept is not applicable 5. It is mutable collection 6. Growable in nature Frozen Sets Frozen sets are immutable objects that only support methods and operators that produce a result without affecting the frozen set or sets to which they are applied.
  • 35. Mutable and Immutable Data Types In general, data types in Python can be distinguished based on whether objects of the type are mutable or immutable. The content of objects of immutable types cannot be changed after they are created. Only mutable objects support methods that change the object in place, such as reassignment of a sequence slice, which will work for lists, but raise an error for tuples and strings.It is important to understand that variables in Python are really just references to objects in memory Some immutable types Some mutable types •int, float, complex •str •bytes •tuple •frozenset •bool •array •bytearray •list •set •Dict
  • 37. Python Arithmetic Operators Operator + Addition - Subtraction * Multiplication / Divison % Modulus ** Exponent // Floor Divison Note:operator always performs floating point arithmetic. . Hence it will always returns float value. But Floor division (//) can perform both floating point and integral arithmetic. If arguments are int type then result is int type. If atleast one argument is float type then result is float type
  • 38. Python Relational Operators Opera tor Example == If(a==n) then True > If(a>n) then True < If(a<n) then True >= If(a>=n) then True <= If(a<=n) then True != If(a!=n) then True <> If(a<>n) then True Relational operators are symbols that perform operations on data and return a result as true or false depending on the comparison conditions. Thus, they are certain functionalities that do something with your variables. Chaining of relational operators is possible. In the chaining, if all comparisons returns True then only result is True. If atleast one comparison returns False then the result is False
  • 39. Python Assignment Operators Eg: a+=2 ====> a = a+2
  • 40. Ternary operator Python ternary operator is also termed as conditional operator. This is because it can evaluate a statement with a condition being true or false. Python ternary operator • Python ternary operaator was introduced in Python 2.5. • If used properly, ternary operator can reduce code size and increase readability of the code. • There is no special keyword for ternary operator, it’s the way of writing if-else statement that creates a ternary statement or conditional expression.
  • 41. Python Bitwise Operators Operator & (AND) | (OR) ^ (XOR) ~ (Binary Ones Complement) << (Binary Left Shift) >> (Binary Right Shift) We can apply these operators bitwise. These operators are applicable only for int and boolean types. By mistake if we are trying to apply for any other type then we will get Error. Note: The most significant bit acts as sign bit. 0 value represents +ve number where as 1 represents -ve value. positive numbers will be repesented directly in the memory where as -ve numbers will be represented indirectly in 2's complement form.
  • 42. Python Logical Operators Operator and (AND) or (OR) not (NOT) For boolean types behaviour: and ==>If both arguments are True then only result is True or ====>If atleast one arugemnt is True then result is True not ==>complement True and False ==>False True or False ===>True not False ==>True x and y: ==>if x is evaluates to false return x otherwise return y . Note = If first argument is zero then result is zero otherwise result is y. x or y: If x evaluates to True then result is x otherwise result is y not x: If x is evalutates to False then result is True otherwise False
  • 43. Python Membership Operators Operator in not in We can use Membership operators to check whether the given object present in the given collection.(It may be String,List,Set,Tuple or Dict) in -Returns True if the given object present in the specified Collection not in -Retruns True if the given object not present in the specified Collection
  • 44. Python Identity Operators We can use identity operators for address comparison. There are 2 identity operators are available 1. is 2. is not r1 is r2 returns True if both r1 and r2 are pointing to the same object r1 is not r2 returns True if both r1 and r2 are not pointing to the same object We can use is operator for address comparison where as == operator for content comparison.
  • 45. Python Type Casting int(value) float(value) str(value) bin(value) oct(value) hex(value) bool(value) chr(value) ord(value) We can convert one type value to another type. This conversion is called Typecasting or Type coersion. Note: • We can convert from any type to int except complex type. • If we want to convert str type to int type, compulsary str should contain only integral value and should be specified in base-10
  • 46. Python Program to find Type and Address of a Value:
  • 47. Operator Precedence If multiple operators present then which operator will be evaluated first is decided by operator precedence.
  • 48. Math Module in Python A Module is collection of functions, variables and classes etc. Math is a module that contains several functions to perform mathematical operations If we want to use any module in Python, first we have to import that module.
  • 51. Decision Making Decision-making is the anticipation of conditions occurring during the execution of a program and specified actions taken according to the conditions. if if condition : statement or if condition : statement-1 statement-2 statement-3 If condition is true then statements will be executed. if-else: if condition : Action-1 else : Action-2 if condition is true then Action-1 will be executed otherwise Action-2 will be executed. if-elif-else: if condition1: Action-1 elif condition2: Action-2 elif condition3: Action-3 elif condition4: Action-4 else: Default Action Based condition the corresponding action will be executed.
  • 52. Code examples for If, else and elif
  • 53. Nested-If Statement We can use one if or else if statement inside another if or else if statement(s). Else operator for Both condition Elif solve this problem
  • 55. Relational Operator in Decision Making Membership Operator in Decision Making
  • 56. Identical Operator in Decision Making
  • 57. Looping and Iteration A loop statement allows us to execute a statement or group of statements multiple times. The following diagram illustrates a loop statement If we want to execute a group of statements multiple times then we should go for Iterative statements. 1. for loop 2. while loop If we want to execute some action for every element present in some sequence(it may be string or collection)then we should go for for loop. where sequence can be string or any collection. Body will be executed for every element present in the sequence.
  • 60. While Loop A while loop statement in Python programming language repeatedly executes a target statement as long as a given condition is true. If we want to execute a group of statements iteratively until some condition false,then we should go for while loop.
  • 61. For Loop It has the ability to iterate over the items of any sequence, such as a list or a string. Range can accept 3 parameters like [range(1,10,2)] 1 is initial point, 10 is condition and 2 is step Sometimes we can take a loop inside another loop,which are also known as nested loops.
  • 62. Nested Loops Python allow nested looping We can use loops to repeat code execution Repeat code for every item in sequence ==>for loop Repeat code as long as condition is true ==>while loop
  • 63. Transfer Statements --- Break and Continue Break -- We can use break statement inside loops to break loop execution based on some condition. Continue -- We can use continue statement to skip current iteration and continue next iteration.
  • 64. Loops with else block: Insideloopexecution,ifbreakstatementnotexecuted,then onlyelsepartwillbeexecuted.elsemeans loopwithoutbreak Break and Continue
  • 65. Count Number of Digits Using Loop Prime Number Using Nested Loop
  • 66. Find a Number is Palindrome or Not Find a Number is Armstrong or Not
  • 68. Pass Statement pass is a keyword in Python. In our programming syntactically if block is required which won't do anything then we can define that empty block with pass keyword. |- It is an empty statement |- It is null statement |- It won't do anything . Sometimes in the parent class we have to declare a function with empty body and child class responsible to provide proper implementation. Such type of empty body we can define by using pass keyword.
  • 69. String MANIPULATION AND OPERATIONS STRING FUNCTIONS & PROBLEMS The most commonly used object in any project and in any programming language is String only. Hence we should be aware of complete information about String data type. What is a String? Any sequence of characters within either single quotes or double quotes is considered as a String. Comparison of Strings: We can use comparison operators (<,<=,>,>=) and equality operators(==,!=) for strings. Comparison will be performed based on alphabetical order.
  • 70. We can also use triple quotes to use single quotes or double quotes as symbol inside String literal. Eg: S = 'This is ' single quote symbol' ==>invalid S = 'This is ' single quote symbol' ==>valid S = "This is ' single quote symbol"====>valid S = 'This is " double quotes symbol' ==>valid S ='The "Python Notes" by ‘Nishant' is very helpful' ==>invalid S = "The "Python Notes" by ‘Nishant' is very helpful"==>invalid S = 'The "Python Notes" by ‘Nishant' is very helpful' ==>valid S = '''The "Python Notes" by ‘NIshant' is very helpful''' ==>valid How to access characters of a String: We can access characters of a string by using the following ways. 1. By using index 2. By using slice operator Python supports both +ve and -ve index. +ve index means left to right(Forward direction) -ve index means right to left(Backward direction) String and its Functions
  • 71. We can use the following 4 methods For forwarding direction: • find() --Returns index of first occurrence of the given substring. If it is not available then we will get -1. • index() -- index() method is exactly same as find() method except that if the specified substring is not available then we will get ValueError. For backward direction: • rfind() • rindex() Finding Substrings: s=input("Enter main string:") subs=input("Enter sub string:") flag=False pos=-1 n=len(s) while True: pos=s.find(subs,pos+1,n) if pos==-1: break print("Found at position",pos) flag=True if flag==False: print("Not Found")
  • 72. startswith() and endswith() To check type of characters present in a string: Python contains the following methods for this purpose. 1) isalnum(): Returns True if all characters are alphanumeric( a to z , A to Z ,0 to9 ) 2) isalpha(): Returns True if all characters are only alphabet symbols(a to z,A to Z) 3) isdigit(): Returns True if all characters are digits only( 0 to 9) 4) islower(): Returns True if all characters are lower case alphabet symbols 5) isupper(): Returns True if all characters are upper case aplhabet symbols 6) istitle(): Returns True if string is in title case 7) isspace(): Returns True if string contains only spaces
  • 74. strip(), lstrip(), rstrip()min() and max() ,swapcase and split
  • 75. Formatting the Strings: We can format the strings with variable values by using replacement operator {} and format() method.
  • 76. Program to calculate length of string String code Example Program to make a new string from 1st 2 and last 2 characters of a string
  • 77. List LISTS ARE ONE OF THE MOST POWERFUL TOOLS IN PYTHON. THEY ARE JUST LIKE THE ARRAYS DECLARED IN OTHER LANGUAGES. BUT THE MOST POWERFUL THING IS THAT LIST NEED NOT BE ALWAYS HOMOGENOUS.
  • 79. Program to get the largest number from a list. Program to get List from user
  • 80. Program to count the number of strings where the string length is 2 or more and the first and last character are same from a given list of strings. List Code Examples Program to remove duplicate values from list
  • 81. Program to sorting a list Program to convert list to str
  • 82. Tuple A TUPLE IS ANOTHER SEQUENCE DATA TYPE THAT IS SIMILAR TO THE LIST. A TUPLE CONSISTS OF A NUMBER OF VALUES SEPARATED BY COMMAS. UNLIKE LISTS, HOWEVER, TUPLES ARE ENCLOSED WITHIN PARENTHESES.
  • 83. Tuple manipulations and operations. *Tuple is a immutable data type. So it does not support all the operations like list or other muttable data types
  • 84. Tuple manipulations and operations. *Tuple is a immutable data type. So it does not support all the operations like list or other muttable data types
  • 85. Program to unpack a tuple in variables.
  • 86. Program to create a tuple and sort it. tup=()
  • 87. Program to count element based on data type
  • 88. Set A SET CONTAINS AN UNORDERED COLLECTION OF UNIQUE AND IMMUTABLE OBJECTS. THE SET DATA TYPE IS, AS THE NAME IMPLIES, A PYTHON IMPLEMENTATION OF THE SETS AS THEY ARE KNOWN FROM MATHEMATICS.
  • 90. Program to test whether every element in S is in T and every element in T is in S.
  • 91. Program create a Shallow copy of a set
  • 92. Program to create a frozenset
  • 93. Program to find maximum and minimum value of set
  • 94. Dictionary IN PYTHON, THE DICTIONARY IS SIMILAR TO HASH OR MAPS IN OTHER LANGUAGES. IT CONSISTS OF KEY- VALUE PAIRS. THE VALUE CAN BE ACCESSED BY A UNIQUE KEY IN THE DICTIONARY.
  • 96. Program to concatenate dictionaries to form a new one
  • 97. Program to generate and print a dictionary that contains a number (between 1 and n) in the form (x, x*x).
  • 98. Program to map two lists into dictionary
  • 99. Program to sort a dictionary by key
  • 100. Test series  PROGRAM TO COUNT OCCURRENCE OF A CHARACTER IN A STRING  PROGRAM TO COUNT THE NUMBER OF STRINGS WHERE THE STRING LENGTH IS 2 OR MORE AND THE FIRST AND LAST CHARACTER ARE SAME FROM A GIVEN LIST OF STRINGS.  PROGRAM TO COUNT ELEMENT OF DIFFERENT DATA TYPE  PROGRAM TO CREATE A TUPLE AT RUN TIME VIA USER INPUT  PROGRAM TO SHORT A TUPLE OF INTEGER ELEMENT VIA CODE
  • 101. Functions in Python If a group of statements is repeatedly required then it is not recommended to write these statements everytime seperately.We have to define these statements as a single unit and we can call that unit any number of times based on our requirement without rewriting. This unit is nothing but function. The main advantage of functions is code Reusability. Note: In other languages functions are known as methods,procedures,subroutines etc . Python supports 2 types of functions 1. Built in Functions 2. User Defined Functions
  • 102. Functions and its Syntax Note: While creating functions we can use 2 keywords 1. def (mandatory) 2. return (optional) Parameters Parameters are inputs to the function. If a function contains parameters,then at the time of calling,compulsory we should provide values otherwise,otherwise we will get error. Return Statement:- Function can take input values as parameters and executes business logic, and returns output to the caller with return statement.
  • 103. Example for Return statement Returning multiple values from a function: In other languages like C,C++ and Java, function can return atmost one value. But in Python, a function can return any number of values.
  • 104. Arguments and Types of Functions:- 1 Positional Argument These are the arguments passed to function in correct positional order. The number of arguments and position of arguments must be matched. If we change the order then result may be changed. If we change the number of arguments then we will get error. Note  If three actual arguments given and there are only two formal parameter allowed then it show an error
  • 105. Default parameter function Keyword Functions We can pass argument values by keyword i.e by parameter name Here the order of arguments is not important but number of arguments must be matched. We can use both positional and keyword arguments simultaneously. But first we have to take positional arguments and then keyword arguments,otherwise we will get syntax error. Sometimes we can provide default values for our positional arguments. If we are not passing any name then only default value will be considered.
  • 106. Variable length parameter 1. * indicate that a variable can store multiple values 2. ** indicate that a variable can store multiple values with key Note: We can mix variable length arguments with positional arguments. After variable length argument,if we are taking any other arguments then we should provide values as keyword arguments. Sometimes we can pass variable number of arguments to our function,such type of arguments are called variable length arguments.
  • 107. Function and its behaviour d
  • 108. Local and Global Global Variables The variables which are declared outside of function are called global variables.These variables can be accessed in all functions of that module. Local Variables: The variables which are declared inside a function are called local variables. Local variables are available only for the function in which we declared it.i.e from outside of function we cannot access. Global keyword: We use global keyword for the2 purposes: 1. To declare global variable inside function 2. To make global variable available to the function so that we can perform required modifications NoteIf global variable and local variable having the same name then we can access global variable inside a function as follows
  • 109. Function Recurssive Calling A function that calls itself is known as Recursive Function.The main advantages of recursive functions are: 1. We can reduce length of the code and improves readability 2. We can solve complex problems very easily.
  • 110. Functions Anonymous Sometimes we can declare a function without any name,such type of nameless functions are called anonymous functions or lambda functions. The main purpose of anonymous function is just for instant use(i.e for one time usage). lambda Function: -- By using Lambda Functions we can write very concise code so that readability of the program will be improved. Lambda Function internally returns expression value and we are not required to write return statement explicitly. Sometimes we can pass a function as an argument to another function. In such cases lambda functions are best choice. filter() function:-- We can use filter() function to filter values from the given sequence based on some condition. filter(function,sequence) where function argument is responsible to perform conditional check sequence can be list or tuple or string. map() function: --For every element present in the given sequence,apply some functionality and generate new element with the required modification. For this requirement we should go for map() function. Eg: For every element present in the list perform double and generate new list of doubles. reduce() function:-- reduce() function reduces sequence of elements into a single element by applying the specified function. reduce() function present in functools module and hence we should write import statement.
  • 111. Examples with Lambda, Map and Reduce In Python every thing is treated as object. Even functions also internally treated as objects only.
  • 112. Function insidefunction Function Aliasing For the existing function we can give another name, which is nothing but function aliasing. We can declare a function inside another function, such type of functions are called Nested functions.
  • 113. Closure function If a function have an inner function and return it then it is called closure. Note: We can pass function as argument to another function Eg: filter(function,sequence) map(function,sequence) reduce(function,sequence) Square of the elements
  • 114. Multiply of all no. Of tuple Reverse a string Reverse Using Recursion
  • 115. Calculate block & small letters Find unique Elements from List
  • 116. Reverse a number Reverse a number using recursion
  • 117. Function Decorators Decorator is a function which can take a function as argument and extend its functionality and returns modified function with extended functionality. But we want to modify this function to provide different message if name is Sam. We can do this without touching wish() function by using decorator. @ is use to call decorator function
  • 118. More With Decorators Using Decorator without @ With Condition
  • 119. Decorator Chaining We can define multiple decorators for the same function and all these decorators will form Decorator Chaining.
  • 120. Generators Generator is a function which is responsible to generate a sequence of values. We can write generator functions just like ordinary functions, but it uses yield keyword to return values. Genrator with reverse ordering Fibonacci with Python
  • 121. More with Generators Advantages of Generator Functions: 1. When compared with class level iterators, generators are very easy to use 2. Improves memory utilization and performance. 3. Generators are best suitable for reading data from large number of large files 4. Generators work great for web scraping and crawling. Generators vs Normal Collections wrt Memory Utilization: Normal Collection: l=[x*x for x in range(10000000000000000)] print(l[0]) We will get MemoryError in this case because all these values are required to store in the memory. Generators: g=(x*x for x in range(10000000000000000)) print(next(g)) Output: 0 We won't get any MemoryError because the values won't be stored at the beginning
  • 122. Procedural vs Modular Programming PROCEDURAL PROGRAMMING INVOLVES FOLLOWING AN ALGORITHM OR A PROCEDURE TO IMPLEMENT ON YOUR SOFTWARE. THE NUMBER CRUNCHING SOFTWARES ARE GENERALLY BASED ON PROCEDURAL PROGRAMMING. WHEREAS MODULAR PROGRAMMING INVOLVING DIVIDING YOUR OBJECTIVE INTO MODULES AND THEN PIPELINING THE MODULES TO OBTAIN THE DEFINED OUTPUT. MODULES ARE MADE ON THE BASIS OF SIMILARITY BETWEEN THE FUNCTIONS.
  • 123. Modules A module is a file containing Python definitions and statements. A module can define functions, classes and variables. A module can also include runnable code. Grouping related code into a module makes the code easier to understand and use. A group of functions, variables and classes saved to a file, which is nothing but module. Every Python file (.py) acts as a module. Creating any Module step by step: 1 Create a py file with functions and variables. 2 If we want to use members of module in our program then we should import that module. import modulename 3We can access members by using module name. modulename.variable modulename.function() Note: whenever we are using a module in our program, for that module compiled file will be generated and stored in the hard disk permanently. from ... import: We can import particular members of module by using from ... import . The main advantage of this is we can access members directly without using module name. We can import all members of a module as follows from NIshant import *
  • 124. Modules and More Various possibilties of import: • import modulename • import module1,module2,module3 • import module1 as m • import module1 as m1,module2 as m2,module3 • from module import member • from module importmember1,member2,memebr3 • from module import memeber1 as x • from module import * Note  Once we defined as alias name,we should use alias name only and we should not use original name. Reloading a Module: By default module will be loaded only once eventhough we are importing multiple multiple times test module will be loaded only once eventhough we are importing multiple times. The problem in this approach is after loading a module if it is updated outside then updated version of module1 is not available to our program. We can solve this problem by reloading module explicitly based on our requirement. We can reload by using reload() function of imp module. The main advantage of explicit module reloading is we can ensure that updated version is always available to our program. Finding members of module by using dir() function: Python provides inbuilt function dir() to list out all members of current module or a specified module. dir() ===>To list out all members of current module dir(moduleName)==>To list out all members of specified module
  • 125. Built-in Modules There is a wide range available of built-in modules in python. The Special variable __name__: For every Python program , a special variable __name__ will be added internally. This variable stores information regarding whether the program is executed as an individual program or as a module. If the program executed as an individual program then the value of this variable is __main__ If the program executed as a module from some other program then the value of this variable is the name of module where it is defined. Hence by using this __name__ variable we can identify whether the program executed directly or as a module.
  • 126. More on Datetime Modules Name and Main Concept
  • 127. Working with Modules There are so many modules present in python, like math module. Now we discuss random module.
  • 128. Packages and its structure Summary diagram of library,packages,modules which contains functions,classes and variables
  • 129. All underscores in python In python there are underscores act differently so we study all cases related to underscores.
  • 130. OOPs in Python OOPs (Object Oriented Programming) is basic concept of programming language which is widely use in C++, PHP, ASP.net languages. It is Problem Solving Approach which is carried out using Object. This is one of influential development used in computer Programming. Main Purpose of Object Oriented Programming is to simplify a design, programming. Why we use OPPs. In Procedural Programming, Program is divided into small parts called Function. Most of the variables are Global in nature which can be accessed freely from any function and Data can flow from function to function because of which Data is not Secure whereas in OOPs Data cannot Move easily from function to function it can make Data secure using access specifier like Private and Protected because of which Data is Secure as compare to Procedural Programming. Procedural Programming give the importance to procedure instead of Data unlike OOPs give more preference to Data in Place of Procedure. There is one major exception to that statement. If you want to create a customized data type (such as a Complex or Fraction number type), and then use it in multiple programs, OOP can be very helpful. Looked at one way, OOP is actually the creation of customized data types, and therefore, in theory, can be useful even in very simple environments. Generally, though, OOP is most useful in one of two situations: In very complex programs. In applications that interact with a GUI, network, or event-based programming system.
  • 131. Procedural vs OOPs POPs OOPs In POP, program is divided into small parts called functions. In OOP, program is divided into parts called objects. In POP, Importance is not given to data but to functions as well as sequence of actions to be done. In OOP, Importance is given to the data rather than procedures or functions because it works as a real world. POP does not have any access specifier. OOP has access specifiers named Public, Private, Protected, etc. POP does not have any proper way for hiding data so it is less secure. OOP provides Data Hiding so provides more security. In POP, Overloading is not possible. In OOP, overloading is possible in the form of Function Overloading and Operator Overloading. What is an Object? An object is nothing but a self-contained component which consists of methods and properties to make a particular type of data useful. An object is a real world entity. Pysical existence of a class is nothing but object. We can create any number of objects for a class. From a programming point of view, an object can be a data structure, a variable or a function. It has a memory location allocated. The object is designed as class hierarchies. An object contain two things attributes(data, property) and behavior(task). Example:= If Human is an object then Attributes are like Name,height,weight,hobbies etc and Behaviours are walk,talk,eat,sleep etc. So as an object I know something and on the basis of know something then I do something.
  • 132. OOPs Concept What is Class? A class is a blueprint or prototype that defines the variables and the methods (functions) common to all objects of a certain kind. In Python every thing is an object. To create objects we required some Model or Plan or Blue print, which is nothing but class. We can write a class to represent properties (attributes) and actions (behaviour) of object. Properties can be represented by variables. Actions can be represented by Methods. Hence class contains both variables and methods. Object is a instance of class. 1. Instance Methods 2. Class Methods 3. Static Methods
  • 133. 28/07/2022 Python ---Constructor A constructor is a special type of method (function) which is used to initialize the instance members of the class. 1) Constructor is used for Initializing the values to the data members of the Class. 1) Constructor is that whose name is same as name of class. 2) Constructor gets Automatically called when an object of class is created. 3) Constructors never have a Return Type even void. 4) Constructor are of Default(Non Parameterized), Parameterized and Copy Constructors. 2) Constructor is optional and if we are not providing any constructor then python will provide default constructor. 3) Constructor definition is executed when we create the object of this class. Constructors also verify that there are enough resources for the object to perform any start-up task.  Constructor is a special method in python.  The name of the constructor should be __init__(self)  Constructor will be executed automatically at the time of object creation.  The main purpose of constructor is to declare and initialize instance variables.  Per object constructor will be exeucted only once.  Constructor can take atleast one argument(atleast self) Heap Memory All objects Address In python, the method __init__ simulates the constructor of the class. This method is called when the class is instantiated. We can pass any number of arguments at the time of creating the class object, depending upon __init__ definition. It is mostly used to initialize the class attributes. Every class must have a constructor, even if it simply relies on the default constructor.
  • 134. Along with the other attributes, a python class also contains some built-in class attributes which provide information about the class. Inbuilt Class Attrributes and Functions SN Attribute Description 1 __dict__ It provides the dictionary containing the information about the class namespace. 2 __doc__ It contains a string which has the class documentation 3 __name__ It is used to access the class name. 4 __module__ It is used to access the module in which, this class is defined. 5 __bases__ It contains a tuple including all base classes. Inbuilt class functions--The in-built functions defined in the class are described in the following table SN Function Description 1 getattr(obj,name,d efault) It is used to access the attribute of the object. 2 setattr(obj, name,value) It is used to set a particular value to the specific attribute of an object. 3 delattr(obj, name) It is used to delete a specific attribute. 4 hasattr(obj, name) It returns true if the object contains some specific attribute
  • 135. Constructor vs Method Types of Variables: Inside Python class 3 types of variables are allowed. 1. Instance Variables (Object Level Variables) 2. Static Variables (Class Level Variables) 3. Local variables (Method Level Variables) 1. Instance Variables: If the value of a variable is varied from object to object, then such type of variables are called instance variables. For every object a separate copy of instance variables will be created. Where we can declare Instance variables: 1. Inside Constructor by using self variable 2. Inside Instance Method by using self variable 3. Outside of the class by using object reference variable Class Variables
  • 136. 28/07/2022 Instance Variables(object level variable): - 1. Inside Constructor by using self variable: We can declare instance variables inside a constructor by using self keyword. Once we creates object, automatically these variables will be added to the object. 2. Inside Instance Method by using self variable: We can also declare instance variables inside instance method by using self variable. If any instance variable declared inside instance method, that instance variable will be added once we call taht method. 3. Outside of the class by using object reference variable: We can also add instance variables outside of a class to a particular object. How to access Instance variables: We can access instance variables with in the class by using self variable and outside of the class by using object reference. How to delete instance variable from the object: 1. Within a class we can delete instance variable as follows del self.variableName 2. From outside of class we can delete instance variables as follows del objectreference.variableName If we change the values of instance variables of one object then those changes won't be reflected to the remaining objects, because for every object we are separate copy of instance variables are available.
  • 138. Static Variable(Class Level Variable) If the value of a variable is not varied from object to object, such type of variables we have to declare with in the class directly but outside of methods. Such type of variables are called Static variables. For total class only one copy of static variable will be created and shared by all objects of that class. We can access static variables either by class name or by object reference. But recommended to use class name. If we change the value of static variable by using either self or object reference variable,then the value of static variable won't be changed,just a new instance variable with thatname will be added to that particular object.
  • 139. Local Variable • Sometimes to meet temporary requirements of programmer,we can declare variables inside a method directly,such type of variables are called local variable or temporary variables. • Local variables will be created at the time of method execution and destroyed once method completes. • Local variables of a method cannot be accessed from outside of method.
  • 140. Method and its working Types of Methods: Inside Python class 3 types of methods are allowed . Instance Methods , Class Methods and Static Methods 1. Instance Methods: Inside method implementation if we are using instance variables then such type of methods are called instance methods. Inside instance method declaration,we have to pass self variable. 2. Class Methods: Inside method implementation if we are using only class variables (static variables), then such type of methods we should declare as class method. We can declare class method explicitly by using @classmethod decorator. For class method we should provide cls variable at the time of declaration. We can call classmethod by using classname or object reference variable.
  • 141. ClassMethod--The @classmethod decorator, is a builtin function decorator that is an expression that gets evaluated after your function is defined. The result of that evaluation shadows your function definition. A class method receives the class as implicit first argument, just like an instance method receives the instance. A class method is a method which is bound to the class and not the object of the class. They have the access to the state of the class as it takes a class parameter that points to the class and not the object instance. It can modify a class state that would apply across all the instances of the class. For example it can modify a class variable that will be applicable to all the instances. Static Method-- A static method does not receive an implicit first argument. A static method is also a method which is bound to the class and not the object of the class. A static method can’t access or modify class state. It is present in a class because it makes sense for the method to be present in class. Class Method Vs Static Method A class method takes cls as first parameter while a static method needs no specific parameters. A class method can access or modify class state while a static method can’t access or modify it. In general, static methods know nothing about class state. They are utility type methods that take some parameters and work upon those parameters. On the other hand class methods must have class as parameter. We use @classmethod decorator in python to create a class method and we use @staticmethod decorator to create a static method in python. Class Method and Static Method
  • 142. Static Method In general these methods are general utility methods. Inside these methods we won't use any instance or class variables. Here we won't provide self or cls arguments at the time of declaration. We can declare static method explicitly by using @staticmethod decorator. We can access static methods by using classname or object reference. Note: In general we can use only instance and static methods.Inside static method we can access • class level variables by using class name. • class methods are most rarely used methods in python.
  • 143. Inner Class or Nested class
  • 144. OOPs Concepts --- Polymorphism Poly means many. Morphs means forms. Polymorphism means 'Many Forms'. Polymorphism means same name with different forms(behaviour). E.g. Mobile. Now there are various division for Polymorphism. Polymorphism: • Overloading • Operator Overloading. • Method Overloading. • Constructor Overloading. • Overriding • Method Overriding. • Constructor Overriding.
  • 145. Overloading and its Types In Overloading, there is a method, operator and constructor with same name but act differently in multiple situation. Example:-- If Bank is a class, deposit and withdrawal is a entity so there are multiple ways to perform it like cash, Check and DD etc. So, In simple way same name with different arguments. 1. Operator Overloading: In Java It never exist. 2. In Python, we achieve Operator Overloading easily.e.g. 6+3, “a”+”b”, 9*2 and “n”*23. 3. It always achieve by using magic(Dunder ) function. And every operator in python has magic method. And return type of every magic method is output.
  • 146. Method and Constructure Overloading(Early /Compile Time Binding) If 2 methods having same name but different type of arguments then those methods are said to be overloaded methods. Note: In python, there is no need to define type for anyone explicitly so how overloading is not available in python. Basically, in Python overloading concept is not required. So, we not worry about different types of argments we worry about ,to pass number of arguments. So for this we have, Default Arguments and Variable length arguments. We also perform overloading with constructors. Method Overriding(Late/RunTime Binding): What ever members available in the parent class are by default available to the child class through inheritance. If the child class not satisfied with parent class implementation then child class is allowed to redefine that method in the child class based on its requirement. This concept is called overriding. Overriding concept applicable for both methods and constructors. Method overriding is a concept of object oriented programming that allows us to change the implementation of a function in the child class that is defined in the parent class. It is the ability of a child class to change the implementation of any method which is already provided by one of its parent class(ancestors). Following conditions must be met for overriding a function: Inheritance should be there. Function overriding cannot be done within a class. We need to derive a child class from a parent class. The function that is redefined in the child class should have the same signature as in the parent class i.e. same number of parameters.
  • 147. What is inheritance? Inheritance is used to extend of parent class to its child class. Python can support single level, multi level, hierarchal and multiple inheritance.
  • 148. Inheritance in Python Single Level Inheritance • Single Parent and Single child Multi level Inheritance • One parent but multiple child at diff. level. Heirarical Inheritance • One Parent but multiple child at same level. Multiple Inheritance • MultipleParents but one single child. At a fairly abstract level, super() provides the access to those methods of the super-class (parent class) which have been overridden in a sub-class (child class) that inherits from it. With the help of super(), from child class we can call parent class members. The main motive of super is code reusability. Notes: From child class, by using super we cannot call parent class instance variable we should use self only. From child class by using super(), we can call parent class static variable. Hybrid Inheritance --- (Single + Multiple + Multilevel+Heirarical) So for this there is a concept of MRO(Method Resolution Order) • If we have Parent class and child class with same method name. • So, When we call object then always first method excecute which present in child and if not present in child then go to parent class. • For A-- (A- obj) • For B-- (B-A-obj) • For C-- (C-A-obj) • For D– (D-C-B-A-obj)
  • 149. C3 Algo -- MRO obj B A C X Y P mro(P) = P,X,Y,C,A,B,O So,here we see that mro for P not actually right.Due to hybrid Inheritance and there is multiple level present so here for Calculating MRO we use C3 Algorithm. Mro(P) = [class(P) + merge(mro(Parents) at samelevel),parentlist] Mro(P) = P+Merge(mro(x),mro(y),mro(c),XYC). 1 E.g. Mro(P) = P+Merge(XABo,YBCo,Co,XYC).  step2. Now here, first level is done now move toward next level. For this we have to know about head and tail. e.g.– If we have a list like ABCDEF so in this. Head --- A Tail --- BCDEF For next level always remember one statement. Mro(P) = P+X+Merge(ABo,YBCo,Co,YC).  step3. remove X Mro(P) = P+X+A+Merge(Bo,YBCo,Co,YC).  step4. remove A Now For B, So B is present in head and tail both then leave that list. Mro(P) = P+X+A+Y+Merge(Bo,BCo,Co,C).  step5. remove Y Mro(P) = P+X+A+Y+B+Merge(o,Co,Co,C).  step6. remove B Mro(P) = P+X+A+Y+B+C+Merge(o,o,o).  step7 . remove C
  • 150. Program to convert integer to roman
  • 151. Program to convert roman to integer
  • 152. Program to make possible unique subset
  • 153. Program to find a pair of elements (indices of the two numbers) from a given array whose sum equals a specific target number.
  • 154. Python program to find the three elements that sum to zero from a set (array) of n real numbers.
  • 155. Program to implement pow(x, n).
  • 157. Passing values to parent constructor using base class name
  • 158. File Handling Python too supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files.Python treats file differently as text or binary and this is important. Each line of code includes a sequence of characters and they form text file. As the part of programming requirement, we have to store our data permanently for future purpose. For this requirement we should go for files. Files are very common permanent storage areas to store our data. And for Temporary storage we use List,Tuple and Dictionary etc. (Heap) So Permanent storage are Files and Database.(Memory). Types of Files: There are 2 types of files 1. Text Files: Usually we can use text files to store character data eg: abc.txt 2. Binary Files: Usually we can use binary files to store binary data like images,video files, audio files etc.
  • 159. 28/07/2022 File Handling Opening a File: Before performing any operation (like read or write) on the file,first we have to open that file.For this we should use Python's inbuilt function open() .But at the time of open, we have to specify mode,which represents the purpose of opening file. e.g. f = open(filename, mode) The allowed modes in Python are 1. r open an existing file for read operation. The file pointer is positioned at the beginning of the file.If the specified file does not exist then we will get FileNotFoundError.This is default mode. 2. w open an existing file for write operation. If the file already contains some data then it will be overridden. If the specified file is not already avaialble then this mode will create that file. 3. a  open an existing file for append operation. It won't override existing data.If the specified file is not already avaialble then this mode will create a new file. 4. r+  To read and write data into the file. The previous data in the file will not be deleted.The file pointer is placed at the beginning of the file. 5. w+  To write and read data. It will override existing data. 6. a+ To append and read data from the file.It wont override existing data. 7. x  To open a file in exclusive creation mode for write operation. If the file already exists then we will get FileExistsError. Note: All the above modes are applicable for text files. If the above modes suffixed with 'b' then these represents for binary files. Eg: rb,wb,ab,r+b,w+b,a+b,xb
  • 160. 28/07/2022 File Handling Closing a File: After completing our operations on the file,it is highly recommended to close the file. For this we have to use close() function. f.close() Various properties of File Object: Once we opend a file and we got file object,we can get various details related to that file by using its properties. name Name of opened file mode Mode in which the file is opened closed  Returns boolean value indicates that file is closed or not readable() Returns boolean value indicates that whether file is readable or not writable()Returns boolean value indicates that whether file is writable or not. Writing data to text files: We can write character data to the text files by using the following 2 methods. • write(str) -- while writing data by using write() methods, compulsory we have to provide line seperator(n),otherwise total data should be written to a single line. • writelines(list of lines) Reading Character Data from text files: We can read character data from text file by using the following read methods. read() To read total data from the file. read(n)To read 'n' characters from the file readline() To read only one line readlines()To read all lines into a list The with statement: The with statement can be used while opening a file.We can use this to group file operation statements within a block. The advantage of with statement is it will take care closing of file,after completing all operations automatically even in the case of exceptions also, and we are not required to close explicitly.
  • 161. 28/07/2022 File Handling Operations tell() We can use tell() method to return current position of the cursor(file pointer) from beginning of the file. The position(index) of first character in files is zero just like string index. Seek():We can use seek() method to move cursor(file pointer) to specified location. E.g.f.seek(offset, fromwhere) offset represents the number of positions . The allowed values for second attribute(from where) are 0---->From beginning of file(default value) 1---->From current position 2--->From end of the file # Note: Python 2 supports all 3 values but Python 3 supports only zero. How to check a particular file exists or not? We can use os library to get information about files in our computer. os module has path sub module,which contains isFile() function to check whether a particular file exists or not? os.path.isfile(fname). Handling csv files: CSV==>Comma seperated values As the part of programming,it is very common requirement to write and read data wrt csv files. Python provides csv module to handle csv files. Zipping and Unzipping Files: It is very common requirement to zip and unzip files. The main advantages are: 1. To improve memory utilization 2. We can reduce transport time 3. We can improve performance. To perform zip and unzip operations, Python contains one in-bulit module zip file. This module contains a class : ZipFile OS Module for File Handling.
  • 163. FileHandling Directory Working It is very common requirement to perform operations for directories like 1. To know current working directory. 2. To create a new directory. 3. To remove an existing directory. 4. To rename a directory. 5. To list contents of the directory etc. os.walk(path,topdown=True,onerror=None,followlinks=False) It returns an Iterator object whose contents can be displayed by using for loop path-->Directory path. cwd means . topdown=True --->Travel from top to bottom onerror=None --->on error detected which function has to execute. followlinks=True -->To visit directories pointed by symbolic links. Note: To display contents of particular directory,we have to provide that directory name as argument to walk() function. os.walk("directoryname") What is the difference between listdir() and walk() functions? In the case of listdir(), we will get contents of specified directory but not sub directory contents. But in the case of walk() function we will get contents of specified directory and its sub directories also. Running Other programs from Python program: os module contains system() function to run programs and commands. It is exactly same as system() function in C language. os.system("commad string") The argument is any command which is executing from DOS. OS To perform these operations,Python provides inbuilt module os,which contains several functions to perform directory related operations. The above program display contents of current working directory but not contents of sub directories. If we want the contents of a directory including sub directories then we should go for walk() function.
  • 164. Program to create or open a file. OS Stats
  • 165. Pickling and Unpickling the object Sometimes we have to write total state of object to the file and we have to read total object from the file. The process of writing state of object to the file is called pickling and the process of reading state of an object from the file is called unpickling. We can implement pickling and unpickling by using pickle module of Python. pickle module contains dump() function to perform pickling. pickle.dump(object,file) pickle module contains load() function to perform unpickling obj=pickle.load(file)
  • 166. Program to write a file
  • 167. Program to write multiple lines in a file
  • 168. Program to read a file
  • 169. File seeking program to point a cusrsor on a specific charactor
  • 170. Program to remove ‘n’ charactor
  • 171. Program to copy content of a file in another file
  • 172. Task: Write a program to create your profile in a text file Your name, address, contact no, dob, father’s name, mother’s name, course, branch, year, semester  All information should be input at runtime by user  All information should be in well format  All information should be display immediately after writing  File name should be entered by user at runtime  File extension is your own choice
  • 173. Program to delete a file
  • 174. Program to rename a file
  • 176. Exceptions Handling IN ANY PROGRAMMING LANGUAGE THERE ARE 2 TYPES OF ERRORS ARE POSS IBLE. 1. SYNTAX ERRORS THE ERRORS WHICH OCCURS BECAUSE OF INVALID SYNTAX ARE CALLED SYNTAX ERRORS 2. RUNTIME ERRORS  ALSO KNOWN AS EXCEPTIONS. WHILE EXECUTING THE PROGRAM IF SOMETHING GOES WRONG BECAUSE OF END USER INPUT OR PROGRAMMING LO GIC OR MEMORY PROBLEMS ETC THEN WE WILL GET RUNTIME ERRORS. EG: PRINT(10/0) ==>ZERODIVISIONERROR : DIVISION BY ZERO. N O T E : E X C E P T IO N H A N D LIN G C O N C E P T A P P LIC A B LE F O R R U N T IM E E R R O R S B U T N O T F O R S Y N TA X E R R O R S WHAT IS EXCEPTION? AN UNWANTED AND UNEXPECTED EVENT THAT DISTURBS NORMAL FLOW OF PR OGRAM IS CALLED EXCEPTION. THE MAIN OBJECTIVE OF EXCEPTION HANDLING IS GRACEFUL TERMINATIO N OF THE PROGRAM. EXCEPTION HANDLING DOES NOT MEAN REPAIRING EXCEPTION. WE HAVE TO DEFINE ALTERNATIVE WAY TO CONTINUE REST OF THE PROGRAM NORMALLY.
  • 177. Default Exception Handing in Python: Every exception in Python is an object. For every exception type the corresponding classes are available. Whevever an exception occurs PVM will create the corresponding exception object and will check for handling code. If handling code is not available then Python interpreter terminates the program abnormally and prints corresponding exception information to the console. The rest of the program won't be executed. Every Exception in Python is a class. All exception classes are child classes of BaseException.i.e every exception class extends BaseException either directly or indirectly. Hence BaseException acts as root for Python Exception Hierarchy. Customized Exception Handling by using try-except: It is highly recommended to handle exceptions. The code which may raise exception is called risky code and we have to take risky code inside try block. The corresponding handling code we have to take inside except block. 1. within the try block if anywhere exception raised then rest of the try block wont be executed eventhough we handled that exception. Hence we have to take only risky code inside try block and length of the try block should be as less as possible. 2. In addition to try block,there may be a chance of raising exceptions inside except and finally blocks also. 3. If any statement which is not part of try block raises an exception then it is always abnormal termination.
  • 179. Control Flow of try and execpt
  • 180. Try with multiple catch The way of handling exception is varied from exception to exception. Hence for every exception type a seperate except block we have to provide. i.e try with multiple except blocks is possible and recommended to use. If try with multiple except blocks available then based on raised exception the corresponding except block will be executed. If try with multiple except blocks available then the order of these except blocks is important .Python interpreter will always consider from top to bottom until matched except block identified. Single except block that can handle multiple exceptions: We can write a single except block that can handle multiple different types of exceptions. except (Exception1,Exception2,exception3,..): or except (Exception1,Exception2,exception3,..) as msg : Parenthesis are mandatory and this group of exceptions internally considered as tuple. Default except block: We can use default except block to handle any type of exceptions. In default except block generally we can print normal error messages. ***Note: If try with multiple except blocks available then default except block should be last,otherwise we will get SyntaxError.
  • 181. Finally block 1. It is not recommended to maintain clean up code(Resource Deallocating Code or Resource Releasing code) inside try block because there is no guarentee for the execution of every statement inside try block always. 2. It is not recommended to maintain clean up code inside except block, because if there is no exception then except block won't be executed. Hence we required some place to maintain clean up code which should be executed always irrespective of whether exception raised or not raised and whether exception handled or not handled. Such type of best place is nothing but finally block. The speciality of finally block is it will be executed always whether exception raised or not raised and whether exception handled or not handled. *** Note: There is only one situation where finally block won't be executed ie whenever we are using os._exit(0) function. Whenever we are using os._exit(0) function then Python Virtual Machine itself will be shutdown.In this particular case finally won't be executed.
  • 183. else block with try-except-finally: We can use else block with try-except-finally blocks. else block will be executed if and only if there are no exceptions inside try block. Without catch block else not working PVM not consider it.
  • 186. User defined Exception Types of Exceptions: 1. Predefined Exceptions 2. User Definded Exceptions 1. Predefined Exceptions: Also known as in-built exceptions The exceptions which are raised automatically by Python virtual machine whenver a particular event occurs, are called pre defined exceptions. Eg 1: Whenev we are trying to perform Division by zero, automatically Python will raise ZeroDivisionError. print(10/0) Eg 2: Whenever we are trying to convert input value to int type and if input value is not int value then Python will raise ValueError automatically. x=int("ten")===>ValueError 2. User Defined Exceptions: Also known as Customized Exceptions or Programatic Exceptions Some time we have to define and raise exceptions explicitly to indicate that something goes wrong ,such type of exceptions are called User Defined Exceptio or Customized Exceptions Programmer is responsible to define these exceptions and Python not having any idea about these. Hence we have to raise explicitly based on our requiremen using "raise" keyword. Eg: InSufficientFundsException , InvalidInputException ,TooYoungException ,TooOldException. How to Define and Raise Customized Exceptions: Every exception in Python is a class that extends Exception class either directly or indirectly. Syntax: class classname(predefined exception class name): def __init__(self,arg): self.msg=arg
  • 188. An overview to Protocols and Ports HTTP, SMTP, IMAP, FTP are high level protocols which are working on TCP and UDP TCP and UDP are low level protocols UDP use in video streaming, VOIP and Online games HTTP Web Server SMTP & IMAP Email Server FTP File Server VOIP - Voice over internet protocol UDP – User datagram protocol IMAP – Internet message access protocol
  • 193. Tkinter Widgets Widgets Description Button The Button widget is used to display buttons in your application Canvas The Canvas widget is used to draw shapes, such as lines, ovals, polygons and rectangles, in your application. Checkbutton The Checkbutton widget is used to display a number of options as checkboxes. The user can select multiple options at a time. Entry The Entry widget is used to display a single-line text field for accepting values from a user. Frame The Frame widget is used as a container widget to organize other widgets. Label The Label widget is used to provide a single-line caption for other widgets. It can also contain images. Listbox The Listbox widget is used to provide a list of options to a user. Menu The Menu widget is used to provide various commands to a user. These commands are contained inside Menubutton.
  • 194. Tkinter Widgets Widgets Description Message The Message widget is used to display multiline text fields for accepting values from a user. Radiobutton The Radiobutton widget is used to display a number of options as radio buttons. Text The Text widget is used to display text in multiple lines. tkMessageBox This module is used to display message boxes in your applications.
  • 196. Creating a tkinter entry with label widget
  • 197. Task- Creating a login screen using tkinter
  • 198. Creating radio button and check boxes
  • 199. Creating a Layout Using Grid
  • 200. Display values from Radio Button and Check box
  • 203. Display values from Entry box on labels
  • 208. Getting Values from Option Menu
  • 211. Creating Button with Image + Text
  • 212. Creating Listbox With Scroll Bar
  • 214. Creating a text Message
  • 219. Creating Shapes on Tkinter
  • 220. GUI calculator in python
  • 221. GUI calculator in python
  • 222. GUI calculator in python
  • 223. Database in Python PLAY WITH SQLITE DATABASE  CREATING & CONNECTING DB  CREATING TABLES  INSERTION, DELETION, UPDATION AND FETCHING RECORD.
  • 224. Database Connectivity Storage Areas As the Part of our Applications, we required to store our Data like Customers Information, Billing Information, Calls Information etc.To store this Data, we required Storage Areas. There are 2 types of Storage Areas. 1) Temporary Storage Areas 2) Permanent Storage Areas 1.Temporary Storage Areas: These are the Memory Areas where Data will be stored temporarily. Eg: Python objects like List, Tuple, Dictionary. Once Python program completes its execution then these objects will be destroyed automatically and data will be lost. 2. 2.Permanent Storage Areas: Also known as Persistent Storage Areas. Here we can store Data permanently. Eg: File Systems, Databases, Data warehouses, Big Data Technologies etc File Systems: File Systems can be provided by Local operating System. File Systems are best suitable to store very less Amount of Information. Limitations: 1) We cannot store huge Amount of Information. 2) There is no Query Language support and hence operations will become very complex. 3) There is no Security for Data. 4) There is no Mechanism to prevent duplicate Data. Hence there may be a chance of Data Inconsistency Problems. To overcome the above Problems of File Systems, we should go for Databases.
  • 225. Python DataBase Databases: 1) We can store Huge Amount of Information in the Databases. 2) Query Language Support is available for every Database and hence we can perform Database Operations very easily. 3) To access Data present in the Database, compulsory username and pwd must be required. Hence Data is secured. 4) Inside Database Data will be stored in the form of Tables. While developing Database Table Schemas, Database Admin follow various Normalization Techniques and can implement various Constraints like Unique Key Constrains, Primary Key Constraints etc which prevent Data Duplication. Hence there is no chance of Data Inconsistency Problems. Limitations of Databases: 1) Database cannot hold very Huge Amount of Information like Terabytes of Data. 2) Database can provide support only for Structured Data (Tabular Data OR Relational Data) and cannot provide support for Semi Structured Data (like XML Files) and Unstructured Data (like Video Files, Audio Files, Images etc) To overcome these Problems we should go for more Advanced Storage Areas like Big Data Technologies, Data warehouses etc. Note: The following is the list of all important methods which can be used for python database programming. connect() cursor() execute() executescript() executemany() commit() rollback() fetchone() fetchall() fetchmany(n) fetch() close()
  • 230. Update and delete record from table Output will appear after executing fetch command
  • 232. What is a Thread? A thread is an entity within a process that can be scheduled for execution. Also, it is the smallest unit of processing that can be performed in an OS. It is also consider as independent part of a process. Also called flow of executuion. A thread contains all this information in a Thread Control Block (TCB): Threading and its Concept What is MultiThreading? It is the concept, which is used by operating system to perform the Multi Tasking within the system. Multi Tasking means executing several task simultaneously. In this, there are two types of Multi Tasking present. 1. Process based Multi Tasking. 2. Thread based Multi Tasking. Multithreading is defined as the ability of a processor to execute multiple threads concurrently. Example related to multi tasking like at same time students concentrate on lectures and also operates its mobile and also look here and there.
  • 233. Types of Multi Threading 1. Process based Multi Tasking: Executing several tasks simmultaneously where each task is a seperate independent process is called process based multi tasking. In this, all tasks entirely differen from each other means there is no relation between them. It is very much suitable as OS level. And also appear for application level sometimes. Eg: while typing python program in the editor we can listen mp3 audio songs from the same system. At the same time we can download a file from the internet. All these taks are executing simultaneously and independent of each other. Hence it is process based multi tasking. 2. Thread based MultiTasking: Executing several tasks simultaneously where each task is a seperate independent part of the same program, is called Thread based multi tasking, and each independent part is called a Thread. In this, every part is different but belong towards one program. Note: Whether it is process based or thread based, the main advantage of multi tasking is to improve performance of the system by reducing response time. The main important application areas of multi threading are: 1. To implement Multimedia graphics , 2. To develop animations ,3. To develop games, 4. To develop web and appln servers. Everytime we try to execute bulk instructions simultaneously,not one by one. Python provides one inbuilt module "threading" to provide support for developing threads. Hence developing multi threaded Programs is very easy in python. Every Python Program by default contains one thread which is nothing but MainThread.
  • 234. Thread Creation The ways of Creating Thread in Python: We can create a thread in Python by using 3 ways : 1. Creating a Thread without using any class(Functional way). 2. Creating a Thread by extending Thread class(OOP). 3. Creating a Thread without extending Thread class(OOP). Note:Thread is a pre defined class present in threading module which can be used to create our own Threads. Main thread is responsible to create and start child thread. Once child started then both act independently. Setting and Getting Name of a Thread: Every thread in python has name. It may be default name generated by Python or Customized Name provided by programmer. We can get and set name of thread by using the following Thread class methods. t.getName() ,t.name----------Returns Name of Thread. t.setName(newName) ,t.name = “xyz”-- To set our own name. Note: Every Thread has implicit variable "name" to represent name of Thread. • Thread Identification Number(ident): For every thread internally a unique identification number is available. • active_count(): This function returns the number of active threads currently running. • enumerate() function: This function returns a list of all active threads currently running. • isAlive(): method checks whether a thread is still executing or not. • join() method: If a thread wants to wait until completing some other thread then we should go for join() method.e..gparty
  • 235. 28/07/2022 Multi ThreadingThread Control Block (TCB) Thread Identifier: Unique id (TID) is assigned to every new thread. Stack pointer: Points to thread’s stack in the process. Stack contains the local variables under thread’s scope. Program counter: A register which stores the address of the instruction currently being executed by thread. Thread state: can be running, ready, waiting, start or done. Thread’s register set: registers assigned to thread for computations. Parent process Pointer: A pointer to the Process control block (PCB) of the process that the thread lives on. Daemon Threads: The threads which are running in the background are called Daemon Threads. The main objective of Daemon Threads is to provide support for Non Daemon Threads( like main thread).e.g. Garbage Collection. Whenever Main Thread runs with low memory, immediately PVM runs Garbage Collector to destroy useless objects and to provide free memory,so that Main Thread can continue its execution without having any memory problems. We can check whether thread is Daemon or not by using t.isDaemon() method of Thread class or by using daemon property. Nature of Daemon Thread--We can change Daemon nature by using setDaemon() method of Thread class. t.setDaemon(True) But we can use this method before starting of Thread.i.e once thread started,we cannot change its Daemon nature,otherwise we will get RuntimeException:cannot set daemon status of active thread. Default Nature: By default Main Thread is always non-daemon.But for the remaining threads Daemon nature will be inherited from parent to child.i.e if the Parent Thread is Daemon then child thread is also Daemon and if the Parent Thread is Non Daemon then ChildThread is also Non Daemon. But if we want to make child opposite to parent it possible
  • 236. 28/07/2022 Synchronization with Threads If multiple threads are executing simultaneously then there may be a chance of data inconsistency problems. Thread synchronization is defined as a mechanism which ensures that two or more concurrent threads do not simultaneously execute some particular program segment known as critical section. Critical section refers to the parts of the program where the shared resource is accessed. Synchronization means at a time only one Thread The main application areas of synchronization are 1. Online Reservation system 2. Funds Transfer from joint accounts etc In Python, we can implement synchronization by using the following 1. Lock 2. RLock 3. Semaphore Concurrent accesses to shared resource can lead to race condition. A race condition occurs when two or more threads can access shared data and they try to change it at the same time. As a result, the values of variables may be unpredictable and vary depending on the timings of context switches of the processes. Synchronization By using Lock concept: Locks are the most fundamental synchronization mechanism provided by threading module. We can create Lock object as follows l=Lock() The Lock object can be hold by only one thread at a time.If any other thread required the same lock then it will wait until thread releases lock.(similar to common wash rooms,public telephone booth etc) A Thread can acquire the lock by using acquire() method. l.acquire() and using release() method. l.release() Note: To call release() method compulsory thread should be owner of that lock.i.e thread should has the lock already,otherwise we will get Runtime Exception saying .
  • 237. 28/07/2022 Synchronization with threads Problem with Simple Lock: The standard Lock object does not care which thread is currently holding that lock.If the lock is held and any thread attempts to acquire lock, then it will be blocked,even the same thread is already holding that lock. If the Thread calls recursive functions or nested access to resources,then the thread may trying to acquire the same lock again and again,which may block our thread. RLOCK To overcome this problem, we should go for RLock(Reentrant Lock). Reentrant means the thread can acquire the same lock again and again.If the lock is held by other threads then only the thread will be blocked. Reentrant facility is available only for owner thread but not for other threads. This RLock keeps track of recursion level and hence for every acquire() call compulsory release() call should be available. i.e the number of acquire() calls and release() calls should be matched then only lock will be released. 1. Only owner thread can acquire the lock multiple times 2. The number of acquire() calls and release() calls should be matched. Difference between Lock and RLock Lock: 1. Lock object can be acquired by only one thread at a time.Even owner thread also cannot acquire multiple times. 2. Not suitable to execute recursive functions and nested access calls 3. In this case Lock object will takes care only Locked or unlocked and it never takes care about owner thread and recursion level. RLock: 1. RLock object can be acquired by only one thread at a time, but owner thread can acquire same lock object multiple times. 2. Best suitable to execute recursive functions and nested access calls 3. In this case RLock object will takes care whether Locked or unlocked and owner thread information, recursiion level.
  • 238. Synchronization with Lock Locks are the most fundamental synchronization mechanism provided by threading module. We can create Lock object as follows l=Lock() The Lock object can be hold by only one thread at a time.If any other thread required the same lock then it will wait until thread releases lock.(e.g==public property) A Thread can acquire the lock by using acquire() method.==== l.acquire() A Thread can release the lock by using release() method. ==== l.release() Note: To call release() method compulsory thread should be owner of that lock.i.e thread should has the lock already,otherwise we will get Runtime Exception saying RuntimeError: release unlocked lock
  • 243. Character classes: We can use character classes to search a group of characters 1. [abc]===>Either a or b or c 2. [^abc] ===>Except a and b and c 3. [a-z]==>Any Lower case alphabet symbol 4. [A-Z]===>Any upper case alphabet symbol 5. [a-zA-Z]==>Any alphabet symbol 6. [0-9] Any digit from 0 to 9 7. [a-zA-Z0-9]==>Any alphanumeric character 8. [^a-zA-Z0-9]==>Except alphanumeric characters(Special Characters) Regular Expression Pre defined Character classes: • s --Space character • S --Any character except space character • d --Any digit from 0 to 9 • D --Any character except digit • w --Any word character [a-zA-Z0-9] • W --Any character except word character (Special Characters) [^a-zA-Z0-9]. • “.” --Any character including special characters Qunatifiers: Means Quantity We can use quantifiers to specify the number of occurrences to match. a Exactly one 'a' a+ Atleast one 'a' a* Any number of a's including zero number a? Atmost one 'a' ie either zero number or one no. a{m} Exactly m number of a's a{m,n} Min m number of a's and Max n no. of a's ^x It will check whether target string starts with x or not x$ It will check whether target string ends with x or not
  • 244. 28/07/2022 Regular Expression-Introduction Regular expression is a sequence of character(s) mainly used to find and replace patterns in a string or file. Regular expressions (called REs, or regexes, or regex patterns) are essentially a tiny, highly specialized programming language embedded inside Python and made available through the re module. Using this little language, you specify the rules for the set of possible strings that you want to match; this set might contain English sentences, or e-mail addresses, or anything you like. If we want to represent a group of Strings according to a particular format/pattern then we should go for Regular Expressions. i.e Regualr Expressions is a declarative mechanism to represent a group of Strings accroding to particular format/pattern. Regular expressions use two types of characters: a) Meta characters: As the name suggests, these characters have a special meaning, similar to * in wild card. e.g. -- . ^ $ * + ? { } [ ] | ( ) b) Literals (like a,b,1,2…) In Python, we have module “re” that helps with regular expressions. So you need to import library re before you can use regular expressions in Python. Applications 1. To develop validation frameworks/validation logic 2. To develop Pattern matching applications (ctrl-f in windows, grep in UNIX etc) 3. To develop Translators like compilers, interpreters etc 4. To develop digital circuits 5. To develop communication protocols like TCP/IP, UDP etc. Functions----- 1. compile() re module contains compile() function to compile a pattern into RegexObject. 2. finditer(): Returns an Iterator object which yields Match object for every Match. start()--Returns start index of the match 2. end()--Returns end+1 index of the match 3. group()--Returns the matched string
  • 245. 28/07/2022 Regular Expression-Functions Methods of Regular Expressions? The ‘re’ package provides multiple methods to perform queries on an input string. Here are the most commonly used methods, • re.match()---We can use match function to check the given pattern at beginning of target string. If the match is available then we will get Match object, otherwise we will get None. • re.fullmatch()---We can use fullmatch() function to match a pattern to all of target string. i.e complete string should be matched according to given pattern. If complete string matched then this function returns Match object otherwise it returns None. • re.search()--- We can use search() function to search the given pattern in the target string. If the match is available then it returns the Match object which represents first occurrence of the match. If the match is not available then it returns None • re.findall()---To find all occurrences of the match. This function returns a list object which contains all occurrences. • re.split()--- If we want to split the given target string according to a particular pattern then we should go for split() function • re.sub()---In the target string every matched pattern will be replaced with provided replacement. • re.subn()--- This function returns a tuple where first element is result string and second element is number of replacements. • re.finditer()---Returns the iterator yielding a match object for each match. On each match object we can call start(), end() and group() functions. • re.compile()--- • ^ symbol--We can use ^ symbol to check whether the given target string starts with our provided pattern or not. if the target string starts with Learn then it will return Match object,otherwise returns None. • $ symbol--We can use $ symbol to check whether the given target string ends with our provided pattern or not