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

Python Notes

New python notes

Uploaded by

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

Python Notes

New python notes

Uploaded by

Ghulam e raza
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 141

Python Programming

Name:- G.Vivek Sai


Batch:- CSE
Subject:- Python
Topic:1.0:What is programming?
• A programming is acts as a mediator between machine and human
• The programming language is main purpose is to convert high-level
instruction to low-level instruction and low-level instruction to high-level
• For example:- ASCII Values

Programm
machine
ing
Human language

High-Level C,CPP,Python,Java low-level(binary level)

Topic:1.1:Types of programming?
• The python consist of two types of programming language they are,
1. POP(Procedure oriented programming)
2. OOP(Object oriented programming)
1) POP:-
• It is execute in ordered.
• Let us consider we have 4 block and each block contain name as
F1,F2,F3,F4
F1 First it is executed then it goes to
F2 that is ordered form

F2

F3

F4
• It doesn’t have security because it start execution from main method.
• In this mechanism it is execute from starting block of code and it execute
upto end block as shown above
• It will executes one block by other block that is serial manner.
• To overcome the security problem in python the OOP Concept is
introduced.
Drawback:-
• Lack of security
• No backward approach
• Intercept and runtime errors
• Reverse approach

2) OOP:-
• It works independent
• In OOP it allows bottom down approach it means it can start at any block
of method is called bottom of approach it overcome the drawback
of(POP)

Types of programming

POP(EX:- C OOP(EX:- Java,Python) Partial pop and partial


Language) oop

Partial pop and partial oop:-


• It is a combination of oop and pop it can execute the entire
code either oop or pop.

Topic:1.2:Major Version in python?


• General we have consider python version 2 and version 3 .
• In this two versions the code will execute in different manner and
returns results in different manner.

Version 2 Version 3
we can directly perform any There is no chances to give direct
calculations performance
To get output in version 2 the symbol To get output in version 3 the print
is used “>>>” statement is used
If you perform any divisiable If you perform any divisiable
operation it will return non-decimal operation it will return decimal
that is integer. values
EX:- 1 and 2 EX:- 1.0 and 1.5
Here we does’nt use any methods to We can directly print the values with
print statements help of print statement and we are
using methods to print the
statements
ASCII is followed It followed by Unicode universal
character encoding stand
Inproper syntax Proper syntax

NOTE:-
• We can start a python version 3 because the reasons is,
1. Unicode scheme
2. Proper syntax or structured
3. Accurate reasons it will generates

Topic:1.3:Introduction to python
• A python is an object oriented programming language which works with
help of objects
• Every objects is treated with object oriented programming
• The main purpose is used python is to solve mathematical operation,
development of websites, maintain database, developing mobile
application and etc..
• Father is Guido Van Rassum in year of 1991
• In python we use different modulus for perform individual task.
• Python was introduces Gudio van Rassum in year of 1991
• By using python we can perform
1. Mathematical operation like matrices
2. Design and develop frontend application
3. Create and maintain database

Topic:1.4:Features of python
• Its has only interpreter
• Dynamic memory allocation
• Secure and robust
• Dynamic typing
• Indentation

Topic:1.5:Interpreter VS Complier
• The complier is execute entire code at a time and it takes faster time to
execute the code
• The interpreter is execute the code line by line and it takes less time to
execute the code.
• The interpreter is faster then complier because it checks the code line
by line and it is fast to find error and it stores the data in primary
memory.
Complier Interpreter

a =10
a =10 It will
It entire b=20 execute
b=20
code is code
print(a+b)
print(a+b) execute line by
line
• The interpreter doesn’t need save file it automatically run when you
click interpreter button
NOTE:-

Complier→it is stored in Secondary memory(file must be save in memory)

Interpreter→it is stored in primary memory(does’nt need save file in memory)

• The complier and interpreter is used to find and fix the error
• In python we doesn’t need complier to execute the code.

Central Primary Secondary


Proccessing memory memory

unit (Interpreter) ( Compiler)

Topic:1.6:Where we run python code


• We can run python code in different platform among though we consider
a special interpreters which contain robust and secure properties
• They are many platform for python they are,
1. Google colob
2. IDLE(Python 3.12 64 bit)
3. Jupinter
4. Spyder
5. Orange Available in
anaconda navigator
6. Console
• Orange is used for frontend and backend
• Google colob is used for machine learning
Topic:1.7:Detail Explanation of Features in Python
1.Dynamic memory allocation:-
* it will create memory automatically for a variables and deallocation when
action is done because of interpreter(primary memory)

2.Dynamic typing:-
* it is defined values, datatype to a variable
Example:-
a=10;
print(a,type(a))
internal mechanism:- classes

<int>

<float>
a=10 <complex>

<str> output (int)


<list>
3.Secure and Robust:-
* every data is organize with the help of objects.

4.Indentation:-
* it is defined a step-by-step format for a block by default it has tab space
* we defined a indentation block with symbol is “;”
Example:-
With Indentation
If(1>2):
Print(“1 is less than 2”)
1 tab space it
is called an
indentation

Without Indentation

If(1>2):
Print(“1 is less than 2”)

Topic:1.8:Why We came variables

• Before variable concept the value are directly stored in memory with
address and it is not secure and it can access every one .
• “ID” is an fixed value it doesn’t change.
• “memory” is an not fixed value it change the value.

ID VS Memory
Example:-
a=10
print(id(a)) #output 165455155
print(memoryview(bytes(a))) #output 0x02457844dji5
10

AL AH AX BL

20

BX CL CH CX

Fig(1):Mechanism of Register
Value is
stored in
What is memory:-
register
• A memory is a group of register
What is register:-
• The register is an group of flip-flops
What is flip-flops:-
• A one bit storage area
Let us consider a memory contain 4x4 register and each register stores 256KB
Memory.
AX Registers Registers Registers 256KB

