You are on page 1of 32

PYTHON (TERM WORK)

SUBJECT CODE: 2018311


(3rd Semester)

GOVERNMENT POLYTECHNIC
BHOJPUR, BIHAR

Name of Student:
Roll No:
Branch:
Session:
Date of Submission:
A
Term Work File
On
Python
Submitted
For
Diploma in Mechanical Engineering
At

Government Polytechnic, Bhojpur


Submitted To Submitted By
Deependra Bhushan
Lecturer, CSE
G.P. Bhojpur
INDEX
Sl. Practical Name Page Date /
No No Remark
Python Term Work
Basic Introduction:

Python is a general purpose, dynamic, high-level, and interpreted programming language. It


supports Object Oriented programming approach to develop applications. It is simple and easy to
learn and provides lots of high-level data structures. Python is a high-level, interpreted,
interactive and object-oriented scripting language.

Python is designed to be highly readable. It uses English keywords frequently whereas the other
languages use punctuations. It has fewer syntactical constructions than other
languages

Features:

 Python is Interpreted: Python is processed at runtime by the interpreter. You do


not need to compile your program before executing it. This is similar to PERL and
PHP.
 Python is Interactive: You can actually sit at a Python prompt and interact with
the interpreter directly to write your programs.
 Python is Object-Oriented: Python supports Object-Oriented style or technique
of programming that encapsulates code within objects.
 Python is a Beginner's Language: Python is a great language for the beginner level
programmers and supports the development of a wide range of applications from simple
text processing to WWW browsers to games.
 Easy-to-learn: Python has few keywords, simple structure, and a clearly defined syntax.
This allows a student to pick up the language quickly
 Easy-to-read and maintain: Python code is more clearly defined and visible to the eyes
and python's source code is fairly easy-to-maintain.
 A broad standard library: Python's bulk of the library is very portable and cross
platform compatible on UNIX, Windows, and Macintosh.
 Interactive Mode: Python has support for an interactive mode, which allows interactive
testing and debugging of snippets of code.
 Portable and extendable: Python can run on a wide variety of hardware platforms and
has the same interface on all platforms. You can add low-level modules to the Python
interpreter. These modules enable programmers to add to or customize their tools to be
more efficient.
 Databases: Python provides interfaces to all major commercial databases.
 GUI Programming: Python supports GUI applications that can be created and ported to
many system calls, libraries and windows systems, such as Windows MFC, Macintosh,
and the X Window system of Unix.
Python History: Python was invented by Guido van Rossum in 1991 at CWI in Netherland. The
idea of Python programming language has taken from the ABC programming language or we
can say that ABC is a predecessor of Python language. Guido van Rossum was a fan of the
popular BBC comedy show of that time, "Monty Python's Flying Circus". So he decided to pick
the name Python for his newly created programming language. Python has the vast community
across the world and releases its version within the short period.

Why learn Python?

Python provides many useful features to the programmer. These features make it most popular
and widely used language. We have listed below few-essential feature of Python.

 Easy to use and Learn


 Expressive Language
 Interpreted Language
 Object-Oriented Language
 Open Source Language
 GUI Programming Support and Wide Range of Libraries and Frameworks
 Dynamic Memory Allocation

Where is Python used Python is a general-purpose, popular programming language and it is


used in almost every technical field. The various areas of Python use are given below.

 Data Science And Date Mining


 Desktop Applications
 Console-based Applications
 Mobile Applications
 Software Development
 Artificial Intelligence
 Web Applications
 Enterprise Applications
 Machine Learning
 Computer Vision or Image Processing Applications and Speech Recognitions

Python Popular Frameworks and Libraries: Python has wide range of libraries and
frameworks widely used in various fields such as machine learning, artificial intelligence, web
applications, etc. We define some popular frameworks and libraries of Python as follows.

 Web development (Server-side) - Django Flask, Pyramid, CherryPy


 GUIs based applications - Tk, PyGTK, PyQt, PyJs, etc.
 Machine Learning - TensorFlow, PyTorch, Scikit-learn, Matplotlib, Scipy, etc
 Mathematics - Numpy, Pandas, etc.
