0% found this document useful (0 votes)
10 views36 pages

r22-applied-python-lab-updated

Uploaded by

ishwaryachattu
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)
10 views36 pages

r22-applied-python-lab-updated

Uploaded by

ishwaryachattu
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/ 36

lOMoARcPSD|47112210

R22 -Applied Python Lab updated

Python Programming (Jawaharlal Nehru Technological University, Hyderabad)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Srividya Bhaskara ([email protected])
lOMoARcPSD|47112210

Applied Python Programming Lab

BVRIT HYDERABAD
College of Engineering for Women
The Temple for Women Empowerment & Human Values
Approved by AICTE & Affiliated to JNTUH, Hyderabad
Nizampet Road, Bachupally, Hyderabad – 500 090, Telangana, India.

Student Notebook
Department Basic Science and Humanities
Year / Semester I B.Tech - II Semester
Subject APPLIED PYTHON PROGRAMMING LABORATORY
Regulation R22
Subject Code

Vision
To emerge as the best among the institutes of technology and research in the
country dedicated to the cause of promoting quality technical education.

Mission
At BVRITH, we Strive to
 Achieve academic excellence through innovative learning practices.
 Enhance intellectual ability and technical competency for a successful career.
 Encourage research and innovation.
 Nurture students towards holistic development with emphasis on leadership skills ,
Life skills and human values.

Prepared by
IT Faculty

Ms S Rama Devi , Associate Professor | Ms M.SudhaRani , Asst.Professor

CSE Faculty

Mr M D Sugnana Rao , Asst Professor | Ms P Kavitha , Asst.Professor |Ms A Naga Kalyani , Asst
Professor

BVRIT HYDERABAD College of Engineering for Women Page 1

Downloaded by Srividya Bhaskara ([email protected])


lOMoARcPSD|47112210

Applied Python Programming Lab

IT - DEPARTMENT VISION

To emerge as a Center of excellence in Information Technology and to produce women


technocrats, global leaders for better tomorrow.

IT - DEPARTMENT MISSION

M1: To impart quality education and inculcate problem solving skills using latest Technologies
in the field of Information Technology.
M2: To encourage multidisciplinary research and consultancy projects.
M3: To promote industry academia linkage and also enhance entrepreneurship skills in women
engineers.

IT- Programme Educational Objectives (PEOs)

After three to six years of graduation, the graduates of this program will be able to:

PEO 1: Develop strong analytical skills using fundamental concepts of science & engineering
subjects.
PEO 2: Excel in programming and critical thinking by applying core technical knowledge
PEO 3: Exhibit continuous learning related to evolving technologies in their professional career
PEO 4: Demonstrate ethical behavior, team work & leadership qualities to solve problems
in broader social context.

BVRIT HYDERABAD College of Engineering for Women Page 2

Downloaded by Srividya Bhaskara ([email protected])


lOMoARcPSD|47112210

Applied Python Programming Lab

CSE - DEPARTMENT VISION

Develop women as technocrats, researchers and entrepreneurs in the field of computer science and
engineering.

CSE - DEPARTMENT MISSION

M1: To impart quality education in Computer Science and Engineering by means of learning
techniques and value-added courses.
M2: To inculcate professional excellence and research culture by encouraging projects in cutting-
edge technologies through industry interactions.
M3: To build leadership skills, ethical values and teamwork among the students.
M4: To strengthen the collaboration of department and industry through internships, mentorships and
professional body activities.

CSE -Programme Educational Objectives (PEOs)

After three to six years of graduation, the graduates of this program will be able to:

PEO–1: Adapt emerging technologies to contribute to the technical innovations for the progressive
development in their respective fields.
PEO–2: Productively engage in multidisciplinary research areas by applying the basic principles
of engineering sciences.
PEO–3: Demonstrate strong technical skills to bring out novel designs/products to address the
social & environmental issues.
PEO–4: Exhibit professional attitude, teamwork and practice code of ethics.

BVRIT HYDERABAD College of Engineering for Women Page 3

Downloaded by Srividya Bhaskara ([email protected])


lOMoARcPSD|47112210

Applied Python Programming Lab

ECE - DEPARTMENT VISION

To emerge as a centre of academic and research excellence in Electronics and Communication


Engineering and create globally competent women technocrats with a high degree of social
consciousness in a holistic learning environment

ECE - DEPARTMENT MISSION

M1: To provide quality education to the students with emphasis on training related to latest
technologies as per industrial needs
M2: To impart research culture, professional ethics and moral values to the students by
committed and competent faculty striving for excellence.
M3: To inculcate a perceptive alacrity in students to identify real life problems, formulate
strategies and evolve into contextually effective solutions.

ECE- Programme Educational Objectives (PEOs)


After three to six years of graduation, the graduates of this program will be able to:

PEO-1: Excel in contemporary problem solving in Electronics and Communication


Engineering and the allied fields through the knowledge-base provided by the
programme.
PEO-2: Demonstrate their technical, communication and leadership skills in professional
environment or as entrepreneurs with social responsibility.
PEO-3: Analyze the latest issues and technology growth in the field of Electronics and
Communication Engineering and update their knowledge and skills accordingly
through continuous learning.
PEO-4: Demonstrate ethical and human values in multicultural and multidisciplinary
environments

BVRIT HYDERABAD College of Engineering for Women Page 4

Downloaded by Srividya Bhaskara ([email protected])


lOMoARcPSD|47112210

Applied Python Programming Lab

EEE - DEPARTMENT VISION

To develop comprehensively trained and socially responsible women electrical and electronics
engineers with competencies and capabilities to adapt to new challenges.

EEE - DEPARTMENT MISSION

M1: To empower the students adept at latest technologies by providing innovative learning
environment.

M2: To cultivate interdisciplinary research mindset and outlook to develop engineering solutions.

M3: To inculcate ethical behavior and professional attitude in order to embrace holistic concept of
living.