BX Registers Registers Registers 256KB

CX Registers Registers Registers


256KB

DX Registers Registers Registers


256KB

How Register Works and Stored?


AH AL

15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

AX
Topic:1.9: variables
• To overcome the previous problem the variable is used.
• The variable is change the address value each every second but, in
previous problem it won’t change the address value it is an disadvantage
and it have access to everyone to overcome previous problem the
variable concept is introduced
• A variable is a name of a memory location it stores some values and it
change the address values each every second and it have security to the
variable by changing the address values
• There is no scope values directly stored in memory the variable acts as
intermediate between values and address
• The variable is advance from previous problem because it change the
address of that variable and keeps secure and it doesn’t access everyone
because of it will change the variables Value

10
1001 1002 1003 1004 1005 1006

1007 1008 1009 1010 1011 1012


10
1013 1014 1015 1016 1017 1018

Address

• Initially the value is stored at location 1002 and there is a chances to find
the address of value it leads to give security to the data then the variable
used the property to change the location from one location to another
another location that is address is 1014
• To check change the location we have method is,

Memoryview(bytes(variable_name))
Example:-

Id output

Memory
address

• In python we are not done declaration in python because of it doesn’t


waste memory and it an dynamic memory allocation it will create a
space or memory automatically
• We can create variables into two steps they are,
1. Declaration of a variable
2. Initialization of a variable
1.Declaration of variable:-
* it is the process of creating memory space for a variable at a memory
For example:-
a

1010
2.Initialization of a variable:-
* the process of assigning a value to a variable is called initialization
For example:-
a=10

10
a

1010
NOTE:-
• In python variable declaration is not supported because if you declare
variables a,b,c and we use only 2variables that is a,b and c variable is
unused and memory is waste and to overcome this problem dynamic
memory allocation is used.

Types of variables Names:-


• In python we defined variable names are 3 types they are,
1. Camel case
2. Pascal case
3. Snake case
1.camel case:-
* each word letters are lowercase except second word first character
Example:-
abcXYZ
2.Pascal Case:-
* Each word first letter capital
Example:-
AbcXyz
3.Snake case:-
* each word connect with underscore(_)
Example:-
abc_xyz

Topic:2.0: Types of variables


• In python they are two types of variables those are,
1. Input Variable(Reading a value from user)
2. Output Variable(Displaying a value)
1.Input variable:-
* this variable is used to accept the value from user
* Here we need to use a method called input
* By Default a input method accept string datatype
Syntax:-
a=input()

Example:-
Without parse convert

Here, two number is


not added because it is
in form of string so, not
added to add two
number we need to
convert into parse

With parse convert

• The parse is nothing but before input method we are keeping datatypes
as follow example

a=int(input(“enter value:”))

• If you want to convert the entire string value into another datatype we
use method as parse()
2.output variable:-
* In python we have output variables treated with objects
* this objects are placed in print method as a parameter

Syntax:-
Print(objects(s),sep,end,file,flush)

Where,

Sep=separator

End=end

File=file

Flush=false

a)Objects:-
* this object is treated as a output variable
Example:-
b) sep:-
* which helps to separate two strings (or) more with some “x” string
Example:-

c)end:-
* this parameter is used to defined a end value for a string
Example:-
Case(1):-

Case(2):-

Case(3):-
d) file:-
* Here we can perform file read operation and file write operation
e) flush:-
* this parameter defined either value is assign to print check whether it is static
or dynamic
* flush=”True”(static) because user perform given input values
Flush=”false”(Buffered)
*dynamic is variable to print a statement
* by default the flush is false in condition
Example:-
a=none
a=10 # output 1
a=input() #output 0
therefore, when you perform “AND” Operation the output generates “false”.

Topic:2.1: Assign Multiple Values to Multiple variables


• There is chance to assign “n” number of values and “m” number of
variables.

Syntax:-

Variable1,variable2,variable3=value1,value2,value3

Example:-

a,b,c=10,20,30
Therefore, Here variable 1 will assign value as 10 and variable 2 will assign
value as 20 and variable 3 will assign value as 30 and if you give extra value it
will shown an error and also if give extra variable will shown an error
Case(1):-

Case(2):-

Case(3):-

Formula:-
Cval=Cvar

Where,
Cval= count of values
Cvar=Count of Variable
• If I give only single value to the 2 variables it will generate “TypeError”

Topic:2.2: Assign single Value to Multiple variables


• There is no chance to assign single number of value and “m” number of
variables.

Syntax:-

Variable1,variable2,variable3= value1

Example:-
a,b,c=10

• It is only take single value to single variable , we cannot assign multiple


variable to the single value ,but single variable can take multiple values
as shown below.
• It is not possible assigning single value to multiple variable but, we can
assign multiple values to a single variable due to the concept of “class of
tuple”

Topic:2.3: What is Identifier


• The identifier is a Name given to variable both variables and identifier
are not same it is different from each other

a = 10 Variable

Identifier

• Therefore identifier presented in variable


• The relation between a identifier and variable is directly proportional

Topic:2.4: What is Constants


• In python the constants is not supported
• A constant is defined as a fixed value to a variable
• Here, there is no keyword to defined constant variable
• Even we can defined constant variable by writing all character in a names
Example:-

PI=3.141516

Topic:2.5: What is literal


• The name of the constant variable is called as literal
• Literal is depends on constants
NOTE:-
• The main difference between identifier and literal is
1. Identifier is general variable name
2. Literal is constant variable name
Example:-
Constant
PI = 3.141516

Literal

