0% found this document useful (0 votes)
1 views41 pages

Python File

python file

Uploaded by

roushansingh3698
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views41 pages

Python File

python file

Uploaded by

roushansingh3698
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Introduction

Python is a programming language that is free, open source, object


oriented, and consider highlight labels top about Python language, it’s inbuilt
data structure and dynamic semantics. In competition with dynamic typing and
binding it is ideal for in used for scripting rapid app development and connecting
existing elements. It is simple and has a short learning curve and its readability the
programme low maintenance. Python also has reusable code and programme
modularity thanks to its support of packages and modules. Overall Python library
and interpreter available for free and it is an open-source language.

Features of Python

1. A free open source: Python is an open-source language means it can be


used and distributed freely, anyone can download the source code, make
attachment and distribute their version of the language.
2. Easy to learn: it is a high-level language; syntax is similarly to English making
it simple to read and understand and learn.
3. Vast library support: Python has a fast standard library that offers all
functions need for task dependence.
4. Greater productivity: its simplicity allows developers on solving problems
that we can say that Python boosts productivity (biggest advantage of
Python).
5. Interpreted language: Python executes every individual line in the code one
by one as it’s an interpreted language.
6. Portability: to Run our programme on different programs many languages
need you to modify the code but not seen in Python.
7. Dynamically typed: till you run the code Python is not aware of the variable
type and assign the data type automatically while the code is being
executed.

Data types in Python


Data types are the classification or categorization of data items. It represents
the kind of value that tells what operation can be performed on a particular data.
Since everything is an object in Python programming, data types are actually
classes and variables are instance of these classes. The Python built in data types
are:
 Numeric: in Python these data type represent the data which has numeric
value. Numeric value can be:

 Integer: this value represented by ‘int’ class.


 Float: this value represented by ‘float’ class.
 Complex numbers: this is represented by ‘complex’ class.
 Sequence type: in Python sequence is the ordered collection of similar or
different data types.
 String: these are arrays of bytes representing Unicode
characters.
 List: these are just like the array, declared in other languages
which is ordered collection of data.
 Tuple: this is also an ordered collection of Python objects.
 Boolean: data type with one of the built-in values like true or false. Boolean
objects that are equal to True (are true), and though those equal to False
(are false).
 Sets: in Python set is an unordered collection of data type that is iterable,
mutable and has no duplicate elements.
 Dictionary: in Python dictionary is an unordered collection of data values,
used to store like a map which unlike other data type that hold only single
value has an element. Dictionary holds key value pair.

Python Operators

The operator is a symbol that performs a certain operation between two


operands, according to one definition. In a particular programming language,
operators serve as the foundation upon which logic is constructed in a programme.
The different operators that Python offers are listed here.

 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.

Consider the following table for a detailed explanation of arithmetic 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

hence, a & b = 0011


a | b = 0111
a ^ b = 0100
~ a = 1000
Operator Description
& (binary and) A 1 is copied to the result if both bits in two operands at the same location are 1. If
not, 0 is copied.
| (binary or) The resulting bit will be 0 if both the bits are zero; otherwise, the resulting bit will
be 1.
^ (binary xor) If the two bits are different, the outcome bit will be 1, else it will be 0.

~ (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:

The assessment of expressions to make decisions typically makes use of the


logical operators. The following logical operators are supported by Python.
Operator Description

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:

The membership of a value inside a Python data structure can be verified


using Python membership operators. The result is true if the value is in the data
structure; otherwise, it returns false.
Operator Description
in If the first operand cannot be found in the second operand, it is evaluated to be true
(list, tuple, or dictionary).

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.

Structure of a Python Program

In this portion we would come to know about the proper structuring and
formatting in Python language.

 Python statement: In general, the interpreter reads and executes the


statements line by line that is sequentially. There are some statements that
mostly python statements are written in such a format that one statement
is only written in a single line. The interpreter considers new line characters
as the terminator of one instruction.
 Multiple statements or line: We can also write multiple statements online
but it is not a good practice as it reduces the reusability and readability of
the code. Try to avoid writing multiple statements in a single line but still
we can write multiple line with the help of ‘;’.
 Line continuation: There are two types of line continuation:
i. Implicit
ii. Explicit
 Comments: Writing comments in the code are very important and they help
in code readability and also talk more about the code.
 White spaces: the most common white space characters are and mostly not
required by the python interpreter.
 White space as indentation: python syntax is quite easy but still we have to
take some care in writing the code. Indentation is used in writing python
codes.

Algorithm & Flowchart

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.

Addition of two numbers:

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:

x=int(input('Enter first value'))


y=int(input('Enter second value'))
z = x+y
print("sum=",z)

Output:

Enter first value 20


Enter second value 20
sum= 40

Largest of two numbers:

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:

num1 = float(input("Enter first number: "))


num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))