EEE - Programme Educational Objectives (PEOs)


After three to six years of graduation, the graduates of this program will be able to:

PEO–1: Propose effective solutions for complex electrical and electronics engineering problems
using modern techniques.
PEO–2: Excel in their career and compete with their global peers in Techno-Scientific fields.
PEO–3: Exhibit good communication skills, ethical behavior & social perception.
PEO–4: Stimulate economic growth and job opportunities through entrepreneurship.

BVRIT HYDERABAD College of Engineering for Women Page 5

Downloaded by Srividya Bhaskara ([email protected])


lOMoARcPSD|47112210

Applied Python Programming Lab

JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY HYDERABAD


PROGRAMMING FOR PROBLEM SOLVING LAB
B.Tech. I Year II Sem.
Course Code: CS106ES/CS206ES LTP C
0 1 2 2
CONTENTS

1 Syllabus .………………..…………..……………... 8
2 Instructions to Students …………….……………………………... 11
3 Introduction to UNIX commands ...………………………….……… ……. 12
4 Lab Cycle-1 Algorithms …………………………………………… 15
5 Lab Cycle-2 Algorithms …………………………………………… 29

Viva Questions with Solutions


6 …………………………………………… 32

BVRIT HYDERABAD College of Engineering for Women Page 6

Downloaded by Srividya Bhaskara ([email protected])


lOMoARcPSD|47112210

Applied Python Programming Lab

PROGRAMMING FOR PROBLEM SOLVING LAB


INTERNAL ASSESSMENT SHEET

LIST OF EXPERIMENTS

Lab Record Viva Total Signature of the


S.No Name of the Experiment Date of Exp done Remarks
[5M] [5M] [5M] [15M] Faculty

BVRIT HYDERABAD College of Engineering for Women Page 7

Downloaded by Srividya Bhaskara ([email protected])


lOMoARcPSD|47112210

Applied Python Programming Lab

List of Experiments
Department Electronic and Communications Engineering

Year / Semester I B. Tech (ECE) – II Semester


Subject APPLIED PYTHON PROGRAMMING LABORATORY

Regulation R22
Subject Code

Course Outcomes: Upon completing this course, the students will be able to

1. Build basic programs using fundamental programming constructs


2. Write and execute python codes for different applications
3. Capable to implement on hardware boards
4. Build efficient solution by processing data from files.

Course PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
CO1 2 2 1 1 1 1 - - 1 - 1 1
CO2 2 3 2 1 1 2 - - 1 - 1 1
CO3 2 3 2 1 1 2 - - 1 - 1 1
CO4 2 2 1 2 1 2 - - 1 - 1 1

SYLLABUS

CYCLES PROGRAMS
1. Downloading and Installing Python and Modules
a) Python 3 on Linux
Follow the instructions given in the URL https://docs.python-
guide.org/starting/install3/linux/
b) Python 3 on Windows
Follow the instructions given in the URL
https://docs.python.org/3/using/windows.html (Please remember that
Windows installation of Python is harder!)
c) pip3 on Windows and Linux
Install the Python package installer by following the
instructions given in the URL
https://www.activestate.com/resources/quick-reads/how-to-
install-and-use-pip3/
d) Installing numpy and scipy
You can install any python3 package using the command pip3 install
<packagename>
e) Installing jupyterlab
Install from pip using the command pip install jupyterlab

BVRIT HYDERABAD College of Engineering for Women Page 8

Downloaded by Srividya Bhaskara ([email protected])


lOMoARcPSD|47112210

Applied Python Programming Lab


2. Introduction to Python3
a) Printing your biodata on the screen
b) Printing all the primes less than a given number
c) Finding all the factors of a number and show whether it is a perfect number, i.e.,
the sum of all its factors (excluding the number itself) is equal to the number itself

3. Defining and Using Functions


a) Write a function to read data from a file and display it on the screen
CYCLE-1 b) Define a boolean function is palindrome(<input>)
c) Write a function collatz(x) which does the following: if x is odd, x = 3x + 1;
if x is even, then x = x/2. Return the number of steps it takes for x = 1
d) Write a function N(m, s) = exp(-(x-m)2/(2s2))/sqrt(2π)s that computes
the Normal distribution

4. The package numpy


a) Creating a matrix of given order m x n containing random numbers in the
range 1 to 99999
b) Write a program that adds, subtracts and multiplies two matrices. Provide an
interface such that, based on the prompt, the function (addition, subtraction,
multiplication) should be performed
c) Write a program to solve a system of n linear equations in n variables using
matrix inverse
5. The package scipy and pyplot
a) Finding if two sets of data have the same mean value
b) Plotting data read from a file
c) Fitting a function through a set a data points using polyfit function
d) Plotting a histogram of a given data set

6. The strings package


a) Read text from a file and print the number of lines, words and characters
b) Read text from a file and return a list of all n letter words beginning with a vowel
c) Finding a secret message hidden in a paragraph of text
d) Plot a histogram of words according to their length from text read from a file

7. Installing OS on Raspberry Pi
a) Installation using PiImager
b)Installation using image file
Downloading an Image
Writing the image to an SD card
CYCLE-2 using Linux
using Windows
Booting up

8.Accessing GPIO pins using Python


a) Installing GPIO Zero library.
First, update your repositories list:
sudo apt update
Then install the package for Python 3:
sudo apt install python3-gpiozero

BVRIT HYDERABAD College of Engineering for Women Page 9

Downloaded by Srividya Bhaskara ([email protected])


lOMoARcPSD|47112210

Applied Python Programming Lab


9.b)Blinking an LED connected to one of the GPIO pin
c)Adjusting the brightness of an LED
d)Adjust the brightness of an LED (0 to 100, where 100 means maximum brightness) using the in-
built PWM wavelength

10.Collecting Sensor Data