How to Install Python (Environment Set-up)

In order to become Python developer, the first step is to learn how to install or update Python on
a local machine or computer. In this tutorial, we will discuss the installation of Python on various
operating systems.

Visit the link https://www.python.org/downloads/ to download the latest release of Python. In


this process, we will install Python 3.8.6 on our Windows operating system. When we click on
the above link, it will bring us the following page.
Step - 1: Select the Python's version to download. Click on the download button.

Step - 2: Click on the Install Now

Double-click the executable file, which is downloaded; the following window will open. Select
Customize installation and proceed. Click on the Add Path check box, it will set the Python path
automatically.
We can also click on the customize installation to choose desired location and features. Other
important thing is install launcher for the all user must be checked.

Step - 3 Installation Process

Now, try to run python on the command prompt. Type the command python -version in
case of python3.
First Python Program:

In this Section, we will discuss the basic syntax of Python, we will run a simple program to
print Hello World on the console. Python provides us the two ways to run a program:
 Using Interactive interpreter prompt
 Using a script file

Interactive interpreter prompt

Python provides us the feature to execute the Python statement one by one at the interactive
prompt. It is preferable in the case where we are concerned about the output of each line of
our Python program.
Open the interactive mode, open the terminal (or command prompt) and type python (python3 in
case if you have Python2 and Python3 both installed on your system).
It will open the following prompt where we can execute the Python statement and check their
impact on the console.

After writing the print statement, press the Enter key.

Here, we get the message "Hello World!" printed on the console.


Using a script file (Script Mode Programming)

The interpreter prompt is best to run the single-line statements of the code. However, we cannot
write the code every-time on the terminal. It is not suitable to write multiple lines of code. Using
the script mode, we can write multiple lines code into a file which can be executed later. For this
purpose, we need to open an editor like notepad, create a file named and save it
with .py extension, which stands for "Python". Now, we will implement the above example using
the script mode.

Step - 1: Open the Python interactive shell, and click "File" then choose "New", it will
open a new blank script in which we can write our code.

Step -2: Now, write the code and press "Ctrl+S" to save the file.
Step - 3: After saving the code, we can run it by clicking "Run" or "Run Module". It will
display the output to the shell

The output will be shown as follows.


CONTENTS: Practical
Unit 1: Write a program to demonstrate basic data type in python.
Explanation: Data types are the classification or categorization of data items. It represents the
kind of value that tells what operations can be performed on a particular data. Since everything is
an object in Python programming, data types are actually classes and variables are instance
(object) of these classes. Following are the standard or built-in data type of Python:
 Numeric
 Sequence Type
 Boolean
 Set
 Dictionary

Numeric: In Python, numeric data type represents the data which has numeric value. Numeric
value can be integer, floating number or even the complex numbers

Integers – This value is represented by int class. It contains positive or negative whole numbers
(without fraction or decimal). In Python there is no limit to how long an integer value can be.

Float – This value is represented by float class. It is a real number with floating point
representation. It is specified by a decimal point. Optionally, the character e or E followed by a
positive or negative integer may be appended to specify scientific notation.

Complex Numbers – Complex number is represented by complex class. It is specified as (real


part) + (imaginary part)j. For example – 2+3j Note – type () function is used to determine the
type of data type.
# Python program to demonstrate numeric value
a=5
print("Type of a: ", type(a))
b = 5.0
print("\nType of b: ", type(b))
c = 2 + 4j
print("\nType of c: ", type(c))

Sequence: In Python, sequence is the ordered collection of similar or different data types.
Sequences allows to store multiple values in an organized and efficient fashion. There are several
sequence types in Python –
 String
 List
 Tuple