if (num1 >= num2) and (num1 >= num3):


largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3

print("The largest number is", largest)

Output:

Enter first number: 54


Enter second number: 85
Enter third number: 35
The largest number is: 85

Calculate area of a triangle

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

Check whether a number is even or odd

Program:
'''Determining odd and even number using function'''

def odd_even(n):
if n%2==0:
return 0
else:
return 1

num=int(input(" Enter any whole number:: "))


flag=odd_even(num)
if flag==0:
print(" ",num," is an even number.")
else:
print(" ",num," is an odd number.")
Output:
Enter any whole number:: 53
53 is an odd number.

Find the greater number from three


numbers

Program:
'''Program to calculate the largest number among three numbers'''

num1 = float(input("Enter first number:: "))


num2 = float(input("Enter second number:: "))
num3 = float(input("Enter third number:: "))
if (num1 >= num2) and (num1 >= num3):
largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3

print("The largest number is", largest)

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

num=int(input(" Enter any number:: "))


flag=amstrong(num)
if flag==0:
print(" ",num," is an amstrong number.")
else:
print(" ",num," is not an amstrong number.")

Output:

Enter any number:: 153


153 is an amstrong number.
Determine a entered character is vowel
or not

Program:
'''Program to check if a character is vowel or not'''

ch = input("Enter a character: ")


if(ch=='A' or ch=='a' or ch=='E' or ch =='e' or ch=='I'
or ch=='i' or ch=='O' or ch=='o' or ch=='U' or ch=='u'):
print(ch," is a Vowel")
else:
print(ch," is a Consonant")

Output:

Enter a character: z
z is a Consonant

Enter the marks of a student in four subjects then


calculate the total and aggregate and display obtained
by the student.

Program:

'''. If the student score and


aggregate greater than 75% than the grade is distinction. If aggregate 60
>= and < 75 than the grade is first division. If aggregate is 50 >= and < 60
then the grade is second division. If aggregate 40 >= and < 50 grade is
third division else the grade is fail.'''

n1=float(input(" Enter the marks of the 1st subject:: "))


n2=float(input(" Enter the marks of the 2nd subject:: "))
n3=float(input(" Enter the marks of the 3rd subject:: "))
n4=float(input(" Enter the marks of the 4th subject:: "))
total=n1+n2+n3+n4
percentage=total/4
if percentage>=75:
print(" The student get distinction.")
elif percentage>=60 and percentage<75:
print(" The student get first division.")
elif percentage>=50 and percentage<60:
print(" The student get second division.")
elif percentage>=40 and percentage<50:
print(" The student get third division.")
else:
print(" The student has failed to qualify.")

Output:

Enter the marks of the 1st subject:: 65


Enter the marks of the 2nd subject:: 69
Enter the marks of the 3rd subject:: 72
Enter the marks of the 4th subject:: 61
The student get first division.

Calculate Sum of its Digits

Program:
'''Program to find sum of digits'''

def sum_digits(n):
sum=0
for digit in str(n):
sum+=int(digit)
return sum

num=int(input(" Enter the number:: "))


sum=sum_digits(num)
print(" Sum of digits is= ",sum)
Output:

Enter the number:: 5641


Sum of digits is= 16

Calculate GCD using recursion

Program:

