Python Term Work Mech 3rd Sem
Python Term Work Mech 3rd Sem
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
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 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.
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.
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.
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.
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
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.
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
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.
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.
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 [ ].
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.
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)
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’.
# Calculating distance
sd = ( (x2-x1)**2 + (y2-y1)**2 ) ** 0.5
# Displaying result
print('Distance = %f' %(d))
# 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.
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
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.
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
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.
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]]
for i in range(len(X)):
# 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.
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.
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.
# 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.
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.
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