1) String
 In Python, Strings are arrays of bytes representing Unicode characters. A string is a
collection of one or more characters put in a single quote, double-quote or triple quote. In
python there is no character data type, a character is a string of length one. It is
represented by str class.
 Creating String: Strings in Python can be created using single quotes or double quotes or
even triple quotes.
 Accessing elements of String: In Python, individual characters of a String can be
accessed by using the method of Indexing. Indexing allows negative address references to
access characters from the back of the String, e.g. -1 refers to the last character, -2 refers
to the second last character and so on.

# Python Program for Creation of String with


single Quotes
String1 = 'Welcome to the Geeks World'
print("String with the use of Single Quotes: ")
print(String1)
#Creating a String with double Quotes
String1 = "I'm a Geek"
print("\nString with the use of Double Quotes: ")
print(String1)
print(type(String1))
# Creating a String with triple Quotes
String1 = '''I'm a Geek and I live in a world of
"Geeks"'''
print("\nString with the use of Triple Quotes: ")
print(String1)
print(type(String1))
Accessing elements of List: In order to access the list items refer to the index number. Use the
index operator [ ] to access an item in a list. In Python, negative sequence indexes represent
positions from the end of the array. Instead of having to compute the offset as in List[len(List)-
3], it is enough to just write List[-3]. Negative indexing means beginning from the end, -1 refers
to the last item, -2 refers to the second-last item, etc.

# Python Program to Access characters of String


String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)

# Printing First character


print("\nFirst character of String is: ")
print(String1[0])

# Printing Last character


print("\nLast character of String is: ")
print(String1[-1])

2) List: Lists are just like the arrays, declared in other language which is a ordered collection of
data. It is very flexible as the items in a list do not need to be of the same type. Creating List:
Lists in Python can be created by just placing the sequence inside the square brackets [ ].

# Python program to demonstrate Creation of List


List = []
print("Initial blank List: ")
print(List)
# Creating a List with the use of a String
List = ['GeeksForGeeks']
print("\nList with the use of String: ")
print(List)
# Creating a List with the use of multiple values
List = ["Geeks", "For", "Geeks"]
print("\nList containing multiple values: ")
print(List[0])
print(List[2])
# Creating a Multi-Dimensional List
List = [['Geeks', 'For'], ['Geeks']]
print("\nMulti-Dimensional List: ")
print(List)
# Python program to demonstrate accessing of
element from list
List = ["Geeks", "For", "Geeks"]
# accessing a element from the list using index
number
print("Accessing element from the list")
print(List[0])
print(List[2])
# accessing a element using negative indexing
print("Accessing element using negative indexing")
# print the last element of list
print(List[-1])
# print the third last element of list
print(List[-3])
3) Tuple: Just like list, tuple is also an ordered collection of Python objects. The only difference
between tuple and list is that tuples are immutable i.e. tuples cannot be modified after it is
created. It is represented by tuple class.
 Creating Tuple: In Python, tuples are created by placing a sequence of values separated
by ‘comma’ with or without the use of parentheses for grouping of the data sequence.
Tuples can contain any number of elements and of any datatype (like strings, integers,
list, etc.). Note: Tuples can also be created with a single element, but it is a bit tricky.
Having one element in the parentheses is not sufficient, there must be a trailing ‘comma’
to make it a tuple. Creation of Python tuple without the use of parentheses is known as
Tuple Packing.

# Python program to demonstrate creation of


Set; creating an empty tuple
Tuple1 = ( )
print("Initial empty Tuple: ")
print (Tuple1)
# Creating a Tuple with the use of Strings
Tuple1 = ('Geeks', 'For')
print("\nTuple with the use of String: ")
print(Tuple1)
# Creating a Tuple with the use of list
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1))
# Creating a Tuple with the use of built-in function
Tuple1 = tuple('Geeks')
print("\nTuple with the use of function: ")
print(Tuple1)
# Creating a Tuple with nested tuples
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('python', 'geek')
Tuple3 = (Tuple1, Tuple2)
print("\nTuple with nested tuples: ")
print(Tuple3)
 Accessing elements of Tuple: In order to access the tuple items refer to the index number.