DHT Sensor interface
Connect the terminals of DHT GPIO pins of Raspberry Pi.
Import the DHT library using import Adafruit_DHT
Read sensor data and display it on screen.

BVRIT HYDERABAD College of Engineering for Women Page 10

Downloaded by Srividya Bhaskara ([email protected])


lOMoARcPSD|47112210

Applied Python Programming Lab

INSTRUCTIONS TO THE STUDENTS

(1) On entering the lab you should make an entry in the log book available with the
details regarding student name, roll no, system no and signature.

(2) You must bring Observation notebook for every lab session. Observation book should be duly
signed by your faculty, failing which your report will not be graded. You must complete all
experimental programs allotted during the session.

(3) You should shutdown the system properly and leave the lab neat and tidy.

BVRIT HYDERABAD College of Engineering for Women Page 11

Downloaded by Srividya Bhaskara ([email protected])


lOMoARcPSD|47112210

Applied Python Programming Lab

INTRODUCTION TO ‘UNIX’ COMMANDS

In order to create and run programs in UNIX environment the following are the some of the basic
editors and commands used.

Creating Directory:

Directories are used to group files together in a hierarchical structure.


mkdir dirname --- creates a new directory
cd dirname --- to change to the specified directory
cd.. --- will get you one level up from your current position(directory) rmdir
dirname --- removes/deletes directory
rm --- deletes files in directory

Editors:

Nano Editor: Basic editors used for creating the programs are nano, vim, emacs.
GNU nano is a small and friendly text editor for beginners. Nano is installed by default in Ubuntu and
many other editors.

To run nano you can use the following syntax:


nano path_filename.c
Nano will follow the path and open that file if it exists. If it does not exist, it’ll start a new buffer
with that filename in that directory.

It’s a WYSIWYG editor; “what you say is what you get.” What you type directly goes into the text
input, unless you modify it with a key like Control or Meta.

Shortcuts:
Ctrl+o --- to save the file contents
Ctrl+x --- to Quit the editor. Nano will politely ask you if you want to save your buffer, and you
can cancel this action as well.
Ctrl+w --- to search for the text in the program

Creating and Running Programs in Nano Editor:

1. To open the file ,at the command prompt type------nano filename.c


2. Create the program and save the file----ctrl+o , ctrl+s
3. Quit the editor-----ctrl+x
4. At the command prompt type
gcc/c99 filename.c
Above command is used to compile the program to generate object code.
5. To run the program type
./a.out(executable file)

BVRIT HYDERABAD College of Engineering for Women Page 12

Downloaded by Srividya Bhaskara ([email protected])


lOMoARcPSD|47112210

Applied Python Programming Lab

Vim Editor: Vim is an advanced text editor that provides the power of the de-facto Unix editor 'Vi'
with a more complete feature set. Vim is often called a "programmer's editor," and is so seful for
programming that many consider it an entire IDE. It's not just for programmers, though. Vim is perfect
for all kinds of text editing.

Vim editor is best for program creation where the user will have the flexibility of differentiating the
keywords and text what the user enters.

To run vim you can use the following syntax:


vim path_filename.c

Shortcuts:

Shift+:+w --- to save the file contents


Shift+:+q --- to Quit the editor without saving the contents of file.
Shift+:+wq --- to save contents and quit the editor

Running Programs in vim Editor:

1. To open the file, at the command prompt type --- vim filename.c
2. Create the program and save the file and quit --- Shift+:+wq
3. At the command prompt type
C99/gcc filename.c
Above command is used to compile the program to generate object code.
4. To run the program type
./a.out(executable file)

Configuration:

vim is a highly configurable editor, and it is best to configure vim to your liking as vim by default
has all the nice features turned off. A list of files and their locations are given below.
~/.vimrc is the vim configuration file which vim reads on startup
~/.vim/ is the directory in which the user can add utility plugins, syntax highlighting
plugins, and indent plugins.

Sample .vimrc file


" Turn on line numbering. Turn it off with "set onu" set nu

" Set syntax on


syntax on

" Indent automatically depending on


filetype filetype indent on
set auto indent

BVRIT HYDERABAD College of Engineering for Women Page 13

Downloaded by Srividya Bhaskara ([email protected])


lOMoARcPSD|47112210

Applied Python Programming Lab

Basic UNIX Commands used:

man command:
man commandname --- shows you the manual page for the command

ls command:
ls --- lists your files in the directory
ls-l --- lists our file in long format, it gives information about size of file, owner of
file, rights for file and last modified time.
Copy command:
cp filename1 filename2 --- copies contents of file1 to file2, where both file1 and file2 will have
same content.
Move command:
mv filename1 filename2 --- moves contents of file1 to file2 and file1 contents will be erased.

Remove command:
rm filename --- removes a file. It is wise to use the option rm -i, which will ask you for
confirmation before actually deleting anything.

BVRIT HYDERABAD College of Engineering for Women Page 14

Downloaded by Srividya Bhaskara ([email protected])


lOMoARcPSD|47112210

Applied Python Programming Lab

LAB CYCLE-1

Downloading and Installing Python and Modules

1a)Python 3 on Linux

$ python3 –version
$ sudo apt-get update
$ sudo apt-get install python3.6

1 b)Python 3 on Windows

Installation steps:
Four Python 3.10 installers are available for download - two each for the 32-bit and 64-bit versions
of the interpreter. The web installer is a small initial download, and it will automatically download
the required components as necessary.

If you select “Install Now”:

 You will not need to be an administrator (unless a system update for the C Runtime Library is required or
you install the Python Launcher for Windows for all users)
 Python will be installed into your user directory
 The Python Launcher for Windows will be installed according to the option at the bottom of the first page
 The standard library, test suite, launcher and pip will be installed
 If selected, the install directory will be added to your PATH
 Shortcuts will only be visible for the current user

BVRIT HYDERABAD College of Engineering for Women Page 15