‘’’Calculate GCD using recursion'''

def gcd(a, b):


if a == b:
return a
elif a < b:
return gcd(b, a)
else:
return gcd(b, a - b)

a =int(input(" Entre the first number:: "))


b =int(input(" Enter the second number:: "))
print(" The result is= ",gcd(a, b))

Output:

Entre the first number:: 7


Enter the second number:: 689
The result is= 1
Find number is a Palindrome number or
not

Program:
'''Program to check a number is palindrome or not'''

num=int(input("Enter any number::"))


temp=num
rev=0
while(num>0):
rem=num%10
rev=rev*10+rem
num=num//10
if(temp==rev):
print("This value is a palindrome number.")
else:
print("This value is not a palindrome number.")

Output:
Enter any number:: 56794
This value is not a palindrome number.

Swap two number using function

Program:
'''Swap two numbers'''

def swap(a,b):
temp=a
a=b
b=temp
return(a,b)

x=int(input(" Enter the value of x:: "))


y=int(input(" Enter the value of y:: "))
x,y=swap(x,y)
print(" The result after the swapping.")
print(" Value of x:", x)
print(" Value of y:", y)

Output:

Enter the value of x:: 78


Enter the value of y:: 96
The result after the swapping.
Value of x: 96
Value of y: 78

Find whether a number is a Neon number


or not

Program:
'''Evaluate neon number.'''

num=int(input("Enter a number:: "))


sqr=num**2
sum_of_digit=0
while sqr>0:
sum_of_digit=sum_of_digit+sqr%10
sqr=sqr//10

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:

'''Print fibonacci serise'''

def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))

nterms = int(input(" How many terms:: "))


if nterms <= 0:
print(" Plese enter a positive integer! ")
else:
print("Fibonacci sequence: ")
for i in range(nterms):
print(recur_fibo(i))

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:

'''Sum of n natural numbers.'''

num=int(input(" Enter the limit:: "))


if num<0:
print(" Enter a positive number")
else:
sum=0
while(num>0):
sum+=num
num-=1
print("The sum is", sum)

Output:

Enter the limit:: 20


The sum is 210

Pattern Printing

Pattern-1:

Program:

height=int(input(" Enter the height:: "))


for i in range(1,height+1):
for k in range(height,i,-1):
print(" ",end=' ')
for j in range(1,i+1):
print(j,end=' ')
for l in range(i-1,0,-1):
print(l,end=' ')
print()
Output:

Enter the height:: 7


1
121
12321
1234321
123454321
12345654321
1234567654321

Pattern-2:

Program:

n=int(input(" Enter the height:: "))


i=1;j=0
while(i<=n):
while(j<=i-1):
print("* ",end="")
j+=1
print("\r")
j=0;i+=1

Output:

Enter the height:: 8


*
**
***
****
*****
******
*******
********
Pattern-3:

Program:

n=int(input(" Enter the range:: "))


for i in range(n):
for j in range(i+1):
print(chr(j + 65), end=" ")
print()

Output:

Enter the range:: 9


A
AB
ABC
ABCD
ABCDE
ABCDEF
ABCDEFG
ABCDEFGH
ABCDEFGHI

Calculate factorial using recursion

Program:

'''Factorial using recursion'''

def factorial(n):
if n == 1:
return n
else:
return n*factorial(n-1)

num=int(input(" Enter a number:: "))


if num<0:
print(" Sorry, factorial does not exist for negative numbers")
elif num==0:
print(" The factorial of 0 is 1")
else:
print(" The factorial of",num,"is",factorial(num))

Output:

Enter a number:: 5
The factorial of 5 is 120

Sum of series

Serise-1
Program:

'''Sum the series 1/1! + 4/2! + 27/3! + ..... + n/n!'''

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:

Enter the last term:: 9


The sum of the serise is= 2.718278769841270
Serise-2
Program:

'''Sum the series -- 1/1^2 + 1/2^2 +.....1/n^2'''

term=int(input(" Enter the last term:: "))


sum=0
c=1
while c<=term:
sum+=(1/(c**2))
c+=1
print(" The sum of the serise is= ",sum)

Output:

Enter the last term:: 8


The sum of the serise is= 1.527422052154195

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:

List is:: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


List after updation is:: [1, 2, 3, 4, 5, 100, 7, 8, 9, 10]
List after appending a value is:: [1, 2, 3, 4, 5, 100, 7, 8, 9, 10, 200]
List after deleting a value is:: [1, 2, 3, 5, 100, 7, 8, 9, 10, 200]

Tuple in Python

Definition: Python Tuple is a collection of objects separated by commas. In


some ways, a tuple is similar to a list in terms of indexing, nested objects, and
repetition but a tuple is immutable, unlike lists which are mutable. To create a
tuple we will use () operators.
Program:
tup1=('a','b',78,1.23)
tup2=('d',78)
print("\n The 1st tuple is:: ",tup1)
print("\n The 2nd tuple is:: ",tup2)
print("\n \n *****Now elements from 1st tuple*****")
print("\n First element:: ",tup1[0])
print("\n printing elements from 2nd till 3rd:: ",tup1[1:3])
print("\n Printing elements from 3rd element:: ",tup1[2:])
print("\n Repeating the tuple:: ",tup1*2)
print("\n \n *****Concatinating 1st and 2nd tuple*****")
print("\n ",tup1+tup2)

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

Definition: A Set is an unordered collection data type that is iterable, mutable,


and has no duplicate elements. Set are represented by { }. 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. This is based on a data
structure known as a hash table. Since sets are unordered, we cannot access items
using indexes as we do in lists.

Program:
people = {"Rohit", "Arijit", "Monodipto"}

print("People:", end = " ")


print(people)

people.add("Amlan")

for i in range(1, 6):


people.add(i)

print("\nSet after adding element:", end = " ")


print(people)

Output:
People: {'Monodipto', 'Arijit', 'Rohit'}
Set after adding element: {'Monodipto', 1, 2, 'Arijit', 'Rohit', 3, 4, 'Amlan', 5}

Dictionary in python

Definition: Dictionary in Python is a collection of keys values, used to store data


values like a map, which, unlike other data types which hold only a single value
as an element. In Python, a dictionary can be created by placing a sequence of
elements within curly {} braces, separated by ‘comma’. Dictionary holds pairs of
values, one being the Key and the other corresponding pair element being its “Key
: value”. Values in a dictionary can be of any data type and can be duplicated,
whereas keys can’t be repeated and must be immutable.
Program:

student_id = {111: "Eric", 112: "Kyle", 113: "Butters"}

print("Initial Dictionary: ")


for i in student_id:
print(i, '->', student_id[i])
student_id[112] = "Stan"
print("Updated Dictionary: ",)
for i in student_id:
print(i, '->', student_id[i])

Output:

Initial Dictionary:
111 -> Eric
112 -> Kyle
113 -> Butters
Updated Dictionary:
111 -> Eric
112 -> Stan
113 -> Butters

Stack in python

Definition: A stack is a linear data structure where data is arranged objects on


over another. It stores the data in LIFO (Last in First Out) manner. The data is
stored in a similar order as plates are arranged one above another in the kitchen.
The simple example of a stack is the Undo feature in the editor. The Undo feature
works on the last event that we have done.
We always pick the last plate from the stack of the plate. In stack, the new
element is inserted at the one end and an element can be removed only that end.
We can perform the two operations in the stack - PUSH and POP. The PUSH
operation is when we add an element and the POP operation is when we remove
an element from the stack.
Program:

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:

Original Stack is:: [1, 2, 3, 4, 5, 6]


Stack after push operation is:: [1, 2, 3, 4, 5, 6, 7]
Stack after pop operation:: [1, 2, 3, 4, 5, 6]
Value obtain after peek operation:: 6

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

Definition: Linear Search is defined as a sequential search algorithm that starts


at one end and goes through each element of a list until the desired element is
found, otherwise the search continues till the end of the data set. It is the easiest
searching algorithm.
Program:

def linear_Search(list1, n, key):

for i in range(0, n):


if (list1[i] == key):
return i
return -1

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:

The list is:: [1, 3, 5, 4, 7, 9]


Enter the element you want to search:: 4
Element found at index: 4

Binary Search

Definition: A binary search is an algorithm to find a particular element in the


list. Suppose we have a list of thousand elements, and we need to get an index
position of a particular element. We can find the element's index position very fast
using the binary search algorithm.
There are many searching algorithms but the binary search is most popular
among them.
The elements in the list must be sorted to apply the binary search algorithm. If
elements are not sorted then sort them first.
Program:

def binary_search(arr, low, high, x):


if high>=low:
mid=(high + low) // 2
if arr[mid]==x:
return mid
elif arr[mid]>x:
return binary_search(arr, low, mid - 1, x)
else:
return binary_search(arr, mid + 1, high, x)
else:
return -1

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:

def selectionSort(array, size):

for ind in range(size):


min_index = ind

for j in range(ind + 1, size):


# select the minimum element in every iteration
if array[j] < array[min_index]:
min_index = j
# swapping the elements to sort the array
(array[ind], array[min_index]) = (array[min_index], array[ind])

arr = [-2, 45, 0, 11, -9,88,-97,-202,747]


print(" The array before sort: ",arr)
size = len(arr)
selectionSort(arr, size)
print(" The array after sorting in Ascending Order by selection sort is: ",arr)

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

Definition: A Bubble sort is an easy algorithm among the various sorting


algorithms. We learn it as a first sorting algorithm. It is easy to learn and highly
intuitive. It can be easy to implement into the code, which is much beneficial for
beginner software developers. But it is the worst algorithm for sorting the elements
in every except because it checks every time the array is sorted or not.

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:

Enter the length of the array:: 5


Element 1:: 85
Element 2:: 72
Element 3:: 36
Element 4:: 1000
Element 5:: 8
Sorted array is::
8 36 72 85 1000

Insertion Sort

Definition: The Insertion sort is a straightforward and more efficient algorithm


than the previous bubble sort algorithm. The insertion sort algorithm concept is
based on the deck of the card where we sort the playing card according to a
particular card. It has many advantages, but there are many efficient algorithms
available in the data structure.
The insertion sort implementation is easy and simple because it's generally taught
in the beginning programming lesson. It is an in-place and stable algorithm that
is more beneficial for nearly-sorted or fewer elements.
The insertion sort algorithm is not so fast because of it uses nested loop for sort the
elements.

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:

The array before sorting: [12, 11, 13, 5, 6]


The array after sorting: [5, 6, 11, 12, 13]

Class & Object in python

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

r=float(input(" Enter the radius of the circle:: "))


ob=Circle(r)
print(" Area of the circle is= ",ob.area())
print(" The circumference of the circle is= ",ob.circumference())

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

Definition: Inheritance is an important aspect of the object-oriented paradigm.


Inheritance provides code reusability to the program because we can use an
existing class to create a new class instead of creating it from scratch.
In inheritance, the child class acquires the properties and can access all the data
members and functions defined in the parent class. A child class can also provide
its specific implementation to the functions of the parent class.
In python, a derived class can inherit base class by just mentioning the base in the
bracket after the derived class name. Consider the following syntax to inherit a
base class into the derived class.

There are 3 types of inheritance in Python:


 Single inheritance: When a child class inherits from only one parent
class, it is called single inheritance. We saw an example above.
 Multilevel 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.
 Multiple inheritance: Python provides us the flexibility to inherit
multiple base classes in the child class.
Program:
class Person:
def __init__(self,name,age):
self.name=name
self.age=age
def display(self):
print(" Name:: ",self.name)
print(" Age:: ",self.age)

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

Operator Overloading in python

Definition: The operator overloading in Python means provide extended


meaning beyond their predefined operational meaning. Such as, we use the "+"
operator for adding two integers as well as joining two strings or merging two lists.
We can achieve this as the "+" operator is overloaded by the "int" class and "str"
class. The user can notice that the same inbuilt operator or function is showing
different behaviour for objects of different classes. This process is known as
operator overloading.

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

# adding two objects


def __add__(self, o):
return self.a + o.a
ob1 = A(69)
ob2 = A(33)
ob3 = A("Rohit")
ob4 = A(" Das")

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:

# initialize the amount variable


marks = 10000

# perform division with 0


a = marks / 0
print(a)
Output:

Traceback (most recent call last):


File "<string>", line 5, in <module>
ZeroDivisionError: division by zero

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:

num=int(input(" Enter the numerator:: "))


dino=int(input(" Enter the denominator:: "))

try:
quo=num/dino
print(" Quotient:: ",quo)

except ZeroDivisionError:
print(" Denominator cannot be zero.")
Output:

Enter the numerator:: 52


Enter the denominator:: 0
Denominator cannot be zero.

Example2:
Program:

a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))

# Throws error since there are only 3 elements in array


print ("Fourth element = %d" %(a[3]))

except:
print ("An error occurred")

Output:

Second element = 2
An error occurred

You might also like