Use the index operator [ ] to access an item in a tuple. The index must be an integer.
Nested tuples are accessed using nested indexing.

# Python program to demonstrate accessing tuple


tuple1 = tuple([1, 2, 3, 4, 5])
# Accessing element using indexing
print("First element of tuple")
print(tuple1[0])
# Accessing element from last negative indexing
print("\n Last element of tuple")
print(tuple1[-1])
print("\n Third last element of tuple")
print(tuple1[-3])

Boolean: Data type with one of the two built-in values, True or False. Boolean objects that are
equal to True are truthy (true), and those equal to False are falsy (false). But non-Boolean objects
can be evaluated in Boolean context as well and determined to be true or false. It is denoted by
the class bool. Note – True and False with capital ‘T’ and ‘F’ are valid booleans otherwise
python will throw an error.

# Python program to demonstrate boolean type


print(type(True))
print(type(False))
print(type(true))

Set: In Python, Set is an unordered collection of data type that is iterable, mutable and has no
duplicate elements. The order of elements in a set is undefined though it may consist of various
elements.
 Creating Sets: Sets can be created by using the built-in set() function with an iterable
object or a sequence by placing the sequence inside curly braces, separated by ‘comma’.
Type of elements in a set need not be the same, various mixed-up data type values can
also be passed to the set.
 Accessing elements of Sets: Set items cannot be accessed by referring to an index, since
sets are unordered the items has no index. But you can loop through the set items using a
for loop, or ask if a specified value is present in a set, by using the in keyword.
# Python program to show the creation of Set in
Python
set1 = set()
print("Initial blank Set: ")
print(set1)

# Creating a Set with the use of a String


set1 = set("GeeksForGeeks")
print("\nSet with the use of String: ")
print(set1)

# Creating a Set with the use of a List


set1 = set(["Geeks", "For", "Geeks"])
print("\nSet with the use of List: ")
print(set1)

# Creating a Set with a mixed type of values


set1 = set([1, 2, 'Geeks', 4, 'For', 6, 'Geeks'])
print("\nSet with the use of Mixed Values")
print(set1)

# Python program to accessing of elements in a set


set1 = set(["Geeks", "For", "Geeks"])
print("\nInitial set")
print(set1)

# Accessing element using for loop


print("\nElements of set: ")
for i in set1:
print(i, end =" ")

# Checking the element using in keyword


print("Geeks" in set1)

Dictionary: Dictionary in Python is an unordered collection of data values, used to store data
values like a map, which unlike other Data Types that hold only single value as an element,
Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more
optimized. Each key-value pair in a Dictionary is separated by a colon :, whereas each key is
separated by a ‘comma’.

 Creating Dictionary: In Python, a Dictionary can be created by placing a sequence of


elements within curly {} braces, separated by ‘comma’. Values in a dictionary can be of
any datatype and can be duplicated, whereas keys can’t be repeated and must be
immutable. Dictionary can also be created by the built-in function dict(). An empty
dictionary can be created by just placing it to curly braces{}. Note – Dictionary keys are
case sensitive, same name but different cases of Key will be treated distinctly.
 Accessing elements of Dictionary: In order to access the items of a dictionary refer to its
key name. Key can be used inside square brackets. There is also a method
called get() that will also help in accessing the element from a dictionary.

# Creating an empty Dictionary


Dict = {}
print("Empty Dictionary: ")
print(Dict)

# Creating a Dictionary with Integer Keys


Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer Keys:
")
print(Dict)

# Creating a Dictionary with Mixed keys


Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys:
")
print(Dict)

# Creating a Dictionary with dict() method