Downloaded by Srividya Bhaskara ([email protected])


lOMoARcPSD|47112210

Applied Python Programming Lab

1 c)pip3 on Windows and Linux

First Check which version of pip3 is installed by entering:


pip3 --version
Output should be similar to:
pip 20.0.2 from C:\Python38\lib\site-packages\pip (python 3.8)
Confirm which version of Python (if any) is installed on your computer by entering:
python --version
Output should be similar to:
Python 3.8.2
Pip3 Installation
Python 3.4+ in most operating systems includes pip3 by default. If your python version is less than 3.4, then you
should upgrade your Python version which will automatically install pip3.
Pip3 Upgrade
In operating system environments that already have Python 3 and pip3 installations, you can upgrade pip3, by
entering:
python -m pip3 install --upgrade pip
Pip3 Usage
To install a Python package, enter:
Pip3 install <package_name>

Install pip3 Ubuntu and Debian Linux

Ubuntu 18.04 has both Python 2 and Python 3 installed by default, and hence has two pip variants for each Python
version.‘pip’, refers to Python 2. pip3 refers to Python 3.

Enter the following command to update Linux:


sudo apt update
Enter the following command to install pip3:
sudo apt install python3-pip
The above command will also install all pip3 dependencies.

Install pip3 Windows


To install or upgrade pip3 in a Windows environment that already has Python 3 installed:
Download the latest version of get-pip.py from
<https://bootstrap.pypa.io/>
You can also use the curl command to download get-pip.py:
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
CD into the directory where get-pip.py was downloaded to, and enter the following command to install pip3 and its
dependencies:
python3 get-pip.py
You can verify that pip3 is installed by navigating to the default pip3 installation directory, eg. C:\python38\scripts\,
and enter:
pip3 –version

BVRIT HYDERABAD College of Engineering for Women Page 16

Downloaded by Srividya Bhaskara ([email protected])


lOMoARcPSD|47112210

Applied Python Programming Lab


1 d)Installing numpy and scipy

To install NumPy with the package manager for Python 3, run:


pip3 install numpy

To install SciPy with the package manager for Python 3, run:


pip3 install scipy

1 e) Installing jupyterlab

JupyterLab requires Python 3.3 or greater. Python's designated package manager, pip, makes it easy to
install JupyterLab. Begin with dnf:

$sudo dnf update


$ sudo dnf install epel-release
$ sudo dnf install python3
$ sudo dnf install python3-pip

After installation, verify that Python and pip are accessible:


$ python3 –version
$ python3 -m pip install --user --upgrade pip

$ python3 -m pip install --user jupyterlab

2.Baisc Programs
2 a)Printing your biodata on the screen

print(name)
print(age)
print(course)
print(address)

2 b)Printing all the primes less than a given number


# First, we will take the input:
n= int(input ("Please, Enter the Upper Range Value: "))

print ("The Prime Numbers in the range are: ")


for number in range (2, n):
if number > 1:
for i in range (2, number):
if (number % i) == 0:
break
else:
BVRIT HYDERABAD College of Engineering for Women Page 17

Downloaded by Srividya Bhaskara ([email protected])


lOMoARcPSD|47112210

Applied Python Programming Lab


print (number)

2 C)Finding all the factors of a number and show whether it is a perfect number, i.e., the sum of
all its factors (excluding the number itself) is equal to the number itself

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


sum_v=0.
for i in range(1,num):
if (num%i==0):
sum_v=sum_v+i.
if(sum_v==num):
print("The entered number is a perfect number")
else:
print(“ Number not perfect number”)

Defining and Using Functions


3 a)Write a function to read data from a file and display it on the screen
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"]
# \n is placed to indicate EOL (End of Line)
file1.write("Hello \n")
file1.writelines(L)
file1.close() #to change file access modes
file1 = open("myfile.txt","r+")
print("Output of Read function is ")
print(file1.read())
print()
# seek(n) takes the file handle to the nth
# bite from the beginning.
file1.seek(0)
print( "Output of Readline function is ")
print(file1.readline())
print()
file1.seek(0)
# To show difference between read and readline
print("Output of Read(9) function is ")
print(file1.read(9))
print()
file1.seek(0)
print("Output of Readline(9) function is ")
print(file1.readline(9))
file1.seek(0)
# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
print()
BVRIT HYDERABAD College of Engineering for Women Page 18

Downloaded by Srividya Bhaskara ([email protected])


lOMoARcPSD|47112210

Applied Python Programming Lab


file1.close()

3b)Define a boolean function ispalindrome(<input>)


def isPanlindrome(num):
return int(num != 0) and ((num % 10) * \
(10**int(math.log(num, 10))) + \
rev(num // 10))

# Reading number
test_number = input (“Enter any number”)

# printing the original number


print ("The original number is : " + str(test_number))

# using math.log() + recursion + list comprehension


# for checking a number is palindrome
res = test_number == isPalindrome(test_number)

# printing result
print ("Is the number palindrome ? : " + str(res))

3 c)Write a function collatz(x) which does the following: if x is odd, x = 3x + 1; if x is even,


then x = x/2. Return the number of steps it takes for x = 1

def printCollatz(n):

# We simply follow steps


# while we do not reach 1
Count = 0
while n != 1:
# If n is odd
if n & 1:
n=3*n+1
count++

# If even
else:
n = n // 2
count++

# Print 1 at the end


print(count)

# Driver code
printCollatz(6)

BVRIT HYDERABAD College of Engineering for Women Page 19

Downloaded by Srividya Bhaskara ([email protected])


lOMoARcPSD|47112210

Applied Python Programming Lab


d)Write a function N(m, s) = exp(-(x-m)2/(2s2))/sqrt(2π)s that computes the Normal distribution

import math
def solve(x,m):
s=1
result = math.exp(-((x-m)**2)/2*(s**s))/((2 * math.pi * s)**0.5)
return result