Topic:2.6:Python Keywords
• A keyword is a fixed meaning , we can use it as a variable name
• In python we have 33 keywords they are,
Topic:2.7:Comment lines
• It is used to explain the code what is happen there.
• This lines are non-executable lines which are used for the purpose to
know what is code is.
• It increases the readability of code
• It’s wont effect the code execution

Types of comment lines:-


• They are 2 types of comment lines available they are,
1. Single comment line(#)
2. Multi-line comment line (‘’’ ‘’’)
1.Single comment line(#):-
* we can defined with single hash (#)
Example:-

2.Multi-line comment line (‘’ ‘’ ‘’ ‘’ ‘’ ‘’):-


* we can defined with (‘’ ‘’ ‘’ ‘’ ‘’ ‘’ )
Example:-
Topic:2.8:Datatypes
• It is defined that what type of values that variable can contains
• In python they is no chance to defined an array because of dynamic
typing
• Here every datatype is an class
• Every datatype variable as a objects
• In python the datatypes is organized by 4 steps
Example:-
a=int(input())

Numeric
Package

< class ‘int’>


Class

Int()
Method

20
Objects

• In python we have 8 types of datatypes as shown below


a) Text Type:-
• Here we defined the values with the type group of characters (strings)
• Here the class Name is < class: “str”>
Example:-

b) Numeric Type:-
• This type is also known as python numeric it contains three classes
named as
1. Int
2. Float
3. Complex
1.Int:-
* it contain non-decimal values from the range 0-9
Example:-

2.float:-
* it contains decimal values from the range 0.0-9.9
Example:-

3.Complex:-
* in this we create a complex values in combination of int and float object it is
in the form of standard complex format.
Example:-

a + ib

Real
part Imaginary part
• It is used to solve physics problem through maths like dot, cross product ,
scaler and vector product calculation
• In python the format of complex value is a+bj

Example:-

c) Sequence type and mapping type and set type:-


• We can discuss this three types in python collections

d) Boolean Type:-
• It returns two values either one is true and other is false
• We can assign the values “true” or “false”
Example:-
Case(1):-

Case(2):-
Case(3):-

e)Binary type:-
* In This type the result returns in view of binary bytes
Example:-

f)Nonetype:-
* in this type we can create a space for a variable at memory the value is null.
Example:-
Topic:2.9:Constructor
• A constructor is a method which doesn’t return any value and classname
and method name should be same .
• The constructor is mainly used for converting one python collection to
other python collection

For Example:-
I want to convert set collection to list and tuple collection as shown
below.

Converting
set to list

Converting
set to tuple

• This are used for converting from one datatype to other datatype
• The main purpose to implement type-casting and type-conversion
• Both type-casting and type- conversion is used to convert one datatype
to other datatype

Topic:3.0:Type-Conversion
• It is the process of converting from small datatype to large datatype.
• Automatically Converted in this type conversion.
• It is also know as implicit conversion.
• It is also know as widening process
• The drawback of type conversion is memory wastage
1 0 Contain 2
Bytes

1 0 . 0 Contain 4 Bytes

(Here Memory
wastage happen)

Example:-
Case(1):-

Case(2):-

Case(3):-

Topic:3.1:Type-Casting
• It is the process of converting from large datatype to small datatype
• It is also known as Explicit conversion
• It is a narrowing process
• The drawback of typecasting is data wastage

1 0 . 2

1 0 Here 2? Data is Wasted

Example:-
Case(1):-

Case(2):-

Case(3):-

Case(4):-
Case(5):-

Case(6):-

Case(7):-

Case(8):-
Topic:3.2:Operator
• A operator is an symbol which is used to perform particular task.
• Every operator returns two values either numeric value or Boolean
values as a result.
• In python we have 7types of operators they are,

a) Arithmetic operators:-
• This operator returns the result in numeric form that is 0 and 1

Example:-
• Now, let us consider the values a,b=5,8 then

b) Assignment Operator:-
• The assignment is used to assign a value to the operators .
• If a+=b is generate a=a+b then consider the example of case(2)
• If a=+b is generate a+b=a then consider the example of case(3) it will
generate the output as b value because a value is equal to a+b then a+b
is is equal to a
Examples:-
Case(1):-

Case(2):-

Case(3):-

• The case(3) generate the output as b value 20 because of “+” operator


have more priority so “+b” have “+ operator” then result is b value of 20
• The case(2) generate the output assignment operator that is adding the
two numbers because of of “+” operator have more priority so “a+” have
“+ operator” then result is b value of 30

c) Comparison operator:-
• These operators returns the results in Boolean values and it finds the
relation between two or more variables.
• Let us consider the comparison operator as shown below.
• The Boolean value is nothing but it generates the output in true or false
condition.
Example:-
Case(1):-

Case(2):-

Case(3):-

Case(4):-
Case(5):-

Case(6):-

d) Logical Operator:-
• This operator is used to perform logical multiplication and addition.
• It returns the result numeric values in physical and Boolean values in
logical.

• Let us consider the truth table of and ,or ,not as shown below
• Let us consider an example according truth table as shown below.

Then, now
8 4 2 1
----------------------------------
1 0 1 0 (a=10 binary value)
0 1 0 1 (b=5 binary value)
--------------------------------------
0 0 0 0 (AND Value) (In decimal 0 that is numeric )
--------------------------------------
1 1 1 1 (OR Value) (In decimal 15)
Note:-
• AND Operator is an Multiplication
• OR Operator is an Addition
Example:-
Case(1):-

Case(2):-

Reason:-
a=10
b=20
20 and 10 (b and a)
0
1

• In the python the highest value is given priority


• So that the above “1” is highest value compare to “0” then “10” will be
executed
a=10

b=20

20 or 10