Dict = dict({1: 'Geeks', 2: 'For', 3:'Geeks'})
print("\nDictionary with the use of dict(): ")
print(Dict)

# Creating a Dictionary with each item as a


Pair
Dict = dict([(1, 'Geeks'), (2, 'For')])
print("\nDictionary with each item as a pair: ")
print(Dict)

# Python program to access a element from a


Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}

# accessing a element using key


print("Accessing a element using key:")
print(Dict['name'])

# accessing a element using get() method


print("Accessing a element using get:")
print(Dict.get(3))
Unit 2: Write a program to compute distance between two points taking input
from the user (Pythagorean Theorem)

# Python Program to Calculate Distance:


#Reading co-ordinates

x1 = float(input('Enter x1: '))


y1 = float(input('Enter y1: '))
x2 = float(input('Enter x2: '))
y2 = float(input('Enter y2: '))

# Calculating distance
sd = ( (x2-x1)**2 + (y2-y1)**2 ) ** 0.5
# Displaying result
print('Distance = %f' %(d))

# Python3 program to calculate distance between two points


import math

# Function to calculate distance


def distance(x1 , y1 , x2 , y2):

# Calculating distance
return math.sqrt(math.pow(x2 - x1, 2) +
math.pow(y2 - y1, 2) * 1.0)

print("%.6f"%distance(3, 4, 4, 3))
Unit 3: Write a python program Using for loop, write a program that prints
out the decimal equivalent of 1+½+1/3….1/n.

# Python program to find the sum of series


def sum(n):
i=1
s = 0.0
for i in range(1, n+1):
s = s + 1/i;
return s;
# Driver Code
n=5
print ("Sum is", round(sum(n), 6))

Unit 4: Write a Python program to find first n prime numbers

Given a number N, the task is to print the prime numbers from 1 to N


So if Input: N = 10
Output: 2, 3, 5, 7

Algorithm:
 First, take the number N as input.
 Then use a for loop to iterate the numbers from 1 to N
 Then check for each number to be a prime number. If it is a prime number, print it.

# Python3 program to display Prime numbers till N function to check if a given number is
prime
def isPrime(n):
#since 0 and 1 is not prime return false.
if(n==1 or n==0):
return False
#Run a loop from 2 to n-1
for i in range(2,n):
#if the number is divisible by i, then n is not a prime number.
if(n%i==0):
return False
#otherwise, n is prime number.
return True

# Driver code
N = 50;
# Check for every number from 1 to N
for i in range(1,N+1):
# Check if current number is prime
if(isPrime(i)):
print(i,end=" ")
Unit 5: Write a program using a for loop that loops over a sequence

Python For loop is used for sequential traversal i.e. it is used for iterating over an iterable like
string, tuple, list, etc. It falls under the category of definite iteration. Definite iterations mean the
number of repetitions is specified explicitly in advance. In Python, there is no C style for loop,
i.e., for (i=0; i<n; i++). There is “for in” loop which is similar to for each loop in other
languages. Let us learn how to use for in loop for sequential traversal. Note: In Python, for loops
only implements the collection-based iteration.

Syntax:
for var in iterable:
# statements

Here the iterable is a collection of objects like lists,


tuples. The indented statements inside the for loops
are executed once for each item in an iterable. The
variable var takes the value of the next item of the
iterable each time through the loop.

# Python program to illustrate iterating over


a list
print("List Iteration")
l = ["geeks", "for", "geeks"]
for i in l:
print(i)
# Iterating over a tuple (immutable)
print("\nTuple Iteration")
t = ("geeks", "for", "geeks")
for i in t:
print(i)
# Iterating over a String
print("\nString Iteration")
s = "Geeks"
for i in s:
print(i)
# Iterating over dictionary
print("\nDictionary Iteration")
d = dict()
d['xyz'] = 123
d['abc'] = 345
for i in d:
print("% s % d" % (i, d[i]))
Loop Control Statements
Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed. Python supports the
following control statements.

