CIVILECEPythonlab manual - R22
CIVILECEPythonlab manual - R22
Python programming
LAB MANUAL
I B. TECH II SEMESTER
1 1
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PRINCETON INSTITUTE OF ENGINEERING & TECHNOLOGY FOR WOMEN
(Approved by AICTE, New Delhi & Affiliated to JNTU Hyderabad)
Chowdaryguda (V), Ghatkesar (M), Medchal-Malkajgiri(D).TS-500088
Phone: 9394544566 / 6305324412
e-mail: [email protected]
JNTUH Code(6M) CIVIL–EEE–ECE-CSE-CSE(AI&ML)-CSE(DS)-CSE(CS) EAMCET Code– PETW
VISION
The educational environment in order to develop graduates with the strong academic technical backgrounds
needed to achieve distinction in the discipline and to bring up the Institution as an Institution of Academic
excellence of International standard.
MISSION
We transform persons into personalities by the state-of-the-art infrastructure, time consciousness, quick
response and the best academic practices through assessment and advice.
CORE VALUES
Attaining global eminence, by achieving excellence in all that we do in life education and service
The educational environment in order to develop graduates with the strong academic technical
backgrounds needed to achieve distinction in the discipline and to bring up the Institution as an
Institution of Academic excellence of International standard.
MISSION
We transform persons into personalities by the state-of-the-art infrastructure, time consciousness, quick
2
DEPARTMENT OF COMPUTER SCIENCE
AND ENGINEERING
3
P[
PROGRAM OUTCOMES:
Problem analysis: Identify, formulate, review research literature, and analyze complex engineering
PO2 problems reaching substantiated conclusions using first principles of mathematics, natural sciences, and
engineering sciences.
Design/development of solutions: Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with appropriate consideration for the
PO3 public health and safety, and the cultural, societal, and environmental considerations.
Conduct investigations of complex problems: Use research-based knowledge and research methods
PO4 including design of experiments, analysis and interpretation of data, and synthesis of the information to
provide valid conclusions.
Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern engineering
PO5 and IT tools including prediction and modeling to complex engineering activities with an understanding
of the limitations.
The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal,
PO6 health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice.
Environment and sustainability: Understand the impact of the professional engineering solutions in
PO7 societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the
PO8 engineering practice.
Individual and team work: Function effectively as an individual, and as a member or leader in diverse
PO9
teams, and in multidisciplinary settings.
Communication: Communicate effectively on complex engineering activities with the engineering
PO10 community and with society at large, such as, being able to comprehend and write effective reports and
design documentation, make effective presentations, and give and receive clear instructions.
Project management and finance: Demonstrate knowledge and understanding of the engineering and
PO11 management principles and apply these to one’s own work, as a member and leader in a team, to manage
projects and in multidisciplinary environments.
Life-long learning: Recognize the need for, and have the preparation and ability to engage in
PO12 independent and life-long learning in the broadest context of technological change.
4
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PREREQUISITES:
A course on “Programming for Problem Solving”, A course on “Computer Organization and Architecture”.
COURSE OBJECTIVES:
The objective of this lab is to get an overview to To provide an understanding of the design aspects of
operating system concepts through simulation and Introduce basic Unix commands, system call interface for
process management, interprocess communication and I/O in Unix
COURSE OUTCOMES:
1. Simulate and implement operating system concepts such as scheduling, deadlock management, file
management and memory management.
2. Able to implement C programs using Unix system calls.
5
P[
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Course Name: Course Code: CS406PC
Year/Semester: I/II Regulation: R22
7
P[
Cycle – 1
1. Downloading and Installing Python and Modules
a) Python 3 on Linux
To install Python 3.6 or 3.8 on Ubuntu Linux machines:
To see which version of Python 3 you have installed, open a command prompt and run
If you are using Ubuntu 16.10 or newer, then you can easily install Python 3.6 with the
following commands:
If you’re using another version of Ubuntu (e.g. the latest LTS release) or you want to use a
more current Python, we recommend using the deadsnakes PPA to install Python 3.8:
8
Step 2: Click on Welcome to Python.org
10
Python 3.11.3 will be downloaded.
12
Step 7 : click on Next.
14
You can also check to see which version of pip3 is installed by entering
Confirm which version of Python (if any) is installed on your computer by entering:
Output should be similar to:
Pip3 Installation
Pip3 Upgrade
In operating system environments that already have Python 3 and pip3 installations, you
can upgrade pip3, by entering:
Ubuntu 20.4 has only Python 3, but still requires a separate python-pip 3 installation.
16
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
CD into the directory where get-pip.py was downloaded to, and enter the following command
to install pip3 and its dependencies:
You can verify that pip3 is installed by navigating to the default pip3 installation directory,
For Example: C:\python38\scripts\, and enter:
e) Installing jupyterlab
Install from pip using the command pip install jupyterlab
2. Introduction to Python3
18
a) Printing your biodata on the screen
OUTPUT
OUTPUT
c) Finding all the factors of a number and show whether it is a perfect number, i.e., the
20
sum of all its factors (excluding the number itself) is equal to the number itself
#program to check the given number is perfect or not and to print all the factors of the given
number
n = int(input("Enter any number: "))
sum1 = 0
for i in range(1, n):
if(n % i == 0):
sum1 = sum1 + i
print("\n",i)
if (sum1 == n):
print("The number is a Perfect number!")
else:
print("The number is not a Perfect number!")
OUTPUT
OUTPUT
22
#program define a boolean function is palindrome(<input>)
def isPalindrome(s):
return s == s[::-1]
s=input("Enter any String")
ans = isPalindrome(s)
if ans:
print("Yes")
else:
print("No")
OUTPUT
24
#Program for Normal Distribution
from matplotlib import pyplot as mp
import numpy as np
def gaussian(x, mu, sig):
return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))
x_values = np.linspace(-3, 3, 120)
for mu, sig in [(-1, 1), (0, 2), (2, 3)]:
mp.plot(x_values, gaussian(x_values, mu, sig))
mp.show()
Sample output:
SAMPLE OUTPUT
26
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
# importing numpy as np
import numpy as np
# creating first matrix
A = np.array([[1, 2], [3, 4]])
# creating second matrix
B = np.array([[4, 5], [6, 7]])
print("Printing elements of first matrix")
print(A)
print("Printing elements of second matrix")
print(B)
# adding two matrix
print("Addition of two matrix")
print(np.add(A, B))
# subtracting two matrix
print("Subtraction of two matrix")
print(np.subtract(A, B))
# multiplication of two matrix
print("multiplication of two matrices")
result = np.dot(A,B)
r=result
for r in result:
print(r)
SAMPLE OUTPUT
28
c) Write a program to solve a system of n linear equations in n variables using matrix
inverse
print(X)
OUTPUT
5. The package scipy and pyplot
a) Finding if two sets of data have the same mean value
30
b) Plotting data read from a file
Sample output:
32
c) Fitting a function through a set a data points using polyfit function
34
d) Plotting a histogram of a given data set
Sample output
6. The strings package
a) Read text from a file and print the number of lines, words and characters
Create a text file and save as data.txt
36
b) Read text from a file and return a list of all n letter words beginning with a vowel
# Python Program that Extract words starting
# with Vowel From A list 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 i in test_list:
if i[0] in vow:
res.append(i)
# Printing result
print("The extracted words : " + str(res))
Sample Output:
c) Finding a secret message hidden in a paragraph of text
38
# Taking input from user
data = 'Svool sld ziv blf'
# 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)
Sample Output:
d) Plot a histogram of words according to their length from text read from a file
bar_names = []
bar_heights = []
bar_names = []
bar_heights = []
Seyfert1 112
Seyfert2 42
Quasars 131
QuasarsSeyfert1 46
Radiogalaxy 5
40
BLlacHP 39
Seyfert3 5
HeIIRegions 55
Sample Output:
Cycle – 2
A simple LED circuit consists of a LED and resistor. The resistor is used to limit the current
that is being drawn and is called a current limiting resistor. Without the resistor the LED would
run at too high of a voltage, resulting in too much current being drawn which in turn would
instantly burn the LED, and likely also the GPIO port on the Raspberry Pi.
To calculate the resistor value we need to examine the specifications of the LED. Specifically
we need to find the forward voltage (VF) and the forward current (IF). A regular red LED has
a forward voltage (VF) of 1.7V and forward current of 20mA (IF). Additionally we need to
know the output voltage of the Raspberry Pi which is 3.3V.
We can then calculate the resistor size needed to limit the current to the LED’s maximum
forward current (IF) using ohm’s law like this:
RΩ=VI=3.3–VFIF=3.3–1.720mA=80Ω
Unfortunately 80 ohm is not a standard size of a resistor. To solve this we can either combine
multiple resistors, or round up to a standard size. In this case we would round up to 100 ohm.
42
Important information: Since ohm’s law tells us that I (current) = V (voltage) / R (ohm)
rounding up the resistor value will lower the actual current being drawn a little. This is good
because we don’t want to run our system at the maximum current rating. Rounding down
instead of up would be dangerous, since it will actually increase the current being drawn.
Increased current would result in running our system over the maximum rating and potentially
destroying or damaging our components.
With the value calculated for the current limiting resistor we can now hook the LED and resistor
up to GPIO pin 8 on the Raspberry Pi. The resistor and LED needs to be in series like the
diagram below. To find the right resistor use the resistor color code – for a 100 ohm resistor it
needs to be brown-black-brown. You can use your multimeter to double check the resistor
value.
When hooking up the circuit note the polarity of the LED. You will notice that the LED has a
long and short lead. The long lead is the positive side also called the anode, the short lead is
the negative side called the cathode. The long should be connected to the resistor and the short
lead should be connected to ground via the blue jumper wire and pin 6 on the Raspberry Pi as
shown on the diagram.
To find the pin number refer to this diagram showing the physical pin numbers on the
44
Writing the Python Software to blink the LED
With the circuit created we need to write the Python script to blink the LED. Before we start
writing the software we first need to install the Raspberry Pi GPIO Python module. This is a
library that allows us to access the GPIO port directly from Python.
To install the Python library open a terminal and execute the following
With the library installed now open your favorite Python IDE (I recommend Thonny Python
IDE more information about using it here)
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.
Next we need to turn the LED on and off in 1 second intervals by setting the output pin to either
high (on) or low (off). We do this inside a infinite loop so our program keep executing until we
manually stop it.
Combining the initialization and the blink code should give you the following full Python
program:
With our program finished, save it as blinking_led.py and run it either inside your IDE or in
the console with:
With the program running you should see something like this:
46
ADJUSTING THE BRIGHTNESS OF AN LED
48
Controlling Brightness of LED using Raspberry Pi 4
Controlling the brightness of an LED or blinking it continually by passing various delays
with PWM(Pulse Width Modulation) it might be your first Raspberry Pi 4 learning experience.
In this article, we perform three activities which are
Turning On & Off LED.
Blinking it using PWM at different frequencies.
Controlling the brightness of the LED.
Required Components:
Raspberry Pi 4 controller.
Monitor/Laptop.
And other connecting wires such as (Ethernet Cable, HDMI Cable, & Powering cable for
both Raspberry Pi and Monitor, etc.)
LED of any color.
Jumper Wire.
Bread-board.
Resistor 100 Ohm.
Now we will proceed further with our first activity i.e. Turning On & Off LED.
Circuit Connection for controlling the brightness of LED using Raspberry pi:
The circuit diagram remains the same for all 3 activities there is no change in the circuit
diagram only we have to change the code for all activities to blink it and to control its brightness
from 0 to 100 by applying PWM signal via Board pin 11(in raspberry pi there are two different
types of pin numbering available, you can use anyone out of these two there is a slight change
in the code by which you can switch these pin numbering configuration). The 2 pin
configurations are GPIO pin configuration and the second one is Board Pin configuration.
further, I’ll tell you what is the change required in the code to switch between available pin
configurations.
As you can see that in the above figure the positive terminal of LED is connected to the board
pin 11 and on which we will apply 5V to turn ON&OFF LED. Now we have done with the
circuit diagram, now think! how to power the LED with raspberry pi? to answer this let us
move to the coding part.
50
Save and run the file. You should see the LED pulse bright and dim, in a continuous cycle.
The frequency ( pwm.freq) tells Raspberry Pi Pico how often to switch the power between on
and off for the LED.
The duty cycle tells the LED for how long it should be on each time. For Raspberry Pi Pico in
MicroPython, this can range from 0 0 to 6 65025. 6502505 would be 100% of the time, so the
LED would stay bright. A value of around2 32512 would indicate that it should be on for half
the time.
52
Overview
DHT11 is a Digital Sensor consisting of two different sensors in a single package. The sensor
contains an NTC (Negative Temperature Coefficient) Temperature Sensor, a Resistive-type
Humidity Sensor and an 8-bit Microcontroller to convert the analog signals from these
sensors and produce a Digital Output.
I have already worked with the DHT11 Sensor in my DHT11 Humidity Sensor on
Arduino Project. In that project, I have mentioned the Pin Configuration of the DHT11
Sensor, how to interface it with a Microcontroller and how the digital Output from the
DHT11 Sensor can be decoded.
So, I suggest you to refer to that project once for more information on DHT11 Humidity and
Temperature Sensor. I’ll explain a few thing which I have missed in the Arduino Project.
We know that the output from the DHT11 Sensor is Digital. But how exactly we can read this
digital data?
In this setup, the Microcontroller acts as a Master and the DHT11 Sensor acts as a Slave. The
Data OUT of the DHT11 Sensor is in open-drain configuration and hence it must always be
pulled HIGH with the help of a 5.1KΩ Resistor.
This pull-up will ensure that the status of the Data is HIGH when the Master doesn’t request
54
the data (DHT11 will not send the data unless requested by the Master).
Now, we will the how the data is transmitted and the data format of the DHT11 Sensor.
Whenever the Microcontroller wants to acquire information from DHT11 Sensor, the pin of
the
Microcontroller is configured as OUTPUT and it will make the Data Line low for a minimum
time of 18ms and releases the line. After this, the Microcontroller pin is made as INPUT.
The data pin of the DHT11 Sensor, which is an INPUT pin, reads the LOW made by the
Microcontroller and acts as an OUTPUT pin and sends a response of LOW signal on the data
line for about 80µs and then pulls-up the line for another 80µs.
After this, the DHT11 Sensor sends a 40 bit data with Logic ‘0’ being a combination of 50µs
of LOW and 26 to 28µs of HIGH and Logic ‘1’ being 50µs of LOW and 70 to 80µs of
HIGH.
After transmitting 40 bits of data, the DHT11 Data Pin stays LOW for another 50µs and
finally changes its state to input to accept the request from the Microcontroller.
NOTE: We have implemented this logic while programming the Arduino. But for Raspberry
Pi, we used a library that takes care of all these things.
Raspberry Pi DTH11 Humidity and Temperature Sensor Interface
By interfacing the DHT11 Sensor with Raspberry Pi, you can build your own IoT Weather
Station. All you need to implement such IoT Weather is a Raspberry Pi, a DHT11 Humidity
and Temperature Sensor and a Computer with Internet Connectivity.
Circuit Diagram
The following is the circuit diagram of the DHT11 and Raspberry Pi Interface.
Components Required
Raspberry Pi 3 Model B
DHT11 Temperature and Humidity Sensor
Connecting Wires
Power Supply
Computer
Circuit Design
If you observe the circuit diagram, there is not a lot of stuff going on with respect to the
connections. All you need to do is to connect the VCC and GND pins of the DHT11 Sensor
to +5V and GND of Raspberry Pi and then connect the Data OUT of the Sensor to the GPIO4
i.e. Physical Pin 7 of the Raspberry Pi.
56
Since we are using a library called Adafruit_DHT provided by Adafruit for this project, we
need to first install this library into Raspberry Pi.
First step is to download the library from GitHub. But before this, I have created a folder
called ‘library’ on the desktop of the Raspberry Pi to place the downloaded files. You don’t
have to do that.
Now, enter the following command to download the files related to the Adafruit_DHT
library
All the contents will be downloaded to a folder called ‘Adafruit_Python_DHT’. Open this
directory using cd Adafruit_Python_DHT. To see the contents of this folder, use ‘ls’
command.
In that folder, there is file called ‘setup.py’. We need to install this file using the following
command.
Code
As we are using the library Adafruit_DHT for this project, there is nothing much to do in the
Python Programming part. All you need to do is to invoke the library with the Sensor and
GPIO Pin and print the values of Temperature and Humidity
import sys
import Adafruit_DHT
import time
while True:
humidity, temperature = Adafruit_DHT.read_retry(11, 4)
print 'Temp: {0:0.1f} C Humidity: {1:0.1f} %'.format(temperature, humidity)
time.sleep(1)
Working
Make the connections as per the circuit diagram and install the library. Use the above python
program to see the results.
58
60