0 1  it is executed “0” that is “20”


e) Identity Operators:-
• This operator is used to check whether the LHS Value and RHS Value
equal or not.
• This operator returns the result Boolean values.
• By using this operator we can compare LHS and RHS with Values.

Example:-
Case(1):-

Case(2):-

Case(3):-

Case(4):-
Case(5):-

• The double equal to is compare address of the objects


• The difference between values and address is,

• Let us consider an example as shown below.


f) Membership Operator:-
• This operator is used to find a particular element is present in collection
or not.

Example:-
Case(1):-
Case(2):-

Case(3):-

Case(4):-

Case(5):-
Case(6):-

Case(7):-

Case(8):-

g) Bitwise Operator:-
• This operator also knowns dangerous operators in operator sets because
tis operator are works on binary bits.
• They are 6types of bitwise operators as follows.
Examples:-
Topic:3.3:Expression
• An expression is a combination of operator and operands.
• An Operator is an Symbols which is used to perform particular task.
• An operand is a variable is an expression.

a + b - c

Operator

Topic:3.4:Arrays
• Arrays is not a list
• It arrays Is stores in ordered
• An array is a collection of elements which contains similar datatypes
elements.(Homogenous data).
• This elements is organized in continuous memory allocation by default
the index first element is start with [0]
• Creating in memory sequence

10 20 30
From
Packages

Modules
Import

Functions

Def
• The above here we need to use arrays packages, modules, and method.
• The list is best compare to arrays.

Syntax:-

Array_name = array.array(specifier, [v1,v2,v3………vn])

Format Specifiers:-
i = integer
c = character Module function datatype values

f = float
d = double
b = Boolean
I= long integer

Example:-
Using Packages

Using Module
Topic:3.5:Strings:-
• A string is group of characters which are Enclosed with Single Quota or
double Quota or double quota
• Strings is not with respect to datatypes.
1. String Introduction
2. String Slicing
3. String Modification
4. String Concatenation
5. String Format
6. String Escape sequence characters

1.String Introduction:-
* we can create a string by assigning a value to a variable that should
be enclosed in single quota or double quota
Syntax:-
Var_name = “ string”

• we can create a string variable in two ways


1. single line value
2. multiline value
• the Single line value uses the single quota or double quota.

• the Multi line value uses the three quota line.


Examples:-
1)

2)

2.String Slicing:-
* The Slicing is defined it is the process of get sub parts of a string
that subparts is known as substring.
* it means small parts of string from original strings
* If you want to do the slicing we need to know what is indexing.
Indexing:-
• it is the process of assigning a unique value to individual character in a
string.
• We can assign indexing in two ways
a) +positive indexing
b) – negative indexing
Types of Indexing

+ve Indexing -ve Indexing

0 to N-1 -1 to -N

v i v e k s a i
0 1 2 3 4 5 6 7 8 9 10 11 12 13

Types of slicing:-
• In python we can implement slicing in two ways
1. Without step count [ Start:end+1]
2. With step count [ start:end+1:sc]
Where,
Sc= step count
Example:-

Reverse of string
3.String Modification:-
* A string which effects with some operations(Mutable) is called
string modification
Uppercase:-

Lower Case:-

Remove Whitespace:-

Replace:-

Split:-
4.String Concatenation:-
* it is the process of combined two or more string with help of
symbol “+”
Example:-
a)

b)

5.String Format:-
* we cannot combine a string within an integer.

• But, I want to combine a string with integer then I will use


concept of formatting a string.
Name=input()
Prof=input()
Comp=input()
Txt=”my name is {}, and I am {} for company{}”
• When you want to try to concate a string and integer in general
way it will raise an error because a string and integer are not be
concated.
Example:-

6.String Escape sequence characters:-

Topic:3.5:String Methods:-
• There are 16 types of methods in strings they are,
1.Capitalize():-
* First letter of every string should be capital

Example:-

2.Casefold():-
* Every string should be converted into lower cases

Example:-

3.Center:-
* this method is used to make a string into a center.

Example:-
Without center

With center
1)

2)

4.Count:-
* this method is used to returns the count of occurrence value.
a= “viv ee k
Contain 2 occurrence
value then it will
generate result 2 that
means “a” came two
times

Example:-

5.Encode:-
* this encode is used the string convert into binary form.
Example:-
6.Ends with:-
* this method Is used to a particular character is ends position or not.
* it returns true or false.
Example:-

7.Expand tabs:-
* this method Is used to expand the space for string.
Example:-

8.find:-
*this method returns the index values of a characters in a string.
a=”ch aa ndu

“a” contain 2 index


then result will be
“2” index value
Example:-
9.format:-
*The format() method formats the specified value(s) and insert them
inside the string's placeholder.
Example:-

10.isalnum:-
*this method return true when string contain alphabets and numeric
values.
Example:-

11.isalpha:-
* this method returns true when the string contain only alphabets if
not it will return false.
Example:-
12.isdigit:-
* this method returns true when the string contain only numeric if
not if will return false.

13.Join:-
* this method is used to join a character at before and after a string.
Example:-

14.Partition:-
* this method is used to split entire string into separate.
Example:-

15.Zfill:-
* this method is used to fill with zero before a string.
Example:-
16.swapcase:-
* this method is used to convert lowercase text to uppercase text and
uppercase to lowercase text.

Topic:3.6:Collections:-
• The 80% in python plays main key role of this
collection.
• They are 4 types of collection in python as shown below.
1. List
2. Tuples
3. Sets
4. Dictionary

• A collection is a group of elements which is belong to same


datatypes or not same datatype and we are not sure those
elements is organize in continuous memory allocation or non-
contingous memory allocation.
• Every collections contains 3 properties that is,
a) Ordered/unordered
b) Mutable/Immutable
c) Allow Duplicates/ not Allow Duplicates