print(solve(4,2))

4 a) Creating a matrix of given order m x n containing random numbers in the range 1 to 99999
import numpy as np
# 1st argument --> numbers ranging from 0 to 9,
# 2nd argument, row = 2, col = 3
Example 1
array = np.random.randint(10, size=(2, 3))
print(array)
Example 2
array = np.random.randint(99999, size=(10, 5))
print(array)

4 b) Write a program that adds, subtracts and multiplies two matrices. Provide an interface such that, based
on the prompt, the function (addition, subtraction, multiplication) should be performed
METHOD 1
# input two matrices of size n x m
matrix1 = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
matrix2 = [[5,8,1],
[6,7,3],
[4,5,9]]
res = [[0 for x in range(3)] for y in range(3)]
# explicit for loops
for i in range(len(matrix1)):
for j in range(len(matrix2[0])):
for k in range(len(matrix2)):
# resulted matrix
res[i][j] += matrix1[i][k] * matrix2[k][j]
print (res)
METHOD 2
# We need install numpy in order to import it
import numpy as np
# input two matrices
mat1 = ([1, 6, 5],[3 ,4, 8],[2, 12, 3])
mat2 = ([3, 4, 6],[5, 6, 7],[6,56, 7])
# This will return dot product
res = np.dot(mat1,mat2)
# print resulted matrix
print(res)

4 c) Write a program to solve a system of n linear equations in n variables using matrix inverse
BVRIT HYDERABAD College of Engineering for Women Page 20

Downloaded by Srividya Bhaskara ([email protected])


lOMoARcPSD|47112210

Applied Python Programming Lab


Systems of Linear Equations
Systems of linear equations can be solved with arrays and NumPy. A system of linear equations is shown
below:
8x+3y−2z=98x+3y−2z=9
−4x+7y+5z=15−4x+7y+5z=15
3x+4y−12z=353x+4y−12z=35NumPy's np.linalg.solve() function can be used to solve this system of
equations for the variables xx, yy and zz.
The steps to solve the system of linear equations with np.linalg.solve() are below:
Create NumPy array A as a 3 by 3 array of the coefficients
Create a NumPy array b as the right-hand side of the equations
Solve for the values of xx, yy and zz using np.linalg.solve(A, b).
The resulting array has three entries. One entry for each variable.
In [1]:
import numpy as np
A = np.array([[8, 3, -2], [-4, 7, 5], [3, 4, -12]])
b = np.array([9, 15, 35])
x = np.linalg.solve(A, b)
x
Out[1]:
array([-0.58226371, 3.22870478, -1.98599767])
We can plug the valuse of xx, yy and zz back into one of the equations to check the answer.
xx is the first entry of the array, yy is the second entry of the array, and zz is the third entry of the array.
xx = x[0]
yy = x[1]
zz = x[2]
When these values are plugged into the equation from above:
8x+3y−2z=98x+3y−2z=9
The answer should be 9.0.
In [2]:
8*x[0] + 3*x[1] - 2*x[2]
Out[2]:
9.0

5a) Finding if two sets of data have the same mean value
# Importing the statistics module
from statistics import mean
# Importing fractions module as fr
# Enables to calculate mean of a
# set in Fraction
from fractions import Fraction as fr

# tuple of positive integer numbers


data1 = (11, 3, 4, 5, 7, 9, 2)
# tuple of a negative set of integers
data2 = (-1, -2, -4, -7, -12, -19)
# tuple of mixed range of numbers
data3 = (-1, -13, -6, 4, 5, 19, 9)
# tuple of a set of fractional numbers
data4 = (fr(1, 2), fr(44, 12), fr(10, 3), fr(2, 3))
# dictionary of a set of values
BVRIT HYDERABAD College of Engineering for Women Page 21

Downloaded by Srividya Bhaskara ([email protected])


lOMoARcPSD|47112210

Applied Python Programming Lab


# Only the keys are taken in
# consideration by mean()
data5 = {1:"one", 2:"two", 3:"three"}

# Printing the mean of above datasets


print("Mean of data set 1 is % s" % (mean(data1)))
print("Mean of data set 2 is % s" % (mean(data2)))
print("Mean of data set 3 is % s" % (mean(data3)))
print("Mean of data set 4 is % s" % (mean(data4)))
print("Mean of data set 5 is % s" % (mean(data5)))
Output :
Mean of data set 1 is 5.857142857142857
Mean of data set 2 is -7.5
Mean of data set 3 is 2.4285714285714284
Mean of data set 4 is 49/24
Mean of data set 5 is 2
5 b) Plotting data read from a file
Requirement:
A text file from where data should be extracted. Let the file name = GFG.txt

import matplotlib.pyplot as plt


import csv
X = []
Y = []
with open('GFG.txt', 'r') as datafile:
plotting = csv.reader(datafile, delimiter=',')
for ROWS in plotting:
X.append(int(ROWS[0]))
Y.append(int(ROWS[1]))
plt.plot(X, Y)
plt.title('Line Graph using CSV')
BVRIT HYDERABAD College of Engineering for Women Page 22

Downloaded by Srividya Bhaskara ([email protected])


lOMoARcPSD|47112210

Applied Python Programming Lab


plt.xlabel('X')
plt.ylabel('Y')
plt.show()
Output:

import matplotlib.pyplot as plt


import numpy as np
X, Y = np.loadtxt('GFG.txt', delimiter=',', unpack=True)
plt.bar(X, Y)
plt.title('Line Graph using NUMPY')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()
Output:

5 c) Fitting a function through a set a data points using polyfit function


BVRIT HYDERABAD College of Engineering for Women Page 23

Downloaded by Srividya Bhaskara ([email protected])


lOMoARcPSD|47112210

Applied Python Programming Lab