Continue Statement:
Continue statement is a loop control statement that forces to execute the next iteration of the loop
while skipping the rest of the code inside the loop for the current iteration only i.e. when the
continue statement is executed in the loop, the code inside the loop following the continue
statement will be skipped for the current iteration and the next iteration of the loop will begin.

Usage of Continue Statement:


Consider the situation when you need to write a program which prints the number from 1 to 10
and but not 6. It is specified that you have to do this using loop and only one loop is allowed to
use. Here comes the usage of continue statement. What we can do here is we can run a loop from
1 to 10 and every time we have to compare the value of the iterator with 6. If it is equal to 6 we
will use the continue statement to continue to the next iteration without printing anything
otherwise we will print the value.

# Python program to demonstrate continue


# loop from 1 to 10

for i in range(1, 11):


# If i is equals to 6,
# continue to next iteration
# without printing
if i == 6:
continue
else:
# otherwise print the value
# of i
print(i, end=" ")

Break statement: Break statement in Python is used to bring the control out of the loop when
some external condition is triggered. Break statement is put inside the loop body generally after
if condition

for i in range(1, 11):


# If i is equals to 6 break ,
without printing any more
if i == 6:
break;
print(i, end=" ")
Write a program using a while loop that asks the user for a number and
prints a countdown from that number to zero.

 Create a variable of integer type and input the number from user.
 Take the condition of while to be >=0 as 0 is also to be printed.Inside the loop we
first print the number then reduce it by 1
 On last iteration we get number = 0 which will be printed and then the value of
number = -1 which fails the while condition halting the loop and ending the
program.

# Programme prints a countdown


#from that number to zero
n = int(input("Enter A Number--->"));
while n >=0:
print (n);
n = n - 1;
Unit 6: Write a Python Program to add matrices and multiply matrices
A matrix is a two-dimensional data structure where numbers are arranged into rows and
columns. Python does not have a built-in type for matrices but we can treat a list of a list as a
matrix. The List is an ordered set of values enclosed in square brackets [ ].
Let A= [ [1, 2, 3] [4, 5, 6] [7, 8, 9] ] be a list of a list, then it can be treated as a 3x3 matrix with 3
rows and 3 columns. The first row can be selected as A [0] and the element in the first row, the
first column can be selected as A [0][0]. To add two matrices we have to add the corresponding
elements of both the matrices individually.

Aim: Program to compute the sum of two matrices and then print it in Python.
# Program to add two matrices using nested loop
X = [[1,2,3],
[4,5,6],
[7,8,9]]

Y = [[9,8,7],
[6,5,4],
[3,2,1]]

result = [[0,0,0],[0,0,0],[0,0,0]]

# iterate through rows

for i in range(len(X)):

# iterate through columns


for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]
for r in result:
print(r)
Aim: Program to compute the multiplication of two matrices
In Python, we can implement a matrix as nested list (list inside a list). We can treat each element
as a row of the matrix.

For example X = [[1, 2], [4, 5], [3, 6]] would


represent a 3x2 matrix. The first row can be
selected as X[0]. And, the element in first row,
first column can be selected as X[0][0].
Multiplication of two matrices X and Y is defined
only if the number of columns in X is equal to the
number of rows Y.If X is a n x m matrix and Y is
a m x l matrix then, XY is defined and has the
dimension n x l (but YX is not defined). Here are
a couple of ways to implement matrix
multiplication in Python.

Using Simple Nested Loops:


In this program we have to use nested for loops to iterate through each row and each column.

# Program to multiply two matrices using nested loops

# take a 3x3 matrix


A = [[12, 7, 3],
[4, 5, 6],
[7, 8, 9]]

# take a 3x4 matrix


B = [[5, 8, 1, 2],
[6, 7, 3, 0],
[4, 5, 9, 1]]