a) Ordered/Unordered:-
• If you create a collection as if is reflects to a output then called
as ordered collection. If not we can treated as unordered
collection.
Example:-
Ordered (output must come ordered if not it is an unordered
[10,20,30] collection

[20,30,10] unordered

b)Mutable/Immutable:-
* It is a process of make a change in a collection we make a into two
ways
1)Elements(changing a value or adding a new value)
2)Structure(After adding new value the length is change)
* when you agree with above two thing then only we say that is
mutable if not it will treated as Immutable.
* the Mutable is defined that it is used to change a value or adding a
new element to a collection is called Mutable
* the Immutable is defined that it doesn’t change any value or not
adding a new element to a collection is called Immutable
* According to mutable if must be satisfies two condition that is
elements and structure
* Now let us consider flow diagram of mutable as shown below
Mutable

Elements Structure

[10,20,30] [10,20,30]

I want to replace 10 with 40 Before adding a new


value and I want to add new element the length have 3
element 50 then this process is
called mutable

[40,20,30,50]  Final Result [40,20,30,50] length is 4

c)Allow Duplicates/Not Allow Duplicates:-


* The collection which accepts duplicates values that means repeated
values is called as allow duplicates collections. If not we say that if
not allow duplicates
Example:-
[10, 20 ,30,40, 20 ]

Duplicates values

Properties of a Collection:-
• Every collection have 3 properties that decides It is have
mutable or immutable or allowing duplicates .
1)List:-
• A list is collection which contains heterogenous data elements
with the properties
a) Ordered
b) Mutable
c) Allow Duplicates values
Syntax:-
List_Name = [Value1, value2 ………………..n]
• This collection is an universal collection.
• We can create a list with symbol”[]”.
Example:-
a=[1,2,3,4]
• We have restricted value of other collection better to use list.
• We have 7 list concepts as show below.
a) Creating a list
b) Ordered
c) Mutable
d) Allow Duplicates
e) List has different datatypes
f) Loop through list
g) List constructor
h) Except the values from user
a)Creating a list:-

b)Mutable:-
• I need to change 30 value to 60 value then I need index value of
30 to change.

a=[10, 20 , 30 ,40,]
a[0] a[1] a[2] a[3]
then the index value of 30 is a[2]
Example:-

c)Allow Duplicates:-

d)List different datatypes:-


e)List Constructor:-

• The main purpose of constructor is to convert a group of


elements into required collection and we can perform one
collection to other collection.
f)Loop through list:-

List Operations:-
• We have 3 operations in list as shown below.
a) Insertion
b) Sort
c) Deletion
Operations

Insert sort Deletion

Insert(p,v) ASC Remove()


Append(v) des pop()
Extend(L) clear()
del

a) Insertion:-
• We can accept the values from user to collection.
• We perform insertion operation three ways there are,
1) Insert(p,v)
2) Append(v)
3) Extend(L)
1.Insert(p,v):-
• This method is used to insert a value based on position or index
values into a list.

Insert(p,v)
Where,
P= index value
V=value for insert
Example:-
Without using input() Keyword
With using input() Keyword

2.Append(v):-
• This method is used to add a element at end of the collection.
Example:-
Without using input() Keyword

With using input() Keyword


3)Extend(L):-
• This method Is used to combined two lists into single lists
Example:-

B)Sort:-
• We perform sorting operation by arranging elements either in
ascending order or descending order.
Example:-

• We can perform sorting operation with help of sort.


• We have method

Sort()
• By default the sort method returns ascending order of
elements.

• If you want descending order we need to pass a parameter into


sort method that is,

Reverse=true
• Here a list an contain any type of data we can perform sorting
operation on the data with respect to ASCII Values.
c)Deletion:-
• It is the process of delete a specific element in a list .
• We can delete using remove() method.
• We have 4 types of different types of deletion they are,
a) Remove()
b) Pop()
c) Clear()
d) Del()
e) Remove()
a)Remove():-
• This method is used to delete a specific element of a collection.
Example:-
Without using input() Keyword

With using input() Keyword


b)Pop():-
• This method is used to delete last element of collection.
Example:-
Without using input() Keyword

With using input() Keyword

c)Clear():-
• This method is used to clear all the elements from collection.
Example:-
Without using input() Keyword
With using input() Keyword

D)del():-
• The del is a statement which is used to remove the memory
space of a variable
Example:-
List Comparation:-
• It returns true when the all elements are same as L.H.S AND
R.H.S list it returns false when those are not same

Task:-
1) write a python code on banking system on list collection from
user input without using functions
Output:-
2) Tuples:-
• A tuples is a group of elements which are belong to same or
different datatypes and the memory allocation is continuous .
Syntax:-

Tuple_name = (value1,value2,value3)

• The properties are,


1) Ordered
2) Immutable
3) Allow Duplications
• We Perform in Tuples are,
1) Creation of Topics
2) Length
3) Constructor
4) Access elements
5) Update Tuples
6) Unpacking
1) Creation of Topics:-
• We can create a tuples with help of “()”
a) Ordered:-

b) Immutable:-
• The Tuples is an packed collection and it have security so, it
cannot change values.
c) Allow Duplication:-

2) Length:-

3) Constructor:-
• Which is used to construct one collection item to other
collection item.
Example:-
4) Accessing Elements:-

5) Update Tuples:-

6) Packed/unpacked tuples:-
a) Packed Tuples:-
• In this mechanism if you create an tuple elements is enclosed
with parathesis there is no scope to change the elements.
Example:-
b) Unpacked Tuples:-
• This collection of unpacking is to unpack the packed collection.
• Once we perform unpack every values loss the properties of
tuples.