EXAMPLE-1
import numpy as np
import matplotlib.pyplot as mp
np.random.seed(12)
x = np.linspace( 0, 1, 25 )
y = np.cos(x) + 0.3*np.random.rand(25)
p = np.poly1d( np.polyfit(x, y, 4) )
t = np.linspace(0, 1, 250)
mp.plot(x, y, 'o', t, p(t), '-')
mp.show()

EXAMPLE-2
import numpy as np
import matplotlib.pyplot as mp
np.random.seed(12)
x=np.linspace(-20,20,10)
y=2*x+5
coeff = np.polyfit(x,y,2)
xn = np.linspace(-20,20,100)
yn = np.poly1d(coeff)
mp.plot( xn,yn(xn),x,y,'o')
5 d) Plotting a histogram of a given data set
To plot a histogram using Matplotlib, we can follow the steps given below −
Make a list of numbers and assign it to a variable x.
Use the plt.hist() method to plot a histogram.
Compute and draw the histogram of *x*.
We can pass n-Dimensional arrays in the hist argument also.
To show the plotted figure, use the plt.show() method.
Example
from matplotlib import pyplot as plt
x = [300, 400, 500, 2000, 10]
plt.hist(x, 10)
plt.show()
Output

BVRIT HYDERABAD College of Engineering for Women Page 24

Downloaded by Srividya Bhaskara ([email protected])


lOMoARcPSD|47112210

Applied Python Programming Lab

6 a) Read text from a file and print the number of lines, words and characters
METHOD -1
This version of the program counts the number of lines, words and characters (including spaces) using
string methods.
Solution algorithm:
At each iteration the for cycle extracts the next line from the file. The following actions take place in the
body of the cycle:
The counter of lines is incremented by 1.
The string is split into words using the split method. The len function counts the number of words in the list
of words. This number is added to the word counter.
To ignore the newline character ('\n'), we remove it using the strip method. The length of the remaining
string in characters is measured by the len function. The resulting value is added to the symbol counter.
The text file:
one two three
city town
big small
Code of the program:
file = open('text.txt')
lines = 0
words = 0
symbols = 0
for line in file:
lines += 1
words += len(line.split())
symbols += len(line.strip('\n'))
print("Lines:", lines)
print("Words:", words)
print("Symbols:", symbols)
BVRIT HYDERABAD College of Engineering for Women Page 25

Downloaded by Srividya Bhaskara ([email protected])


lOMoARcPSD|47112210

Applied Python Programming Lab


Result:
Lines: 3
Words: 7
Symbols: 31

METHOD-2
This is a more classical algorithm for solving the problem. We do not use the len function and string
methods.
The each line is scanned character by character. In this case, when counting characters, not only the
newline character is not taken into account, spaces and tabs are also excluded.
To count the number of words, an additional variable (pos) is introduced, which "shows" whether we are
inside the word or not. If a non-whitespace character is encountered and before that we were outside the
word, then a new word has begun. The word counter should be incremented by 1.
The text file:
one two three
city town
big small
Code of the program:
file = open('text.txt')
lines = 0
words = 0
letters = 0
for line in file:
lines += 1
for symbol in line:
if symbol not in (' ', '\n', '\t'):
letters += 1
pos = 'out'
for symbol in line:
if symbol != ' ' and pos == 'out':
words += 1
pos = 'in'
elif symbol == ' ':
pos = 'out'
print("Lines:", lines)
print("Words:", words)
print("Letters:", letters)
Result:
Lines: 3
Words: 7
Letters: 27

6b)
Read text from a file and return a list of all n letter words beginning with a vowel
METHOD-1
# initializing list
test_list = ["all", "love", "and", "get", "educated", "by", "gfg"]
# printing original list
print("The original list is : " + str(test_list))
res = []
vow = "aeiou"
for sub in test_list:
flag = False
BVRIT HYDERABAD College of Engineering for Women Page 26

Downloaded by Srividya Bhaskara ([email protected])


lOMoARcPSD|47112210

Applied Python Programming Lab

# checking for begin char


for ele in vow:
if sub.startswith(ele):
flag = True
break
if flag:
res.append(sub)
# printing result
print("The extracted words : " + str(res))

METHOD-2
Using any(), startswith() and loop
# initializing list
test_list = ["all", "love", "and", "get", "educated", "by", "gfg"]
# printing original list
print("The original list is : " + str(test_list))
res = []
vow = "aeiou"
for sub in test_list:
# check for vowel beginning
flag = any(sub.startswith(ele) for ele in vow)
if flag:
res.append(sub)
# printing result
print("The extracted words : " + str(res))
METHOD-3
Using find() method

#Starting with vowels


# initializing list
test_list = ["all", "love", "and", "get", "educated", "by", "gfg"]
# printing original list
print("The original list is : " + str(test_list))
def vowelstart(s):
if(s.find("a")==0 or s.find("e")==0 or s.find("i")==0 or s.find("e")==0 or s.find("u")==0):
return True
return False
res = []
for sub in test_list:
if(vowelstart(sub)):
res.append(sub)
# printing result
print("The extracted words : " + str(res))

BVRIT HYDERABAD College of Engineering for Women Page 27

Downloaded by Srividya Bhaskara ([email protected])


lOMoARcPSD|47112210

Applied Python Programming Lab

6 c) ) Finding a secret message hidden in a paragraph of text


# Taking input from user
data = 'Welcome to...'

