Python File
Python File
Features of Python
Python Operators
Arithmetic operators
Comparison operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Arithmetic Operators:
Arithmetic operations between two operands are carried out using
arithmetic operators. It includes the exponent (**) operator as well as the +
(addition), - (subtraction), * (multiplication), / (divide), % (reminder), and // (floor
division) operators.
Operator Description
+ (Addition) It is used to add two operands. For example, if a = 10, b = 10 => a+b = 20
- (Subtraction) It is used to subtract the second operand from the first operand. If the first operand
/ (divide) It returns the quotient after dividing the first operand by the second operand. For
example, if a = 20, b = 10 => a/b = 2.0
* It is used to multiply one operand with the other. For example, if a = 20, b = 4 => a *
(Multiplication) b = 80
% (reminder) It returns the reminder after dividing the first operand by the second operand. For
example, if a = 20, b = 10 => a%b = 0
** (Exponent) As it calculates the first operand's power to the second operand, it is an exponent
operator.
// (Floor It provides the quotient's floor value, which is obtained by dividing the two
division) operands.
Comparison operator:
Comparison operators compare the values of the two operands and return
a true or false Boolean value in accordance. The following table lists the
comparison operators.
Operator Description
== If the value of two operands is equal, then the condition becomes true.
!= If the value of two operands is not equal, then the condition becomes true.
<= The condition is met if the first operand is smaller than or equal to the second
operand.
>= The condition is met if the first operand is greater than or equal to the second
operand.
> If the first operand is greater than the second operand, then the condition becomes
true.
< If the first operand is less than the second operand, then the condition becomes
true.
Assignment Operators:
The right expression's value is assigned to the left operand using the
assignment operators. The following table provides a description of the assignment
operators.
Operator Description
= It assigns the value of the right expression to the left operand.
+= By multiplying the value of the right operand by the value of the left operand, the
left operand receives a changed value. For example, if a = 10, b = 20 => a+ = b will be
equal to a = a+ b and therefore, a = 30.
-= It decreases the value of the left operand by the value of the right operand and
assigns the modified value back to left operand. For example, if a = 20, b = 10 => a-
= b will be equal to a = a- b and therefore, a = 10.
*= It multiplies the value of the left operand by the value of the right operand and
assigns the modified value back to then the left operand. For example, if a = 10, b =
20 => a* = b will be equal to a = a* b and therefore, a = 200.
%= It divides the value of the left operand by the value of the right operand and assigns
the reminder back to the left operand. For example, if a = 20, b = 10 => a % = b will
be equal to a = a % b and therefore, a = 0.
**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign 4**2 =
16 to a.
//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign 4//3 = 1
to a.
Bitwise Operators:
The two operands' values are processed bit by bit by the bitwise operators.
Consider the case below.
For example,
if a = 7
b=6
then, binary (a) = 0111
binary (b) = 0110
~ (negation) The operand's bits are calculated as their negations, so if one bit is 0, the next bit
will be 1, and vice versa.
<< (left shift) The number of bits in the right operand is multiplied by the leftward shift of the
value of the left operand.
>> (right shift) The left operand is moved right by the number of bits present in the right operand.
Logical Operators:
and The condition will also be true if the expression is true. If the two expressions a and b
are the same, then a and b must both be true.
or The condition will be true if one of the phrases is true. If a and b are the two expressions,
then an or b must be true if and is true and b is false.
not If an expression a is true, then not (a) will be false and vice versa.
Membership Operators:
not in If the first operand is not present in the second operand, the evaluation is true (list,
tuple, or dictionary).
Identity Operators:
Operator Description
is If the references on both sides point to the same object, it is determined to be true.
is not If the references on both sides do not point at the same object, it is determined to be
true.
Module
Python module is a fine containing Python definition and statements. A
module can define function, classes and variables. A module can also include
runnable code. Grouping related code into a module makes the code easier to
understand and use it also makes the code logically organised.
Python Path
Python path is a special environment variable that provides guidance to
the Python interpreter about where to find various libraries and applications. It is
similar to the PATH environment variable in other languages, such as C and Java,
but has additional directories for Python modules.
In this portion we would come to know about the proper structuring and
formatting in Python language.
Flowchart:
A flowchart is a type of diagram that represents a workflow or process. A
flowchart can also be defined as a diagrammatic representation of an algorithm,
a step-by-step approach to solving a task. The flowchart shows the steps as boxes
of various kinds, and their order by connecting the boxes with arrows.
Algorithm:
In mathematics and computer science, an algorithm is a finite sequence of
rigorous instructions, typically used to solve a class of specific problems or to
perform a computation. Algorithms are used as specifications for performing
calculations and data processing.
Flowchart:
Algorithm:
Start
Step1: Take two numeric values from the user
Step2: Verify both values are numeric
Step3: Add both values and store result into a new variable
Step4: Display the result
Stop
Program:
Output:
Flowchart:
Algorithm:
Start
Step 1: Initialise three numbers a, b, c.
Step 2: If a is higher than b and c then, print a.
Step 3: Else if b is greater than c and a then, print b.
Step 4: Else if c is greater than a and b then, print c.
Step 5: Else print any number.
Stop
Program:
Output:
Program:
'''Calculate the area of a triangle using heron's formula.'''
'''Heron's formula:: (S*(S-A)*(S-B)*(S-C))**0.5'''
a=float(input(" Enter the first side of the triangle:: "))
b=float(input(" Enter the second side of the triangle:: "))
c=float(input(" Enter the third side of the triangle:: "))
s=(a+b+c)/2
area=((s*(s-a)*(s-b)*(s-c))**0.5)
print(" The area of the triangle is= ",area)
Output:
Enter the first side of the triangle:: 52.3
Enter the second side of the triangle:: 45.6
Enter the third side of the triangle:: 32.65
The area of the triangle is= 737.3263492106023
Program:
'''Determining odd and even number using function'''
def odd_even(n):
if n%2==0:
return 0
else:
return 1
Program:
'''Program to calculate the largest number among three numbers'''
Output:
Enter first number:: 85
Enter second number:: 53
Enter third number:: 180
The largest number is 180
Find a number is an Armstrong number
Program:
'''Program to check a number is Amstrong or not.'''
def amstrong(n):
str_n=str(n)
n_len=len(str_n)
cp_n=n
sum=0
while n>0:
r=n%10
sum=sum+(r**n_len)
n=n//10
if sum==cp_n:
return 0
else:
return 1
Output:
Program:
'''Program to check if a character is vowel or not'''
Output:
Enter a character: z
z is a Consonant
Program:
Output:
Program:
'''Program to find sum of digits'''
def sum_digits(n):
sum=0
for digit in str(n):
sum+=int(digit)
return sum
Program:
Output:
Program:
'''Program to check a number is palindrome or not'''
Output:
Enter any number:: 56794
This value is not a palindrome number.
Program:
'''Swap two numbers'''
def swap(a,b):
temp=a
a=b
b=temp
return(a,b)
Output:
Program:
'''Evaluate neon number.'''
if num==sum_of_digit:
print(" ",num," is a neon number")
else:
print(" ",num," is not a neon number")
Output:
Enter a number:: 9
9 is a neon number
Program to calculate fibonacci series
Program:
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
Output:
How many terms:: 10
Fibonacci sequence:
0
1
1
2
3
5
8
13
21
34
Find sum of first n natural numbers
Program:
Output:
Pattern Printing
Pattern-1:
Program:
Pattern-2:
Program:
Output:
Program:
Output:
Program:
def factorial(n):
if n == 1:
return n
else:
return n*factorial(n-1)
Output:
Enter a number:: 5
The factorial of 5 is 120
Sum of series
Serise-1
Program:
def factorial(n):
if n == 1:
return n
else:
return n*factorial(n-1)
term=int(input(" Enter the last term:: "))
sum=0
c=1
while c<=term:
sum+=(c/factorial(c))
c+=1
print(" The sum of the serise is= ",sum)
Output:
Output:
List in Python
Definition: Python Lists are just like dynamically sized arrays, declared in other
languages (vector in C++ and ArrayList in Java). In simple language, a list is a
collection of things, enclosed in [ ] and separated by commas. Lists are the simplest
containers that are an integral part of the Python language. Lists need not be
homogeneous always which makes it the most powerful tool in Python. A single
list may contain Data Types like Integers, Strings, as well as Objects. Lists are
mutable, and hence, they can be altered even after their creation.
Program:
num_list=[1,2,3,4,5,6,7,8,9,10]
print(" List is:: ",num_list)
num_list[5]=100
print(" List after updation is:: ",num_list)
num_list.append(200)
print(" List after appending a value is:: ",num_list)
num_list.pop(3)
print(" List after deleting a value is:: ",num_list)
Output:
Tuple in Python
Output:
The 1st tuple is:: ('a', 'b', 78, 1.23)
The 2nd tuple is:: ('d', 78
*****Now elements from 1st tuple*****
First element:: a
printing elements from 2nd till 3rd:: ('b', 78)
Printing elements from 3rd element:: (78, 1.23)
Repeating the tuple:: ('a', 'b', 78, 1.23, 'a', 'b', 78, 1.23)
*****Concatinating 1st and 2nd tuple*****
('a', 'b', 78, 1.23, 'd', 78)
Sets in Python
Program:
people = {"Rohit", "Arijit", "Monodipto"}
people.add("Amlan")
Output:
People: {'Monodipto', 'Arijit', 'Rohit'}
Set after adding element: {'Monodipto', 1, 2, 'Arijit', 'Rohit', 3, 4, 'Amlan', 5}
Dictionary in python
Output:
Initial Dictionary:
111 -> Eric
112 -> Kyle
113 -> Butters
Updated Dictionary:
111 -> Eric
112 -> Stan
113 -> Butters
Stack in python
stack=[1,2,3,4,5,6]
print("\n Original Stack is:: ",stack)
stack.append(7)
print("\n Stack after push operation is:: ",stack)
stack.pop()
print("\n Stack after pop operation:: ",stack)
last_element_index=len(stack)-1
print("\n Value obtain after peek operation:: ",stack[last_element_index])
Output:
Queue in python
Definition: A queue is a linear type of data structure used to store the data in
a sequentially. The concept of queue is based on the FIFO, which means "First in
First Out". It is also known as "first come first severed". The queue has the two ends
front and rear. The next element is inserted from the rear end and removed from
the front end.
Program:
queue=[1,2,3,4,5,6]
print("\n Original Queue is:: ",queue)
queue.append(7)
print("\n Queue after insertion:: ",queue)
queue.pop(0)
print("\n Queue after deletion:: ",queue)
last_element_index=len(queue)-1
print("\n Value obtain after peek operation:: ",queue[last_element_index])
Output:
queue=[1,2,3,4,5,6]
print("\n Original Queue is:: ",queue)
queue.append(7)
print("\n Queue after insertion:: ",queue)
queue.pop(0)
print("\n Queue after deletion:: ",queue)
last_element_index=len(queue)-1
print("\n Value obtain after peek operation:: ",queue[last_element_index])
Linear Search
list1 = [1 ,3, 5, 4, 7, 9]
print(" The list is:: ", list1)
key = int(input(" Enter the element you want to search:: "))
n = len(list1)
res = linear_Search(list1, n, key)
if(res == -1):
print("Element not found")
else:
print("Element found at index: ", res+1)
Output:
Binary Search
arr =[]
leng=int(input(" Enter the length of the array:: "))
i=0
while i<leng:
n=int(input(" Element "+str(i+1)+":: "))
arr.append(n)
i+=1
x=int(input(" Enter the element to find:: "))
arr.sort()
result=binary_search(arr, 0, len(arr)-1, x)
if result!=-1:
print("Element is present at index", str(result))
else:
print("Element is not present in array")
Output:
Enter the length of the array:: 8
Element 1:: 85
Element 2:: 69
Element 3:: 13
Element 4:: 188
Element 5:: 74
Element 6:: 2
Element 7:: 58
Element 8:: 986
Enter the element to find:: 188
Element is present at index 6
Selection Sort
Definition: The selection sort algorithm sorts an array by repeatedly finding the
minimum element (considering ascending order) from unsorted part and putting
it at the beginning. The algorithm maintains two subarrays in a given array.
Program:
Output:
The array before sort: [-2, 45, 0, 11, -9, 88, -97, -202, 747]
The array after sorting in Ascending Order by selection sort is: [-202, -97,
-9, -2, 0, 11, 45, 88, 747]
Bubble Sort
Program:
def bubbleSort(arr):
n = len(arr)
swapped = False
for i in range(n-1):
for j in range(0, n-i-1):
if arr[j] > arr[j + 1]:
swapped = True
arr[j], arr[j + 1] = arr[j + 1], arr[j]
if not swapped:
return
arr=[]
leng=int(input(" Enter the length of the array:: "))
i=0
while i<leng:
n=int(input(" Element "+str(i+1)+":: "))
arr.append(n)
i+=1
bubbleSort(arr)
print("Sorted array is:: ", end=" ")
for i in range(len(arr)):
print("% d" % arr[i], end=" ")
Output:
Insertion Sort
Program:
def insertionSort(arr):
if (n := len(arr)) <= 1:
return
for i in range(1, n):
key = arr[i]
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
arr = [12, 11, 13, 5, 6]
print(" The array before sorting: ",arr)
insertionSort(arr)
print(" The array after sorting: ",arr)
Output:
Definition: There are 2 main aspects of oop. In fact a class is the basic building
block in Python. A class creates a new type and object is an instance of the class.
Classes provides a blueprint or a template using which objects are created. In fact
in Python everything is an object or an instance of same class.
Program:
class Circle:
pi=3.14
def __init__(self,radius):
self.radius=radius
def area(self):
return Circle.pi*self.radius*self.radius
def circumference(self):
return 2*Circle.pi*self.radius
Output:
Enter the radius of the circle:: 5.6
Area of the circle is= 98.4704
The circumference of the circle is= 35.168
Inheritance in python
class Teacher(Person):
def __init__(self,name,age,exp,r_area):
Person.__init__(self,name,age)
self.exp=exp
self.r_area=r_area
def displaydata(self):
Person.display(self)
print(" Experience:: ",self.exp)
print(" Research area:: ",self.r_area)
class Student(Person):
def __init__(self,name,age,course,marks):
Person.__init__(self,name, age)
self.course=course
self.marks=marks
def dispalydata(self):
Person.display(self)
print(" Course:: ",self.course)
print(" Marks:: ",self.marks)
T=Teacher("Jaya",43,20,"Recommender System")
print("\n \n ****TEACHER****")
T.displaydata()
print("\n \n ****STUDENT****")
S=Student("Rohit",20,"BCA",98)
S.dispalydata()
Output:
****TEACHER****
Name:: Jaya
Age:: 43
Experience:: 20
Research area:: Recommender System
****STUDENT****
Name:: Rohit
Age:: 20
Course:: BCA
Marks:: 98
Program-1:
class Complex:
def __init__(self):
self.real=0
self.img=0
def setvalue(self,real,img):
self.real=real
self.img=img
def __add__(self,c):
temp=Complex()
temp.real=self.real+c.real
temp.img=self.img+c.img
return temp
def display(self):
print(" ( ",self.real,"+",self.img,"i )")
c1=Complex()
c1.setvalue(1,2)
c2=Complex()
c2.setvalue(3,4)
c3=Complex()
c3=c1+c2
print(" RESULT::")
c3.display()
Output:
RESULT:: ( 4 + 6 i )
Program-2:
class A:
def __init__(self, a):
self.a = a
print(ob1 + ob2)
print(ob3 + ob4)
print(A.__add__(ob1 , ob2))
print(A.__add__(ob3,ob4))
print(ob1.__add__(ob2))
print(ob3.__add__(ob4))
Output:
102
Rohit Das
102
Rohit Das
102
Rohit Das
Exception in python
Exception or Error: Error in Python can be of two types i.e. Syntax errors and
Exceptions. Errors are the problems in a program due to which the program will
stop the execution. On the other hand, exceptions are raised when some internal
events occur which changes the normal flow of the program.
Types of errors seen in python: There are two types of Error occurs in
python-
I. Syntax errors
II. Logical errors (Exceptions)
Syntax errors: When the proper syntax of the language is not followed then
a syntax error is thrown.
Example:
# initialize the amount variable
amount = 10000
# check that You are eligible to
# purchase Dsa Self Paced or not
if(amount>2999)
print("You are eligible to purchase Dsa Self Paced")1
Output:
File "<string>", line 6
if(amount>2999)
^
SyntaxError: expected ':'
Logical Errors(Exception): When in the runtime an error that occurs after
passing the syntax test is called exception or logical type. For example, when we
divide any number by zero then the ZeroDivisionError exception is raised, or when
we import a module that does not exist then ImportError is raised.
Example:
Exception Handilng: Try and except statements are used to catch and
handle exceptions in Python. Statements that can raise exceptions are kept inside
the try clause and the statements that handle the exception are written inside
except clause.
Example1:
Program:
try:
quo=num/dino
print(" Quotient:: ",quo)
except ZeroDivisionError:
print(" Denominator cannot be zero.")
Output:
Example2:
Program:
a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))
except:
print ("An error occurred")
Output:
Second element = 2
An error occurred