Example:-

10 20 30

20 30
10
x y z
3) Sets:-
• Set is a group of element which is not organized because it is
unordered and mutable and not allows duplications values.
• We can create a set by using {} notation
a) Create a set
b) Set Constructor
c) Accessing elements using loop
d) Checking element is present in collection
a) Create a set:-
1) Unordered:-

2) Immutable:-

3) Not Allow Duplicates:-


b) Set Constructor:-

c) Accessing elements using loop:-

d) Checking element is present in collection:-

Operations:-
• There are 3 types of operations in sets they are,
a) Insertion
b) Joins
c) Deletion
• Let us consider flow diagram of operations in sets they are,
operations

Insertion Joins Deletion

Add() union() del

Update() pop

Remove

Discard

Clear

a) Insertion:-
1) Add():-
• This method is used to add a elements to existing set.
Example:-
Without using input() Keyword

With using input() Keyword


2)Update:-
• This method is used to join two sets into single sets.
Example:-
Without using input() Keyword

With using input() Keyword

b) Join:-
• This method is used to perform union operations between two
sets.
Example:-
Without using input() Keyword
With using input() Keyword

c) Deletion:-
a) Remove:-
• This method is used to remove a elements from sets if the
elements is existing it will remove if not it will raise key errors.
Example:-
Without using input() Keyword

With using input() Keyword

b) Discard:-
• This method is used to delete an element if it is an existing set.if
not won’t raise any error it will print existing set.
Example:-
Without using input() Keyword

With using input() Keyword

c) Clear:-
• This method is used to clear the sets
Example:-
Without using input() Keyword

d) Pop:-
• This method is used to delete first element of the sets.
Example:-
Without using input() Keyword
e) Del:-
• This method Is used to delete entire set collection.
Example:-
Without using input() Keyword

Task:-
2)write a python code on banking system on set collection from
user input without using functions.
Output:-
4)Dictionary:-
• A dictionary is a group of element it is also known as grammer
structure it is an “n” dimension collection i.e nx2
• The data and arranged in form of table that is rows and
columns .
• The data is organized in key value format that is table format
with the properties ordered and mutable, not allow the
duplicates keys values.
• We can create a dictionary using { : }
Keys Values
aaa 6
bbb 7
ccc 8
ddd 10
ee 11

• The dictionary perform,


1) Creation of dictionary
2) Access Dictionary Elements
3) Get Keys
4) Get Values
1) Creation of Dictionary:-
a) Ordered:-

b) Not allow duplicate values:-


2) Accessing Dictionary Elements:-

3) Get Keys:-
4) Get Values:-

Operations:-
• There are two operation have in dictionary they are,
a) Insertion
b) Deletion

Operations

Insertion Deletion

General Method pop


Pop item
Clear
Del
a) Insertion:-
• We can insert a element in general way.
Example:-

Without using input() Keyword

It have format key = value

With using input() Keyword


b) Deletion:-
1) Pop:-
• This method is used to delete a specified element a dictionary.
Example:-
Without using input() Keyword

With using input() Keyword

2) Pop item:-
• This method is used to delete last element in a collection .
Example:-
Without using input() Keyword

3) Clear:-
• This method is used to clear a all elements in a dictionary.
Example:-
Without using input() Keyword

4) Del:-
• This keyword is used to delete all the item of the dictionary .
• Now we have two important role in dictionary they are,
1) Convert dictionary into table format.
2) Nested Dictionary
1)Convert dictionary into table format:-
• This method we can convert the single line result of dictionary
into table format.
Example:-
Without using input() Keyword

With using input() Keyword


Using Pandas:-
• This is the second method to convert the dictionary into table
format. In this we are using import pandas as pd
Without using input() Keyword
With using input() Keyword
2) Nested Dictionary:-
• Here, we can create dictionary inside dictionary is called nested
dictionary.
Example:-

Task:-
3)write a python code on banking system on Dictionary collection
from user input without using functions.
Using Tabulate Format
Output:-
Using pandas Format
Output:-
Using Normal Format
Output:-

Topic:3.7:Object Oriented Programming(OOP):-


• The oop is the mainly used for to give the security to the data.
• A object oriented programming is allows to
decompose(dividing) problems into number of entities of called
objects then we can say those are methods.
Purposes:-
• The main main purpose of to came oop is to provide an security
to the data.
• For providing security we need to use some principle called oop
principle .
• We have 6type of object oriented programming they are,
1) Object and class
2) Data Encapsulation
3) Inheritance
4) Polymorphism
5) Data Abstraction
6) Message Passing

1)Object and class:-


a)Class:-
• A class is container it consists methods and data members and
objects.
• It Is like a structure or template to perform specific task.
• Class acts a shield for methods , if anyone want to access a
value first it need to take permission from the class in this
manner the security is applied.
• According to mathematical way,

(methods + Data Members) + Objects

• Let us consider diagram that corresponding to class they are,

Class

Methods

Data
Member

a) Creation of Class:-
• We can create a class using “class” keyword.
b) What is Method:-
• A method is a contain self contained block of code which is
used to perform particular task.
• In method we need to pass “self” as a default parameter at
method declaration.
• We can create a method with the keyword of “def”.
Syntax:-

def method _ Name(self , pl):


c) What is Data member:-
• A data member is defined that as a variables in methods the
main moto of oops is to provide.
b)Object:-
• An object is a basic runtime entity in object oriented world the
main purpose of objects is to pass values from one place to
other place.
• A object is a just like a variables it refers a arguments of
elements it contains every data temporarily .
• An object performs two operations
1) Creation of object
2) Calling Of objects
1) Creation of Object:-
• In this we need to create objects for the purpose of creating
space for values which are objects is holds