# conversion Chart
conversion_code = {
# Uppercase Alphabets
'A': 'Z', 'B': 'Y', 'C': 'X', 'D': 'W', 'E': 'V', 'F': 'U',
'G': 'T', 'H': 'S', 'I': 'R', 'J': 'Q', 'K': 'P', 'L': 'O',
'M': 'N', 'N': 'M', 'O': 'L', 'P': 'K', 'Q': 'J', 'R': 'I',
'S': 'H', 'T': 'G', 'U': 'F', 'V': 'E', 'W': 'D', 'X': 'C',
'Y': 'B', 'Z': 'A',
# Lowercase Alphabets
'a': 'z', 'b': 'y', 'c': 'x', 'd': 'w', 'e': 'v', 'f': 'u',
'g': 't', 'h': 's', 'i': 'r', 'j': 'q', 'k': 'p', 'l': 'o',
'm': 'n', 'n': 'm', 'o': 'l', 'p': 'k', 'q': 'j', 'r': 'i',
's': 'h', 't': 'g', 'u': 'F', 'v': 'e', 'w': 'd', 'x': 'c',
'y': 'b', 'z': 'a'
}
# Creating converted output
converted_data = ""

for i in range(0, len(data)):


if data[i] in conversion_code.keys():
converted_data += conversion_code[data[i]]
else:
converted_data += data[i]
# Printing converted output
print(converted_data)

Output
Dvoxlnv gl

6 d) Plot a histogram of words according to their length from text read from a file
def splitString (str):
l1 = []
s = str.split( )
for words in s :
l1.append(len(words))
print(l1)
# Main code
# declare string and assign value
from matplotlib import pyplot as plt
import numpy as np
str = "Hello World How are you? Program execution starts at Preprocessor directives starts Modulo
operator cannot be used ANSI expansion ASCII expansion C language developped by Format "

BVRIT HYDERABAD College of Engineering for Women Page 28

Downloaded by Srividya Bhaskara ([email protected])


lOMoARcPSD|47112210

Applied Python Programming Lab


# call the function
splitString(str)
a = np.array(splitString(str))
# Creating histogram
fig, ax = plt.subplots(figsize =(10, 7))
ax.hist(a, bins = [0, 4, 8])
# Show plot
plt.show()

Cycle 2:
7. How to Install an Operating System on a Raspberry Pi
Your Raspberry Pi doesn't come with an operating system pre-installed.
Before you even think about downloading an operating system for your Raspberry Pi, you need to make sure you
have the right storage media. When choosing an SD card to buy you may find that a 32GB card is almost as
affordable.
Several tools are available that can write a Raspberry Pi operating system to an SD card
Installation using PiImager
Available from the official Raspberry Pi website, Raspberry Pi Imager is a utility that writes an operating system
to your Pi's SD card.
Visit: www.raspberrypi.org -> Select software-> Select the OS installation using Raspberry Pi imager
Once imager is started select the OS and storage then press write button.
But this procedur take slong time and sometimes even the system may hang.

To avoid this we use second approach.

Installation using Image file

At first download the Raspberry Pi OS image into the system which is very big image from internet.(type
raspberry Pi OS with desktop and recommended software and download which will be downloaded as zip file.
Extract the zip file and store it on your computer.)
Once imager is started select the Custom option for OS selecting OS image and upload from your computer
BVRIT HYDERABAD College of Engineering for Women Page 29

Downloaded by Srividya Bhaskara ([email protected])


lOMoARcPSD|47112210

Applied Python Programming Lab

Select storage (SD card) to which you want to write then press Write button,which writes or burnt to the memory
card.
Take that card and insert to Rasberrypi computer which makes Raspberry Pi to put into.
8. Accessing GPIO Pins using Python
a) Installing GPIO Zero library
GPIO Zero is installed by default in the Raspberry Pi OS desktop image, and the Raspberry Pi Desktop
image for PC/Mac, both available from raspberrypi.org.
1.Update the repositories list using
sudo apt update
2. Install the package for Python3
sudo apt install python3-gpiozero (or)
for Python2
sudo apt install python-gpiozero
b) Blinking an LED connected to one of GPIO pin
To initialize the GPIO ports on the Raspberry Pi we need to first import the Python library, the initialize the
library and setup pin 8 as an output pin.
Initialization code:
Import RPi. GPIO as GPIO # Import Raspberry Pi GPIO library
from time import sleep # Import the sleep function from the time module
GPIO. setwarnings(False) # Ignore warning for now
GPIO. setmode(GPIO.BOARD) # Use physical pin numbering
GPIO. setup(8, GPIO.OUT, initial=GPIO.LOW) # Set pin 8 to be an output pin and set initial value to low (off)

LED blink code:


while True: # Run forever
GPIO. output(8, GPIO.HIGH) # Turn on
sleep(1) # Sleep for 1 second
GPIO. output(8, GPIO.LOW) # Turn off
sleep(1) # Sleep for 1 second

BVRIT HYDERABAD College of Engineering for Women Page 30

Downloaded by Srividya Bhaskara ([email protected])


lOMoARcPSD|47112210

Applied Python Programming Lab


Combine both initialization and blink code in a single python file and run it. Then it should result like below

c) Adjusting the brightness of an LED


import RPi.GPIO as GPIO
import time
# Led1 on my Board
led = 11
GPIO.setmode( GPIO.BOARD)
GPIO.setup( led, GPIO.OUT)
# 50Hz PWM Frequency
pwm_led = GPIO.PWM( led, 50)
# Full Brightness, 100% Duty Cycle
pwm_led.start(100)
try:
while True:
duty_s = raw_input("Enter Brightness Value (0 to 100):")
# Convert into Integer Value
duty = int(duty_s)
pwm_led.ChangeDutyCycle(duty)
time.sleep(0.5)
except KeyboardInterrupt:
print "Exiting Program"
except:
print "Error Occurs, Exiting Program"
finally:
GPIO.cleanup()

BVRIT HYDERABAD College of Engineering for Women Page 31

Downloaded by Srividya Bhaskara ([email protected])


lOMoARcPSD|47112210

Applied Python Programming Lab

c) Adjusting the brightness of an LED( 0 to 100, where 100 means maximum brightness) using the in-built PWM
wavelength.

const int LED_PIN = 5;

const int ON_TIME = 1000;


const int OFF_TIME = 1000;