result = [[0, 0, 0, 0],


[0, 0, 0, 0],
[0, 0, 0, 0]]

# iterating by row of A
for i in range(len(A)):

# iterating by column by B
for j in range(len(B[0])):

# iterating by rows of B
for k in range(len(B)):
result[i][j] = result[i][j]+
A[i][k] * B[k][j]
for r in result:
print(r)
Matrix Multiplication (Vectorized implementation)
import numpy as np
# take a 3x3 matrix
A = [[12, 7, 3],
[4, 5, 6],
[7, 8, 9]]
# take a 3x4 matrix
B = [[5, 8, 1, 2],
[6, 7, 3, 0],
[4, 5, 9, 1]]
# result will be 3x4
result= [[0,0,0,0],[0,0,0,0],[0,0,0,0]]
result = np.dot(A,B)
for r in result:
print(r)
Unit 7: Write a Python program to check if a string is palindrome or not.

Given a string, write a python function to check if it is


palindrome or not. A string is said to be
palindrome if the reverse of the string is the same as
string. For example, “radar” is a palindrome, but “radix”
is not a palindrome. To understand this example, you
should have the knowledge of the following topics:

 Python if...else Statement


 Python Strings
 String Methods

# Program to check if a string is palindrome or


not
my_str = 'radar'
# make it suitable for caseless comparison
my_str = my_str.casefold()
# reverse the string
rev_str = reversed(my_str)
# check if the string is equal to its reverse
if list(my_str) == list(rev_str):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")

Note: in above we have taken a string stored in my_str. Using the method casefold() we make it
suitable for caseless comparisons. Basically, this method returns a lowercased version of the
string. We reverse the string using the built-in function reversed(). Since this function returns a
reversed object, we use the list() function to convert them into a list before comparing.

# function to check string is palindrome or not by iterative method


def isPalindrome(str):
# Run loop from 0 to len/2
for i in range(0, int(len(str)/2)):
if str[i] != str[len(str)-i-1]:
return False
return True
# main function
s = "malayalam"
ans = isPalindrome(s)
if (ans):
print("Yes")
else:
print("No")
Unit 8: Write a Python program to Extract Unique values dictionary values

Sometimes, while working with data, we can have problesm in which we need to perform the
extraction of only unique values from dictionary values list. This can have application in many
domains such as web development. Let s discuss certain ways in which this task can be
performed.Dictionary in Python is a data type for an ordered collection of data values.
Dictionaries hold a key-value pair where each value is linked with a unique key.

Look at the example to understand the input-output format.


Input: {'A': [1, 3, 5, 4], 'B': [4, 6, 8, 10], 'C': [6, 12, 4, 8], 'D': [5, 7, 2] }
Output: [1, 2, 3, 4, 5, 6, 7, 8, 10, 12]

To solve this problem in Python, we can use the following approaches:


Using sorted ( ), values( ) and list comprehension: In this approach, we will be using a
combination of these methods to extract unique values from a dictionary. We will use the
values() method to extract values from the dictionary. List comprehension will be used to get
unique values from the list. sorted() method is simply used to sort the unique values in ascending
order.

 Step 1- Initialise a dictionary with keys and values


 Step 2- Print the original dictionary
 Step 3- Declare a list to store the result
 Step 4- Using values() to get the values from the dictionary
 Step 5- Use list comprehension to get values that are not already present in the dictionary
 Step 6- Use the sorted() method to sort the elements in ascending order
 Step 7- Print the result
dict1 = {'A' : [1, 3, 5, 4],
'B' : [4, 6, 8, 10],
'C' : [6, 12, 4 ,8],
'D' : [5, 7, 2]}
print("The original dictionary is : " ,dict1)

# Using list comprehension, values() and sorted()


res = list(sorted({ele for val in dict1.values() for ele in val}))

# print result
print("The unique values list is : " , res)
Unit 9: Write a Python program to read file word by word and count
characters, words.