Obj _Name = Class _ Name()

Example:-

Obj = vivek() or sai = vivek()


2) Calling Of Objects:-
• In this we need to call a method with the help of objects and it
may or may not contains parameters.

Obj _Name . method _ Name()

Example:-
With Parameter

2)
2)Data Encapsulation :-
• The wrapping of data and methods into single unit is known as
class that is encapsulation.
• In encapsulation there is no involvement of objects.

• We implement encapsulation mechanism with help of class and


data members and method member only.
• When implement of encapsulation we have two parts.
1) Covered parts
2) Uncovered parts
• The covered parts is defined that all the data members are get
security
• The uncovered part we found only methods.
Example:-
Case(1):-

Case(2):-
3)Inheritance:-
• The process of deriving a new class from already existing class
it means it getting properties from before class to current class
the main use of inheritance properties is code re-usability.
• Here, we need to use constructor rotation to call the previous
class to get properties.
• We need to use : operator to inherit
• The main purpose of inheritance if we have multiple classes(m)
and we create objects for each classes so, if the classes are
1000, we create 1000 objects so it is a very difficult task.
• To avoid this problem we go with the concept called
inheritance.
• In python we have 5 types of inheritance they are,
1) Single
2) Muti-level
3) Multiple
4) Hierarchal
5) Hybrid
1) Single Inheritance:-
• In this inheritance have exact two classes one is
a) Parent class or base class.
b) Child class or derived class.
Example:-
Class vivek():
Def add(self): Base Class
Print (“ class A”)
Class sai (vivek):
Def sub(self): Derived Class

Print(“class B”)

Derived class name Base class Name

• We have formula to calculate how many objects is required to


create .
Co= ( Cc – Ccc)
Where,
Co = count of object
Cc= count of classes
Ccc = count of child classes
Cc= 2 , Ccc= 1
Co= (2-1)
Co = 1 ( object creating)
Example:-

2) Multi – level inheritance:-


• Multi-Level inheritance is possible in python like other object-
oriented languages. Multi-level inheritance is archived when a
derived class inherits another derived class. There is no limit on
the number of levels up to which, the multi-level inheritance is
archived in python.
• In this multi- inheritance we have minimum 3 class and count of
class must be greater than 2
• In this inheritance we have one parent class and one child class
and “N” numbers intermediate class.
• We have formula to calculate how many objects is required to
create .
Co= ( Cc-(Cic + Cpc))
Where,
Co = count of object
Cc= count of classes
Cic = count of intermediate classes
Cpc = count of parent classes
Cc= 3 , Cic= 1 , Cpc =1
Co= (3-(1+1))
Co = 1 ( object creating)
Example:-
3) Multiple Inheritance:-
• In this inheritance we have “n” number superclasses and one
subclass here, the moto is we need to get properties from mutli
-class at a time.
• Here, the minimum count is 3 and count of java multiple
inheritance not supported directly because there is no scope to
allocate memory allocation for every class one by one.
• I won’t support directly in java we can implement via ‘interface
concept’ in this situation is called diamond problem.

• In python the memory allocation is done temporary so, that


there is an chance multiple Inheritance it supports directs in
python.
Co= ( Cc – Cpc)
Where,
Co = count of object
Cc= count of classes
Cpc = count of parent classes
Co = (3-2)
Co= 1
Example:-

4) Hierarchal inheritance:-
• This inheritance is opposite to multiple inheritance which we
have one super class and “n” Child Class .
• Which is Oriented in tree like Structure
Co= ( Cc – Cpc)
Where,
Co = count of object
Cc= count of classes
Cpc = count of parent classes
Co = (4-1)
Co= 3
• When more than one derived class are created from a single
base this type of inheritance is called hierarchical inheritance.
In this program, we have a parent (base) class and two child
(derived) classes.
Example:-
5)Hydrid Inheritance:-
• Inheritance consisting of multiple types of inheritance is called
hybrid inheritance.

Example:-
4)Polymorphism:-
• The Ability to take more then one form called polymorphism
• In python have the polymorphism classified into two types
they are,
a) Runtime (Method Overriding)
b) Compile Time(Method overloading)
Example:-

a) Compile time(Method Overloading):-


• The same methods name and different parameters with a
class is called method .
• In this mechanism we have single class which contains two or
more methods all methods name should be name and
parameters is different.
• Based on
1) Count of parameters
2) Types of parameters
• In simply we can say that “same method name” and different
parameters within a class.

• In python the overloading is not supported it returns false.


• To implement overloading in python we used “dispatch
method”.
• There is no implementation of method overloading
mechanism and not supported direct in python because there
is no specification in datatype
• For that we need to use package called “multiple dispatch”
and module “dispatch”.
Example:-
Case(1):-

Case(2):-

Example:-
b) Runtime ( Method overriding):-
• In this mechanism we have two or more classes contains single
method in each class contains same method name and same
parameters the count and time should be same in simple we
can say that same method name and same parameters in
different classes.
• For establishment communication with classes we use
inheritance concepts.

Structure:-
Example:-
5) Abstraction:-
• This method is the process of hiding internal details and expose
what user need.
• We need to use a package called “abc” and module “ABC” to
implement abstraction.
• The abstraction is not supported directly .
• In abstraction we hide the data by abstract methods for that we
need to load package “abc” and module “ABC”.
• We can create abstract method called none definition.
Example:-
6) Message Passing:-
• The process of passing values via objects to the method is
called as message passing or message communication.

Topic:3.8:Exceptions:-
• A error is defined as a mistake done by user .
• The error may raise in both implicit and explicitly based on the
situation.
• Errors are classified into two types they are,
a) Syntax Error
b) Exception Error

