r22-applied-python-lab-updated
r22-applied-python-lab-updated
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
CSE Faculty
Mr M D Sugnana Rao , Asst Professor | Ms P Kavitha , Asst.Professor |Ms A Naga Kalyani , Asst
Professor
IT - DEPARTMENT VISION
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.
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.
Develop women as technocrats, researchers and entrepreneurs in the field of computer science and
engineering.
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.
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.
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.
To develop comprehensively trained and socially responsible women electrical and electronics
engineers with competencies and capabilities to adapt to new challenges.
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.
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.
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
LIST OF EXPERIMENTS
List of Experiments
Department Electronic and Communications Engineering
Regulation R22
Subject Code
Course Outcomes: Upon completing this course, the students will be able to
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
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
(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.
In order to create and run programs in UNIX environment the following are the some of the basic
editors and commands used.
Creating 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.
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
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.
Shortcuts:
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.
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.
LAB CYCLE-1
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.
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
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.
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:
2.Baisc Programs
2 a)Printing your biodata on the screen
print(name)
print(age)
print(course)
print(address)
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
# Reading number
test_number = input (“Enter any number”)
# printing result
print ("Is the number palindrome ? : " + str(res))
def printCollatz(n):
# If even
else:
n = n // 2
count++
# Driver code
printCollatz(6)
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
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
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
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
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
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
# 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 = ""
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 "
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.
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
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)
c) Adjusting the brightness of an LED( 0 to 100, where 100 means maximum brightness) using the in-built PWM
wavelength.
void setup(){
pinMode( LED_PIN, OUTPUT );
}
void loop(){
digitalWrite( LED_PIN, HIGH );
delay( ON_TIME );
#initialize GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.cleanup()
#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
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
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()
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.
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.
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
Python is suitable for scripting, but in general, it is considered a general-purpose programming language.
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.
Integer
Complex numbers
Floating-point numbers
Strings
Built-in functions
Decorator is the most useful tool in Python as it allows programmers to alter the changes in the behavior of class
or function.