Python too supports file handling and allows users to handle files i.e., to read and write files,
along with many other file handling options, to operate on files. Python treats file differently as
text or binary and this is important. Each line of code includes a sequence of characters and they
form text file. Each line of a file is terminated with a special character, called the EOL or End of
Line characters like comma {,} or newline character. It ends the current line and tells the
interpreter a new one has begun. Let’s start with Reading and Writing files.
Working of open() function: Before performing any operation on the file like read or write, first
we have to open that file. For this, we should use Python’s inbuilt function open(). But at the
time of opening, we have to specify the mode, which represents the purpose of the opening file.

 f = open(filename, mode), Where the following mode is supported:


 r: open an existing file for a read operation.
 w: open an existing file for a write operation. If the file already contains some data then it
will be overridden.
 a: open an existing file for append operation. It won’t override existing data.
 r+: To read and write data into the file. The previous data in the file will not be deleted.
 w+: To write and read data. It will override existing data.
 a+: To append and read data from the file. It won’t override existing data.

# Python program to read file word by word


# opening the text file
with open('GFG.txt','r') as file:
# reading each line
for line in file:
# reading each word

for word in line.split():


s#displaying the words

print(word)
To count the lines, word, and characters within a text file in Python:

Counting the lines, word, and characters within a text file results in the line count, word count,
and character count, which includes spaces. For instance the text file containing "Hello
World\nHello Again\nGoodbye" results on lines: 3 words: 5 characters: 29.

 We will use str.split() to count the lines, word, and characters within a text file.
 Call open(file, mode) with the pathname of a file as file and mode as "r" to open the file
for reading.
 Use a for-loop to iterate through the file.
 At each iteration, use str.strip(characters) with "\n" as characters to strip it from each
line str, and use str.split() to create a list containing all the words from the line str.
 Also, in each iteration, add 1 to the number of lines, use len(object) with the list
containing the word from the line as object to add it to the number of words, and
 use len(object) with the stripped line as object to add it to the number of characters.

file = open("sample.txt", "r")


number_of_lines = 0
number_of_words = 0
number_of_characters = 0
for line in file:
line = line.strip("\n")
won't count \n as character
words = line.split()
number_of_lines += 1
number_of_words += len(words)
number_of_characters += len(line)
sfile.close()
print("lines:", number_of_lines,
"words:", number_of_words,
"characters:", number_of_characters)

Program Explanation
 User must enter a file name.
 The file is opened using the open() function in the read mode.
 A for loop is used to read through each line in the file.
 Each line is split into a list of words using split().
 The number of words in each line is counted using len() and the count variable is
incremented.
 The number of words in the file is printed.
Unit 10: Write a Python program for Linear Search
Searching is a technique to find the particular element is present or not in the given list.
There are two types of searching –

 Linear Search
 Binary Search
Both techniques are widely used to search an element in the given list.
Linear Search is a method of finding elements within a list. It is also called a sequential search.
It is the simplest searching algorithm because it searches the desired element in a sequential
manner. It compares each and every element with the value that we are searching for. If both are
matched, the element is found, and the algorithm returns the key's index position.

Problem: Given an array arr[] of n elements, write a function to search a given element x in
arr[].

Examples :
Input : arr[] = {10, 20, 80, 30, 60, 50,
110, 100, 130, 170}
x = 110;
Output : 6
Element x is present at index 6

Input : arr[] = {10, 20, 80, 30, 60, 50,


110, 100, 130, 170}
x = 175;
Output : -1
Element x is not present in arr[].

def linear_Search(list1, n, key):


# Searching list1 sequentially
for i in range(0, n):
if (list1[i] == key):
return i
return -1
list1 = [1, 3, 5, 4, 7, 9]
key = 7
n = len(list1)
res = linear_Search(list1, n, key)
if(res == -1):
print("Element not found")
else:
print("Element found at index: ", res)

You might also like