a) Syntax Error:-
• This Errors are also called Implicit errors are the mistakes are
done by user while writing the code syntaxy
• In python every error to be considered either syntax error or
logical error based on situation.
Example:-
Case(1):-
Case(2):-

b) Exceptions Errors:-
• This are runtime errors which syntactically correct but logically
mistake is called as exception.
• The exception is classified into 2 types they are,
1) Pre-Defined exception or Built- in Exception.
2) User-defined Exception.

1) Pre-defined Exception:-
• this exception are raise when code contains logical mistakes.
• They are many types of logical mistakes as shown below.
1) Syntax error
2) Type error
3) Name error
4) Index error
5) Key error
6) Value error
7) Attribute error
8) Io error
9) Zero division error
10) Import error

1)Syntax Error:-

• Explanation:
o This code will raise a syntax error because you cannot
assign a value to a literal (10 = a should be a = 10).
o Print(a) should be print(a) since Python is case-sensitive.

2)Type Error:-

• Explanation:
o This code will raise a type error because it attempts to
concatenate a string (a) with an integer (b).
o Strings and integers cannot be directly concatenated or
added in Python.

3)Name Error:-

• Explanation:
o This code will raise a name error because the variable a is
not defined before it is used.

4)Index Error:-

• Explanation:
o This code will raise an index error because the list a has
only two elements (indices 0 and 1).
o Attempting to access a[2] is out of the valid index range.

5) Key Error:-

• Explanation:
o This code will raise a key error because the key 3 does not
exist in the dictionary a.
o Key errors occur when you try to access a dictionary with
a key that is not present.

6)Value Error:-

• Explanation:
o This code will raise a value error if the user inputs a non-
numeric string like "aa".
o The int() function expects a string that can be converted
to an integer, and if it receives an invalid value, a value
error is raised.

7)Attribute Error:-

• Explanation:
o This code will raise an attribute error because the int
object a does not have an append method.
o Attribute errors occur when you try to use an attribute or
method that does not exist for a particular object type.

8. I/O Error:-
Explanation:

• This code attempts to open a file named cs.txt in write mode


("w").
• The open function returns a file object, which is stored in
variable a.
• The print(a) statement will print the representation of the file
object, not an error.
• However, if there is an issue with accessing the file (e.g.,
permission denied or invalid path), it might raise an IOError.

Output:

9. ZeroDivisionError:-

Explanation:

• This code assigns 1 to variable a and 0 to variable b.


• The print(a / b) statement attempts to divide a by b, which is
not allowed as division by zero is undefined.
• This will raise a ZeroDivisionError.

Output:
10. Import Error:-

(a) Import array

Explanation:

• This code imports the array module and creates an array of


integers ('i') with elements [1, 2, 3].

(b) Import keyz (assumed to be an error)

Explanation:

• This line attempts to import a module named keyz.


• If keyz is not a valid module or not installed, this will raise an
ImportError.

Output:

Structure of exceptions:-

• To solve the runtime error with syntaxial manner.


• We have 3 types of exceptions in python as shown below
a) Try Block
b) Except
c) Finally
Note:-
• Here, An Exception means Containing Errors
Working Principle:-
• In tryblock we place a code which can raise error . if it is raise
error it forward to that Except , if there is no error raised in try
block it will skip the except block and prints Finally Block of
code
• Try block is used to create block of statement which is are
doubtfull of generating the exception
Example:-
Case(1):-

If you don’t know that error name


then write exception word
because it is an pre-defined
function it will detects
automatically that name error

Case(2):-
• If you know that error name then write that error name
b)User-defined:-
• We can create or raise own exception based on the situation
• Here, we need to raise user-defined excecption as keyword of
raise
• In this no need of implementation of structure of exception.
• Python also allows you to create your own exceptions by
deriving classes from the standard built-in exceptions.
• Here is an example that has a user-defined MyException class.
Here, a class is created that is subclassed from base Exception
class. This is useful when you need to display more specific
information when an exception is caught.
• In the try block, the user-defined exception is raised whenever
value of num variable is less than 0 or more than 100 and
caught in the except block. The variable e is used to create an
instance of the class MyException.
Example:-
Topic:3.9:Module:-
• A module is a group of function which are is used to provide
flexibility to the user to access required modules from file to
other file.
• Here, we need to create two files with extension .py
a) One file contain function declaration and implementation
but, not function call
b) Other file is user file we need to call function from here
• In python we have two types of modules they are,
1) Pre-defined Module
2) User-Defined Module

1) Pre-defined Module:-
• There are build in modules which have specific operations.

1) Import math
2) Import re
3) Import platform
4) Import datatime
5) Import os
6) Import sys
7) Import json
8) Import random
9) Import collections
10)Import request
11)Import csv
2) User-defined module:-

Topic:4.0:File Handling:-
• A file is a group of objects (data) of type any information that
means In a file we can store any type of data.
• The main purpose of file is for storage
• Operations of files,
1) Opening files
2) Creating/writing file
3) Reading file
4) Closing file
Modes:-
Opening a File

• The open() function is used to open a file or we can open


existing file . It returns a file object and is most commonly used
with two arguments: the file name and the mode.

Example:-

f = open(“example.txt”,w)

Now, check the weather the file is created in hard disk


Creating and writing data into the file:-

Now, check the weather the file is written in file or not

• Here we use the write() method to write the any information


into file

Reading a file:-

• This method is used to read the data from the files.

Result:-
Closing a file:-

• This method is used to close a file after performing read/write


operation.

Append a file:-

Result:-

Topic:4.1:Conditional Statements:-
• The statement which can execute based on a
condition(constraint/ restriction) is called as conditional
statement.

You might also like