Python
Python
Python
• Python is a high level and object oriented language which was
developed in 1991 by Guido Vonn Rossum.
• Python is compiled and interpreted language.
• At first step python program is compiled and converted into
bytecode which is independent code and then in second step
we interpret the bytecode and make it executable file.
• Python follows Object oriented, procedure oriented and even
driven programming models.
• Python also helps to create GUI application.
• Python has huge set of predefined libraries which easily helps
to create and solve the complex problem in easy steps.
• Python is dynamically typed language which means we don’t
have to tell at compile time any details of identifiers.
• Python is most popular language and ranked at 1st in TIOBE
index.
Python Vs All Other Language
Python is only language which works in almost every types of
computer software.
Python is dynamically typed language and in other languages we
have to define first to use something like identifiers.
Python helps to create GUI, Game, Social Media applications.
Python plays an important role in robotic science, machine learning
and artificial intelligence. Other language are not compatible to work
with these technologies.
Other language has some typical strict and complex syntax which
may create problem for new users to learn and grab it.
Python has most easy syntax and most user-friendly language to
learn as beginners.
Programming Models
Procedure oriented programming model works by making function for
every task to do. We create separate function to do the specific task.
Example of procedure oriented can c, cpp, python, etc.
Object oriented programming works on real world objects. We can
represent any real world object into code and solve their problem.
Example of object oriented can cpp, java, python, etc.
Event driven programming model specifically works on behalf of user
action whenever user does anything an event occurred like mouse
click, double click, mouse hover, etc.
Example of event driven programming can be visual basic, python,
etc.
Difference between procedure and
object oriented
Procedure oriented programming Object oriented programming
We can’t represent real world We can represent real world
object. object into code easily.
This is not suitable for solving It solves the complex and real
the complex problem. world problem.
Code becomes lengthy when It handles huge amount of data
large problem are to be solved. by using different features.
It does not have capability to It provides full control of data
control the data thus don’t and provides security by using
provide security of data. class concept.
Identifiers
Those who can change their value is called variable.
Those who can not change their value are constant.
Identifiers are the entities which helps to write the code.
Keywords are the special characters which do have special meaning.
Variable name can not be similar with keyword.
There are 33 keywords in python :-
Operators
Operators are those who operates on operands.
Operators are used to perform the operation on given data.
Operators primarily can be of binary, ternary, assignment, compound,
comparison, logical, bitwise, relational operator, etc.
Binary operators are those who operates on two operands.
Like example +,-,*,/, etc. there are two operands given in binary
operator.
Ternary operators are those who can work on three operands. It is
also called conditional operator.
We have discussed in detail about operators in next page.
Flowchart of operators
Operators can be classified into mainly :-
1. Assignment Operator:- we can assign any value lvalue is variable and
rvalues is constant. Like x=12
2. Comparison Operator:- we can compare two or more than two values by
using them. Like <,>,<=,>=, etc
3. Relational Operator:- we can show the relations between variables with
the help of them. Like
4. Logical Operator:- these are used to test the variables logically is it true or
false. Like &&, ||, ! are three which are widely used.
5. Bitwise Operator:- these operates on single value generally it operates to
change the value of them. Like &, |, ! are widely used.
6. Compound Operator:- these are operators which are primarily
combination of two operator. Like +=,-+, *=, /=, etc are widely used.
Object Oriented Programming
This is programming model which works on real world objects and solves the
complex problems in easy steps.
We create classes to represent a real world objects and different variables
and methods are used to show their behavior.
OOP concepts provides full security of data within the program that’s why
almost all upcoming languages implement this model.
Abstraction, Encapsulation, Inheritance, Polymorphism, Data Hiding, etc are
the core concepts which OOP consists.
We will cover all important concepts in details in further discussions.
Abstraction
This concepts refers that only important details are to be disclosed to the
user unnecessary details need not to be shown.
It makes the user to understand the concepts easily without knowing the
internal details.
For ex- ATM machine which only provides you to perform your transaction
without knowing internal implementation.
Creation of classes
Class Complex:
__init__(r,i):
this.r=r;
this.i=I;
Comp(self,real,image):
self.real=real
self.image=image
Complex c1(5,6)
Examples of programs
Programs to find the even numbers between given range.
Program to find the odd numbers between given range.
Program to find the prime numbers between given range.
Program to find the sum of given numbers.
Program to find the square root of given numbers in range.
Program to swap the two numbers in python.
Program to calculate the square of given number in range.
Program to calculate the cube of number in given range.
Program to perform the operation in array.
Program to print the numbers whose are palindrome in given range.
Data Types in Python
Data types are however can be broadly categorized in three types namely-
Container:- these are the types which hold the data like list, set, dict, tuple,
etc.
Predefined:- these are already defined like integer, character, float, strings.
User-defined:- we can create our own data types. Class are used to create
own data types.
Data types plays important role in storing the different types of data.
Strings are used to store the text values specially we can also perform
different operations on them.
We are going the dsecribe the different function in the next page.
Functions in Maths
Sum(): it adds the given range of numbers and returns the result.
Len(): it is string function which count the number of characters.
Sin(): it finds the value of given angle in sine
Cos(): it finds the value of given angle in cosine.
Tan(): it finds the value of given angle in tan.
Asin(): it finds the value of given angle in sin-1
Acos(): it finds the value of given angle in cos-1
Count(): it counts the given value in range.
Range(): it is used for purpose of printing the numbers counting.
Atan(): it is used to find the value of given angle in tan -1
Important terms to know in python
Mutable means we can edit, change the content.
Immutable means we can’t change and edit the content.
Iterable means we can apply the loop on the given data type.
Not Iterable means we can’t visit and apply the loop on given data.
There are plenty of different data types which are used for different purpose.
We are going to cover List, Tuple, Set, Dict, Map, Filter, Reduce, etc are some
of concept which we are going to cover in detail in further discussion.
List & (List Vs Array)
List are used to hold large amount of values in linear fashion, it can be
homogeneous and heterogeneous data types.
List can store similar and dissimilar types of values and also allow some
operation on that.
There are some predefined function we can perform on list are :
Count(): It counts the total values pass
Max(): It returns maximum value given in list.
Min(): It returns minimum value in given list.
Sum(): It returns sum of given values in given list (All values must be of int)
List Vs Array
List can be used for homogeneous and heterogeneous data types. But
array can only be used for similar data types.
List are fast in nature we can perform operation easily on them. But
array manipulation proved to be complex and time consuming.
List is widely used where different data types need to be handles
easily and data related with single entity need to handled. But array
are not superior to handle the different data types.
List are created by using [ ] we can create empty list. But array are
not created empty generally we have to tell size.
List are dynamic in nature we don’t have to tell the size of list. But
array have static and dynamic both in nature so these are not flexible
as list.
Int num[5] it means we have created five empty blanks variables in
sequence manner. Its index starts from 0 always.
List provides negative indexing as well. But array does not provide.
Tuple
It is another data type which stores different set of items at single
place.
It is immutable in nature while list is mutable means we can’t alter
the values of tuple.
Tuple does not allow many operations which list provides.
We use parenthesis to create tuple in python.
Like t1 = tuple(‘Naveen’, 34, ‘siwan’ )
It will create empty tuple but we have to pass the value inside it.
It is usually used to store the data related with single entity.
Some common operation we can apply on tuple are:
Count(): it counts the number of values we have passed in tuple.
Dict
This is another data type which primarily stores value in key-pair
method.
We can have no same key for any data it means key must be unique.
We can assign any value for respective keys it may be replicated
data.
Dictionary is used when we want to store the data by mapping to
their key.
We can have example {“45”:”Naveen kumar”}
Set is another type of data type which also uses concept of key-value
pair it can have used for another condition where we want unique
storage of data.
Set stores the value at random location and there is no sequential
access.
To access the data in set and dict we have to use key to use them.
For example d1 = {‘1’:”ABC”,’2’:”BCA”,’3’:”CDD”};
Function overloading
Function overloading is the concept which demonstrate that how can
we use single function to do the multiple task.
Let suppose I want to make a function sum which can be used to add
the values based on given argument.
But it is going to give problem we have to create multiple argument
function which is going to be more tedious and time consuming and it
will also decrease code readability.
We can solve this problem by doing function overloading we can
make a single function but overload it for multiple argument.
We will understand it by coding we have to follow the basic syntax of
python programming in which we will create __init__() method which
is used to initialize the value at compile time.
Below code will describe function overloading example
Code for Function Overloading
class Example:
def __init__(self, a, b):
self.a=a
self.b=b
def show(self):
print(self.a,end=‘ ‘)
print(self.b,end=‘ ‘)
def sum(self,a=None,b=None,c=None):
return a+b+c
First = Example()
First.sum() #it should throw error because no argument is passed
First.sum(1,2,4) # it will give 7 as output
Operator Overloading
Like function overloading we can also overload operator to add the
given type of data. This data type can be user-defined and predefined
as well.
Like take an example I want to add two points with their coordinates
points.
Class Point:
def __init__(self,x,y):
self.x=x
self.y=y
Def show(self):
print({0},{1}.format())
Def __add__(self,other):
x = self.x+other.x
y = self.y+other.y
Example of Operator Overloading
First = Point(2,2)
Second = Point(4,3)
First.__add__(second) #this is the way to call the method
First.show() #it will show the output (6,5)
Like this we can overload many of the operator in similar way in next
slide we will describe more about operator overloading and example
whose operator can be overloaded.
Operator overloading enhances the code readability and reusability
and explore the features of OOP methodology.
In function overloading we have function with different number of
argument and their types we can create huge no of functions.
Operator Overloading
Function Expression Syntax
Adding of Numbers P1.__add__(p2)
Subtracting P1.__sub__(p2)
Multiply P1.__mul__(p2)
Division P1.__div__(p2)
Module P1.__mod__(p2)
Left Shift P1.__lshift__(p2)
Right Shift P1.__rshift__(p2)
AND P1.__and__(p2)
OR P1.__or__(p2)
NOT P1.__not__(p2)
Comparison Operator
Similar to arithmetic operator we can also overload comparison
operator
Some of example are like less than, equal to , greater than, less than
equal to , greater than equal to, etc.
we can overload them by using following syntax:
P1.__lt__(p2)
P1.__lte__(p2)
P1.__gt__(p2)
P1.__gte__(p2)
P1.__eq__(p2)
In next slide we will try to overload one of the comparison operator
related to point similar that addition is performed previously.
Example of Comparison Operator Overloading
Class Point:
Def __init__(self,x=0,y=0):
self.x=x
self.y=y
Def __show__(self):
print({0}{1}.format())
Def __lt__(self,Other):
if self.x>Other.x
return self.x
else
return other.x
Membership and Identity Operator
Membership operator means it will check the presence of a particular
element inside the list and list of items.
It uses in operator to check.
Like we can take an example l1 = [32,54,66,11,23,77]
I want to check is 54 present inside list so I will write 54 in l1 if it will
be present it will give true otherwise return false.
Identity operator checks is the given elements are equal to or not.
Like I want to check equality operator of two elements.
Like we can take an example l1=List[] and l2=List[] if l1 and l2 are
equal it will return true otherwise false.
It will be taken as l1 is l2 if it will give true means it contains same id
of given object.
Function overriding
It looks like the concept of similar to function overloading but in
previous one we don’t have same argument but later one contains
same number and type of argument than only function overriding is
achieved.
We can take an example where parent class just want to hold the
basic structure of any item and child class will describe about its
structure.
So child class implements the mentioned function and writes the
basic functionality so in that time we have to override the function in
child class.
Best example can be Car and Sports Car where both have similar
functionality so we will mention method applyBreak() and override
into child class because child class also have same way to apply
break.
It becomes important when we use inheritance and its basic features
whose can be fulfilled by using their OOP concept.
Overloading and overriding comes under polymorphism concept of
Solving Python Problem
Programs to find the even numbers between given range.
Solution:
count=int(input("Enter last value to decide range")
for i in range(1,count+1):
if(i%2==0):
print(i,end=' ')
We can take an example like count=12 then
Output will be 2,4,6,8,10,12 this is expected output if this program does not
give it means program contains some kind of errors.
Solving Problem in Python
Programs to find the odd numbers between given range.
Solution:
count=int(input("Enter last value to decide range")
for i in range(1,count+1):
if(i%2!=0):
print(i,end=' ')
We can take an example like count=10 then
Output will be 1,3,5,7,9 this is expected output if this program does not give it
means program contains some kind of errors.
Solving Problem in Python
Programs to find the prime numbers between given range.
Solution:
count=int(input("Enter last value to decide range")
for i in range(1,count+1):
if(checkPrime(i)):
print(i,end=' ')
Def checkPrime(x):
For I in range(1,x/2+1):
if(x%i==0):
Numpy and panda in python
These are predefined libraries which are used to store the data
efficiently and access them easily.
We can also use predefined functions which are used to perform
operation on them.
Array is simple example which can be used to store heterogeneous
type of data.
Import numpy as np
Np.array([2,2],dtype=int)
Exception Handling in Python
There are certain situation where we are not able to handle the
problem found in program at compile time.
We can handle those problem at run time we need to write the code
in particular segment where error is expected at run time.
There are mainly three keywords are there we used try, catch, finally,
throw they are used for different purpose.
Try keyword holds the code which is expected to throw the error.
Catch keyword gives genuine message which need to handle
respective kind of error.
By using throw keyword we can throw the kinds of error explicitly.
Finally keyword which is always going to run irrespective of error
occurrence.