void setup(){
pinMode( LED_PIN, OUTPUT );
}

void loop(){
digitalWrite( LED_PIN, HIGH );
delay( ON_TIME );

digitalWrite( LED_PIN, LOW );


delay( OFF_TIME );
}

9) Collecting Sensor Data

import RPi.GPIO as GPIO


import csv
import time, datetime
from time import sleep
import Adafruit_DHT
import os.path

#initialize GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.cleanup()

#set up DHT sensor


dht_sensor = Adafruit_DHT.DHT11
dht_pin = 7

#global variables
datafile = "/home/pi/Desktop/Temp_Humid.csv"

#main function - will take temp, humidity and timestamp and write to csv every 10s
def main():
i=1

BVRIT HYDERABAD College of Engineering for Women Page 32

Downloaded by Srividya Bhaskara ([email protected])


lOMoARcPSD|47112210

Applied Python Programming Lab

while(1):
print("Beginning cycle " + str(i))
data = get_data()
add_to_file(data)
sleep(10)
print("End of cycle " + str(i))
i = i+1

#get temp and humidity and add to 'data' dictionary


def get_data():
now = datetime.datetime.now()
humidity, temp = Adafruit_DHT.read(dht_sensor, dht_pin)
if humidity is not None and temp is not None:
data = {'timestamp':str(now.strftime("%Y%m%d_%H-%M-%S")), 'temperature':temp, 'humidity':humidity}
print(data)
return(data)

#write temp, humidity and time stamps to csv file


def add_to_file(data):
if os.path.isfile(datafile): #checks if file exists. if yes, appends values for dictionary under corresponding
header in a new line
with open(datafile, 'a', newline='') as csvfile:
fieldnames = ['Time', 'Temperature', 'Humidity']
data_writer = csv.DictWriter(csvfile, fieldnames=fieldnames, delimiter=' ', quotechar='|',
quoting=csv.QUOTE_MINIMAL)

data_writer.writerow({'Time': data['timestamp'], 'Temperature': data['temperature'], 'Humidity':


data['humidity']})

else: #creates file (that has been checked and does not yet exist) and adds headers and values for all 3 keys in
dict
with open(datafile, 'w', newline='') as csvfile:
fieldnames = ['Time', 'Temperature', 'Humidity']
data_writer = csv.DictWriter(csvfile, fieldnames=fieldnames, delimiter=' ', quotechar='|',
quoting=csv.QUOTE_MINIMAL)

data_writer.writeheader()
data_writer.writerow({'Time': data['timestamp'], 'Temperature': data['temperature'], 'Humidity':
data['humidity']})

if __name__ == "__main__":
main()

BVRIT HYDERABAD College of Engineering for Women Page 33

Downloaded by Srividya Bhaskara ([email protected])


lOMoARcPSD|47112210

Applied Python Programming Lab

Viva Questions:

1. What is Python?

Python is a high-level and object-oriented programming language with unified semantics designed primarily for
developing apps and the web. It is the core language in the field of Rapid Application Development (RAD) as it
offers options such as dynamic binding and dynamic typing.

2. What are the benefits of Python?

The benefits of Python are as follows:

 Speed and Productivity: Utilizing the productivity and speed of Python will enhance the process control
capabilities and possesses strong integration.
 Extensive Support for Libraries: Python provides a large standard library that includes areas such as
operating system interfaces, web service tools, internet protocols, and string protocols. Most of the
programming tasks are already been scripted in the standard library which reduces effort and time.
 User-friendly Data Structures: Python has an in-built dictionary of data structures that are used to build
fast user-friendly data structures.
 Existence of Third Party Modules: The presence of third-party modules in the Python Package Index
(PyPI) will make Python capable to interact with other platforms and languages.
 Easy Learning: Python provides excellent readability and simple syntaxes to make it easy for beginners to
learn.

3. What are the key features of Python?

The following are the significant features of Python, and they are:

 Interpreted Language: Python is an interpreted language that is used to execute the code line by line at a
time. This makes debugging easy.
 Highly Portable: Python can run on different platforms such as Unix, Macintosh, Linux, Windows, and so
on. So, we can say that it is a highly portable language.
 Extensible: It ensures that the Python code can be compiled on various other languages such as C, C++,
and so on.
 GUI programming Support: It implies that Python provides support to develop graphical user interfaces

4. What type of language is Python? Programming or Scripting?

Python is suitable for scripting, but in general, it is considered a general-purpose programming language.

5. What are the applications of Python?

The applications of Python are as follows:

 GUI based desktop applications


 Image processing applications
 Business and Enterprise applications
 Prototyping
 Web and web framework applications
BVRIT HYDERABAD College of Engineering for Women Page 34

Downloaded by Srividya Bhaskara ([email protected])


lOMoARcPSD|47112210

Applied Python Programming Lab


6.What are the two major loop statements?

for and while

7. What do you understand by the term PEP 8?

PEP 8 is the Python latest coding convention and it is abbreviated as Python Enhancement Proposal. It is all
about how to format your Python code for maximum readability.

8. How memory management is done in Python?


 In Python memory management is done using private heap space. The private heap is the storage area for
all the data structures and objects. The interpreter has access to the private heap and the programmer
cannot access this private heap.
 The storage allocation for the data structures and objects in Python is done by the memory manager. The
access for some tools is provided by core API for programmers to code.
 The built-in garbage collector in Python is used to recycle all the unused memory so that it can be
available for heap storage area.

9. What are the built-in types available in Python?

The built-in types in Python are as follows:

 Integer
 Complex numbers
 Floating-point numbers
 Strings
 Built-in functions

10. What are Python Decorators?

Decorator is the most useful tool in Python as it allows programmers to alter the changes in the behavior of class
or function.

BVRIT HYDERABAD College of Engineering for Women Page 35

Downloaded by Srividya Bhaskara ([email protected])

You might also like