Python Lab Manual
Python Lab Manual
ENGINEERING
3/3/2024
Prepared
by
Dr. VISHWANATH G
Assistant Professor,
Department of Biomedical and Robotic Engineering
Mysore University School of Engineering
University of Mysore
1 Python for System Programming lab
List of Experiments
Expt.
Programs
No.
Check math functions.
a) floor(), ceil(), trunc(), radians(), degrees(), sin(), cos(), tan().
b) fmod(), log10(), gcd(), pow(), modf().sqrt(), exp().
1
Understand Control Flow statements.
a) Convert the temperature value from one unit to another.
b) Display all the even/odd numbers between given two numbers
Understand Control Flow statements.
c) Check whether the given number is a prime or not.
2 d) Find the sum of all the numbers between given two numbers.
e) Find whether the given number is an Armstrong number or not.
f) Display first n Fibonacci numbers.
Implement user defined functions.
a) Function to find LCM of a number.
3 b) Function to find HCF of a number.
c) Recursive function to find sum of all numbers up to a given number.
d) Recursive function to find factorial of a number.
Check String Operations:
a) len(), split(), join(), upper(), lower(), swapcase(), title(),
4 b) Fi6nd(), index(), count(), replace(), sorted(), strip().
c) String slicing.
Check List and Tuple Operations.
a) len(), append(), extend(), insert(), remove().
5 b) reverse(), clear(), sort(), sorted(), count().
c) List comprehension: Creating list, Creating Matrix, Transpose of a Matrix,
Addition, Difference and Scalar multiplication of two matrices.
Check Dictionary and Set Operations.
a) Add element, Modify element, Delete element, clear(), copy().
b) get values, get keys, get items.
c) union(), intersection(), difference(), symmetrical_difference().
6
Understand File Handling in Python
a) Read data from a file.
b) Write data into a file.
Experiment No 1:-
Check math functions.
a.
floor() :- The floor() function is a mathematical function that returns the largest integer
less than or equal to a given number. In other words, it rounds down the number to
the nearest integer.
example: 3.5 = 3; -2.7 = -3 ; 9 = 9;
import math
x = 3.6
# floor(): Returns the largest integer less than or equal to x
print("floor({}) = {}".format(x, math.floor(x))) # Output: ceil(3.6) = 3
ceil() :- The ceil() function is a mathematical function that returns the smallest integer
greater than or equal to a given number. In other words, it rounds up the number
to the nearest integer.
example: 3.5 = 4; -2.7 = -2 ; 9 = 9;
import math
x = 3.6
result = math.ceil(x)
print("ceil({}) = {}".format(x, result)) # Output: ceil(3.6) = 4
In Python, the math.ceil() function from the math module is used to compute the ceiling
value.
trunc() :- The trunc() function is a mathematical function that truncates a given
number towards zero. It simply removes the fractional part of the number,
returning the integer part.
example: trunc (3.5) = 3; trunc (-2.7) = -2 ; trunc(9)= 9;
import math
x = 3.6
result = math.trunc(x)
print("trunc({}) = {}".format(x, result)) # Output: trunc(3.6) = 3
import math
degree_angle = 45
radian_angle = math.radians(degree_angle)
print("radians({}) = {}".format(degree_angle, radian_angle))
# Output: radians(45) = 0.7853
sin() :The sin() function is a mathematical function that returns the sine of an angle. In
trigonometry, the sine of an angle in a right triangle is defined as the ratio of the
length of the side opposite the angle to the length of the hypotenuse.
import math
angle_in_radians = math.pi / 6 # 30 degrees in radians
sin_value = math.sin(angle_in_radians)
print("sin({} radians) = {}".format(angle_in_radians, sin_value))
# Output: sin(0.523598 radians) = 0.499999
cos() :- The cos() function is a mathematical function that returns the cosine of an
angle. In trigonometry, the cosine of an angle in a right triangle is defined as the
ratio of the length of the adjacent side to the length of the hypotenuse.
import math
angle_in_radians = math.pi / 3 # 60 degrees in radians
cos_value = math.cos(angle_in_radians)
print("cos({} radians) = {}".format(angle_in_radians, cos_value))
# Output: cos(1.0471975511965976 radians) = 0.5000000000000001
tan() :- The tan() function is a mathematical function that returns the tangent of an
angle. In trigonometry, the tangent of an angle in a right triangle is defined as the
ratio of the length of the side opposite the angle to the length of the side adjacent
to the angle.
import math
angle_in_radians = math.pi / 6 # 30 degrees in radians
tan_value = math.tan(angle_in_radians)
print("tan({} radians) = {}".format(angle_in_radians, tan_value))
# Output: tan(0.5235987755982988 radians) = 0.5773502691896257
b.
i. fmod() :- The fmod() function is a mathematical function and It calculates the floating-
point remainder of dividing two numbers. The difference between fmod() and the
% operator (modulo operator) is how they handle negative numbers.
Given two numbers x and y, fmod(x,y) returns the floating-point remainder of dividing x by y.
Formula is given by :- fmod(x,y)=x−n×y
Example :-
• fmod(10, 3) returns 1.0 because 10 divided by 3 equals 3 with a remainder of 1.
• fmod(-10, 3) returns -1.0 because −10 divided by 3 equals −3 with a remainder of −1.
import math
x = 10
y=3
remainder = math.fmod(x, y)
print("fmod({}, {}) = {}".format(x, y, remainder)) # Output: fmod(10, 3) = 1.0
ii. log10() : The log10() function is a mathematical function that calculates the base-10
logarithm of a given number. Given a real number x, the log10() function computes
the logarithm to the base 10 of x, denoted as log10(x).
That is log10(x)=y implies 10y=x
Example
iii. gcd() : The gcd() function is a mathematical function that computes the greatest
common divisor (GCD) of two integers. Mathematically, the greatest common
divisor of a and b, denoted as gcd(a,b),
import math
a = 12
b = 18
result = math.gcd(a, b)
print("gcd({}, {}) = {}".format(a, b, result)) # Output: gcd(12, 18) = 6
iv. pow(x, y) :The pow(x, y) function returns the value of x raised to the power of y. It's
equivalent to 𝒙𝒚 .
import math
result = pow(2, 3)
print("2 raised to the power of 3 is:", result) # Output: 2 raised to the power of 3 is : 8
v. modf(x) :This function returns the fractional and integer parts of x as a tuple. The
fractional part is the value after the decimal point, and the integer part is the
vii. exp(x): This function returns the exponential of x, which is e raised to the power
of x, where e is the base of the natural logarithm.
import math
result = math.exp(1)
print("Exponential of 1:", result) # Output: Exponential of 1: 2.718281828459045
Experiment No 2:-
Understand Control Flow statements.
a) Convert the temperature value from one unit to another.
def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32
def fahrenheit_to_celsius(fahrenheit):
return (fahrenheit - 32) * 5/9
def celsius_to_kelvin(celsius):
return celsius + 273.15
def kelvin_to_celsius(kelvin):
return kelvin - 273.15
def fahrenheit_to_kelvin(fahrenheit):
celsius = fahrenheit_to_celsius(fahrenheit)
return celsius_to_kelvin(celsius)
def kelvin_to_fahrenheit(kelvin):
celsius = kelvin_to_celsius(kelvin)
return celsius_to_fahrenheit(celsius)
return celsius_to_fahrenheit(value)
elif from_unit == "F" and to_unit == "C":
return fahrenheit_to_celsius(value)
elif from_unit == "C" and to_unit == "K":
return celsius_to_kelvin(value)
elif from_unit == "K" and to_unit == "C":
return kelvin_to_celsius(value)
elif from_unit == "F" and to_unit == "K":
return fahrenheit_to_kelvin(value)
elif from_unit == "K" and to_unit == "F":
return kelvin_to_fahrenheit(value)
else:
return "Invalid conversion"
# Example usage:
value = 100
from_unit = "C"
to_unit = "F"
converted_value = temperature_converter(value, from_unit, to_unit)
print(f"{value} {from_unit} is equal to {converted_value} {to_unit}")
# Example usage:
start_num = int(input("Enter the start number: "))
end_num = int(input("Enter the end number: "))
if choice.lower() == 'even':
numbers = display_even_or_odd(start_num, end_num, even=True)
print("Even numbers between", start_num, "and", end_num, "are:", numbers)
elif choice.lower() == 'odd':
numbers = display_even_or_odd(start_num, end_num, even=False)
#Output
Enter the start number: 5
Enter the end number: 20
Which numbers do you want to display?
Enter 'even' for even numbers or 'odd' for odd numbers: even
Even numbers between 5 and 20 are: [6, 8, 10, 12, 14, 16, 18, 20]
def is_prime(n):
if n <= 1:
return False
elif n <= 3:
return True
elif n % 2 == 0 or n % 3 == 0:
return False
i=5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
if is_prime(num):
print(num, "is a prime number")
else:
print(num, "is not a prime number")
#Output
Enter a number: 32
32 is not a prime number
d) Find the sum of all the numbers between given two numbers.
def main():
start = int(input("Enter the starting number: "))
end = int(input("Enter the ending number: "))
if __name__ == "__main__":
main()
#output
Enter the starting number: 10
Enter the ending number: 20
The sum of numbers between 10 and 20 is: 165
Armstrong number is a number that is equal to the sum of cubes of its digits. For example
0, 1, 153, 370, 371 and 407 are the Armstrong numbers.
153 = (1*1*1)+(5*5*5)+(3*3*3)
where: (1*1*1)=1 ; (5*5*5)=125 ; (3*3*3)=27
So: 1+125+27=153
def is_armstrong_number(num):
# Convert the number to a string to count the digits
num_str = str(num)
# Get the number of digits
num_digits = len(num_str)
# Initialize sum to 0
sum_of_cubes = 0
# Iterate through each digit and calculate the sum of cubes
for digit in num_str:
sum_of_cubes += int(digit) ** num_digits
def main():
num = int(input("Enter a number: "))
if is_armstrong_number(num):
print(num, "is an Armstrong number.")
else:
print(num, "is not an Armstrong number.")
if __name__ == "__main__":
main()
#Output
Enter a number: 321
321 is not an Armstrong number.
def fibonacci(n):
fib_series = []
if n <= 0:
return fib_series
elif n == 1:
fib_series.append(0)
else:
fib_series = [0, 1]
for i in range(2, n):
fib_series.append(fib_series[-1] + fib_series[-2])
return fib_series
def main():
n = int(input("Enter the value of n to display the first n Fibonacci numbers: "))
if n <= 0:
print("Please enter a positive integer.")
else:
fib_series = fibonacci(n)
print("First", n, "Fibonacci numbers:")
print(fib_series)
if __name__ == "__main__":
main()
#OUTPUT
Enter the value of n to display the first n Fibonacci numbers: 10
First 10 Fibonacci numbers:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
1. First, find the GCD (Greatest Common Divisor) of the two numbers.
2. Then, use the formula: LCM (a, b) = (a * b) / GCD (a, b).
def main():
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if __name__ == "__main__":
main()
#OUTPUT
Enter first number: 12
Enter second number: 18
LCM of 12 and 18 is: 36
def main():
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if __name__ == "__main__":
main()
#OUTPUT
Enter first number: 24
Enter second number: 36
HCF of 24 and 36 is: 12
=5+(4+(3+(2+(1+0))))=5+(4+(3+(2+(1+0)))) =15
def sum_up_to_n_recursive(n):
if n == 0:
return 0
else:
return n + sum_up_to_n_recursive(n - 1)
def main():
num = int(input("Enter a number: "))
if num < 0:
print("Please enter a non-negative integer.")
else:
result = sum_up_to_n_recursive(num)
print("Sum of all numbers up to", num, "is:", result)
if __name__ == "__main__":
main()
#OUTPUT
Enter a number: 5
Sum of all numbers up to 5 is: 15
def main():
num = int(input("Enter a number: "))
if num < 0:
print("Factorial is not defined for negative numbers.")
else:
result = factorial_recursive(num)
print("Factorial of", num, "is:", result)
if __name__ == "__main__":
main()
#OUTPUT
Enter a number: 5
Factorial of 5 is: 120
def main():
text = input("Enter a string: ")
string_operations(text)
if __name__ == "__main__":
main()
#OUTPUT
Enter a string: hello world! How are you today?
Original string: hello world! How are you today?
Length of the string: 31
Splitting the string: ['hello', 'world!', 'How', 'are', 'you', 'today?']
Joining the string with '_': hello_world!_How_are_you_today?
Uppercase: HELLO WORLD! HOW ARE YOU TODAY?
Lowercase: hello world! how are you today?
Swapping case: HELLO WORLD! hOW ARE YOU TODAY?
Title case: Hello World! How Are You Today?
def main():
text = " hello world! "
string_operations(text)
if __name__ == "__main__":
main()
#OUTPUT
Original string: hello world! How are you today?
Finding 'world': 9
Index of 'world': 9
Count of 'o': 5
Replacing 'world' with 'Python': hello Python! How are you today?
Sorted characters: [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '!', '?', 'H', 'a', 'a', 'd', 'd', 'e', 'e', 'h', 'l',
'l', 'l', 'o', 'o', 'o', 'o', 'o', 'r', 'r', 't', 'u', 'w', 'w', 'y', 'y']
Stripped string: hello world! How are you today?
c) String slicing.
def string_slicing(text):
print("Original string:", text)
print("First three characters:", text[:3])
print("Characters from index 3 to 7:", text[3:8])
print("Last five characters:", text[-5:])
print("Every second character:", text[::2])
print("Reversed string:", text[::-1])
def main():
text = "Python Programming"
string_slicing(text)
if __name__ == "__main__":
main()
#OUTPUT
Original string: Mysore University School of Engineering
First three characters: Mys
Characters from index 3 to 7: ore U
Last five characters: ering
Every second character: Msr nvriySho fEgneig
Reversed string: gnireenignE fo loohcS ytisrevinU erosyM
#Adds all the elements of an iterable (e.g., another list) to the end of the list.
extend()
my_list = [1, 2, 3]
my_list.extend([4, 5])
print(my_list) # Output: [1, 2, 3, 4, 5]
#Sorts the list in ascending order by default. Can take parameters to sort in
descending order or by a key function sort()
my_list = [4, 2, 1, 3]
my_list.sort()
print(my_list) # Output: [1, 2, 3, 4]
#Returns a new list containing all items from the original list in ascending order. The
original list remains unchanged. sorted()
my_list = [4, 2, 1, 3]
new_list = sorted(my_list)
print(new_list) # Output: [1, 2, 3, 4]
print(my_list) # Output: [4, 2, 1, 3]
Tuple Operations
Tuples are immutable, so they do not support methods that modify the tuple, such as
append(), extend(), insert(), remove(), reverse(), clear(), and sort().
#Returns a new list containing all items from the tuple in ascending order
sorted()
my_tuple = (4, 2, 1, 3)
new_list = sorted(my_tuple)
print(new_list) # Output: [1, 2, 3, 4]
NOTE : Lists and tuples can be manipulated and analysed using Python's built-in methods
c. List comprehension: Creating list, Creating Matrix, Transpose of a Matrix, Addition,
Difference and Scalar multiplication of two matrices.
A concise way to create lists using a single line of code
i. Creating a Matrix
A list of lists representing a matrix.
Dictionary Operations
i. Add Element
# Adding a new key-value pair to the dictionary
my_dict = {'a': 1, 'b': 2}
my_dict['c'] = 3 # Adding new element
print(my_dict) # Output: {'a': 1, 'b': 2, 'c': 3}
iv. clear()
#Removes all items from the dictionary.
my_dict = {'a': 1, 'b': 2, 'c': 3}
my_dict.clear() # Clearing dictionary
print(my_dict) # Output: {}
v. copy()
#Returns a shallow copy of the dictionary
my_dict = {'a': 1, 'b': 2}
new_dict = my_dict.copy() # Copying dictionary
print(new_dict) # Output: {'a': 1, 'b': 2}
vi. values()
#Returns a view object that displays a list of all the values in the dictionary.
my_dict = {'a': 1, 'b': 2, 'c': 3}
values = my_dict.values()
print(values) # Output: dict_values([1, 2, 3])
vii. keys()
#Returns a view object that displays a list of all the keys in the dictionary.
my_dict = {'a': 1, 'b': 2, 'c': 3}
keys = my_dict.keys()
print(keys) # Output: dict_keys(['a', 'b', 'c'])
viii. items()
#Returns a view object that displays a list of dictionary's key-value tuple pairs.
my_dict = {'a': 1, 'b': 2, 'c': 3}
items = my_dict.items()
print(items) # Output: dict_items([('a', 1), ('b', 2), ('c', 3)])
Set Operations
ix.union()
#Returns a set containing all the unique elements from both sets.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
print(union_set) # Output: {1, 2, 3, 4, 5}
x. intersection()
#Returns a set containing the common elements from both sets.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1.intersection(set2)
print(intersection_set) # Output: {3}
xi. difference()
#Returns a set containing elements that are in the first set but not in the second set
set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = set1.difference(set2)
print(difference_set) # Output: {1, 2}
xii. symmetric_difference()
#Returns a set containing elements that are in either of the sets, but not in both.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
symmetric_difference_set = set1.symmetric_difference(set2)
print(symmetric_difference_set) # Output: {1, 2, 4, 5}
OR
# Python code to illustrate with()
with open("tv99_news.txt ") as file:
data = file.read()
print(data)
#output
TV99 News, Stay tuned for breaking news that breaks your trust. TV99 News,
delivering drama disguised as information.
Why did the scarecrow win an award? Because he was outstanding in his field!
OR
i. Creating a file using write command
# Python code to create a file
file = open('fun.txt','w')
file.write("Why did the scarecrow win an award? ")
file.write("Because he was outstanding in his field!")
file.close()
#output
Why did the scarecrow win an award? Because he was outstanding in his field!
ii. We can also use the written statement along with the with() function.
# Python code to illustrate with() alongwith write()
with open("file.txt", "w") as f:
f.write("Hello World!!!")
#output
Hello World!!!
#output
Why did the scarecrow win an award? Because he was outstanding in his field! This will
add this line
// For understanding
print("Content of 'example.txt':")
print(content)
#OUTPUT
Data written to 'example.txt' successfully.
Content of 'example.txt':
Python is a great programming language.
It is widely used in web development, data science, and automation.
Learning Python can be fun and rewarding.
NumPy is a powerful, open-source library in Python that is used for numerical and scientific
computing. It stands for "Numerical Python" and provides support for large, multi-
dimensional arrays and matrices, along with a collection of mathematical functions to
operate on these arrays efficiently.
Features of NumPy:
1. ndarray (N-Dimensional Array):
✓ Arrays in NumPy are like lists but optimized for numerical operations. They can be
indexed, sliced, and iterated over efficiently.
2. Broadcasting:
✓ Allows operations on arrays with different shapes without explicit looping, making
element-wise calculations straightforward.
3. Mathematical Functions:
✓ Provides a wide range of optimized functions for arithmetic, statistics, linear
algebra, and more, operating efficiently on entire arrays.
4. Linear Algebra:
✓ Includes functions for matrix operations like multiplication, finding determinants,
eigenvalues, and solving linear equations.
5. Random Number Generation:
✓ NumPy includes tools for generating random data, crucial for simulations, statistical
modeling, and other applications.
6. Integration with Other Libraries:
✓ Seamless integration with tools like SciPy for advanced scientific computing,
pandas for data analysis, and Matplotlib for visualization.
To start
import numpy as np
# Example matrix
matrix = np.array([[8, 3, 4], [2, 7, 1], [9, 6, 5]])
print("Original Matrix:\n", matrix)
#output Original Matrix: [[8 3 4] [2 7 1] [9 6 5]]
# Diagonal
diagonal_elements = matrix.diagonal()
print("\nDiagonal elements:", diagonal_elements)
#output Diagonal elements: [8 7 5]
# Max
max_element = matrix.max()
print("Maximum element:", max_element)
#output Maximum element: 9
# Min
min_element = matrix.min()
print("Minimum element:", min_element)
#output Minimum element: 1
# Sum
sum_elements = matrix.sum()
print("Sum of all elements:", sum_elements)
#output Sum of all elements: 45
# Mean
mean_value = matrix.mean()
print("Mean of all elements:", mean_value)
#output Mean of all elements: 5.0
# Sort
sorted_matrix = np.sort(matrix, axis=None).reshape(matrix.shape)
print("Sorted Matrix:\n", sorted_matrix)
#output Sorted Matrix: [[1 2 3] [4 5 6] [7 8 9]]
# Transpose
transpose_matrix = matrix.transpose()
print("Transpose of the matrix:\n", transpose_matrix)
#output Transpose of the matrix: [[8 2 9] [3 7 6] [4 1 5]]
# Addition
matrix_addition = matrix1 + matrix2
print("\nMatrix Addition:\n", matrix_addition)
#output
Matrix Addition: [[10 10 10] [10 10 10] [10 10 10]]
# Subtraction
matrix_subtraction = matrix1 - matrix2
print("Matrix Subtraction:\n", matrix_subtraction)
#output
Matrix Subtraction: [[-8 -6 -4] [-2 0 2] [ 4 6 8]]
# Multiplication
matrix_multiplication = matrix1 * matrix2
print("Matrix Element-wise Multiplication:\n", matrix_multiplication)
#output
Matrix Element-wise Multiplication: [[ 9 16 21] [24 25 24] [21 16 9]]
# Division
matrix_division = matrix1 / matrix2
print("Matrix Element-wise Division:\n", matrix_division)
#output
Matrix Element-wise Division:
[[0.11111111 0.25 0.42857143] [0.66666667 1. 1.5 ] [2.33333333 4. 9. ]]
To handle data using pandas for the tasks you've mentioned, we'll go through each part
step-by-step.
Step 1: Install Pandas
pip install pandas
Step 2: Import Pandas and Create a Sample Data Frame
import pandas as pd
# Provided data
data = {
'Name': ['Puneeth Rajkumar', 'Yash', 'Rakshit Shetty', 'Deepika Padukone', 'Shah Rukh
Khan', 'Aishwarya Rai', 'Leonardo DiCaprio', 'Tom Hanks', 'Angelina Jolie'],
'Birth_Year': [1975, 1986, 1983, 1986, 1965, 1973, 1974, 1956, 1975],
'Industry': ['Kannada', 'Kannada', 'Kannada', 'Bollywood', 'Bollywood', 'Bollywood',
'Hollywood', 'Hollywood', 'Hollywood']
}
# Creating a DataFrame
df = pd.DataFrame(data)
#output
Bollywood Actors:
Name Birth_Year Industry
3 Deepika Padukone 1986 Bollywood
4 Shah Rukh Khan 1965 Bollywood
5 Aishwarya Rai 1973 Bollywood
#output
Birth_Year Industry
Name
Puneeth Rajkumar 1975 Kannada
Yash 1986 Kannada
Rakshit Shetty 1983 Kannada
Deepika Padukone 1986 Bollywood
Shah Rukh Khan 1965 Bollywood
Aishwarya Rai 1973 Bollywood
Leonardo DiCaprio 1974 Hollywood
Tom Hanks 1956 Hollywood
Birth_Year
count 9.000000
mean 1978.111111
std 7.497369
min 1956.000000
25% 1974.000000
50% 1975.000000
75% 1983.000000
max 1986.000000
Bollywood Actors:
Name Birth_Year Industry
3 Deepika Padukone 1986 Bollywood
4 Shah Rukh Khan 1965 Bollywood
5 Aishwarya Rai 1973 Bollywood
To get Excel data into Python, you can use the pandas library.
import pandas as pd
import pandas as pd
import matplotlib.pyplot as plt
plt.ylabel('Profit')
plt.show()
# Create a histogram
plt.figure(figsize=(10, 5))
plt.hist(df['Sales'], bins=5)
plt.title('Sales Distribution')
plt.xlabel('Sales')
plt.ylabel('Frequency')
plt.show()
Objective:
To interface the Sense HAT with Raspberry Pi and read sensor data.
Components Required:
• Raspberry Pi
• Sense HAT
• MicroSD card with Raspbian installed
• Power supply
• HDMI monitor, keyboard, and mouse (or remote access)
Sense Hat
The Sense HAT has an 8×8 RGB LED matrix and a five-button joystick, and includes the
following sensors:
• Gyroscope
• Accelerometer
• Magnetometer
• Temperature
• Barometric pressure
• Humidity
• Colour and brightness
Procedure:
1. Hardware Setup:
o Attach the Sense HAT to the GPIO pins of the Raspberry Pi.
2. Software Setup:
sense = SenseHat()
sense.clear()
temp = sense.get_temperature()
print(temp)
humidity = sense.get_humidity()
print(humidity)
pressure = sense.get_pressure()
print(pressure)
# output
13.0328322501
45.7368595024
1013.03333333 https://trinket.io/sense-hat
python3 sense_hat_script.py
Observations:
To send a message
# Message to display
message = "MUSE is the Best Engineering college in Mysore"
Components Required:
• Raspberry Pi
• Stepper motor
• ULN2003 stepper motor driver
• Jumper wires
• Breadboard
Procedure:
1. Hardware Setup:
o Connect the stepper motor to the ULN2003 driver.
o Connect the IN1, IN2, IN3, and IN4 pins of the driver to GPIO pins on the Raspberry
Pi (e.g., GPIO17, GPIO18, GPIO27, GPIO22).
GPIO.setmode(GPIO.BCM)
control_pins = [17, 18, 27, 22]
halfstep_seq = [
[1,0,0,1],
[1,0,0,0],
[1,1,0,0],
[0,1,0,0],
[0,1,1,0],
[0,0,1,0],
[0,0,1,1],
[0,0,0,1]
]
for i in range(512):
for halfstep in range(8):
for pin in range(4):
GPIO.output(control_pins[pin], halfstep_seq[halfstep][pin])
time.sleep(0.001)
GPIO.cleanup()
Observations:
To interface a DC motor with Raspberry Pi and control its speed using PWM.
Components Required:
• Raspberry Pi
• DC motor
• L298N motor driver
• Jumper wires
• Breadboard
Procedure:
1. Hardware Setup:
o Connect the DC motor to the L298N driver.
o Connect the IN1 and IN2 pins of the driver to GPIO pins on the Raspberry Pi (e.g.,
GPIO17 and GPIO18).
o Connect the ENA pin of the driver to another GPIO pin (e.g., GPIO22) for PWM
control.
GPIO.setup(IN1, GPIO.OUT)
GPIO.setup(IN2, GPIO.OUT)
GPIO.setup(ENA, GPIO.OUT)
GPIO.output(IN1, GPIO.LOW)
GPIO.output(IN2, GPIO.LOW)
pwm.ChangeDutyCycle(abs(speed))
Components Required:
• Raspberry Pi
• OLED display (e.g., SSD1306)
• Jumper wires
• Breadboard
Procedure:
1. Hardware Setup:
o Connect the VCC, GND, SCL, and SDA pins of the OLED display to the corresponding
pins on the Raspberry Pi.
2. Install Required Libraries:
import Adafruit_SSD1306
from PIL import Image, ImageDraw, ImageFont
# Initialize library.
disp.begin()
# Clear display.
disp.clear()
disp.display()
# Draw text.
draw.text((0, 0), 'Hello, World!', font=font, fill=255)
# Display image.
disp.image(image)
disp.display()
Observations:
Questions
1) What is Python? What are the benefits of using Python?
Python is a programming language with objects, modules, threads, exceptions and automatic
memory management. The benefits of pythons are that it is simple and easy, portable, extensible,
build-in data structure and it is an open source.
2) What is PEP 8?
PEP 8 is a coding convention, a set of recommendation, about how to write your Python code more
readable.
Pickle module accepts any Python object and converts it into a string representation and dumps it into
a file by using dump function, this process is called pickling. While the process of retrieving original
Python objects from the stored string representation is called unpickling.
Python language is an interpreted language. Python program runs directly from the source code. It
converts the source code that is written by the programmer into an intermediate language, which is
again translated into machine language that has to be executed.
• Python memory is managed by Python private heap space. All Python objects and data structures are
located in a private heap. The programmer does not have an access to this private heap and interpreter
takes care of this Python private heap.
• The allocation of Python heap space for Python objects is done by Python memory manager. The core
API gives access to some tools for the programmer to code.
• Python also have an inbuilt garbage collector, which recycle all the unused memory and frees the
memory and makes it available to the heap space.
6) What are the tools that help to find bugs or perform static analysis?
PyChecker is a static analysis tool that detects the bugs in Python source code and warns about the
style and complexity of the bug. Pylint is another tool that verifies whether the module meets the
coding standard.
A Python decorator is a specific change that we make in Python syntax to alter functions easily.
The difference between list and tuple is that list is mutable while tuple is not. Tuple can be hashed for
e.g as a key for dictionaries.
Everything in Python is an object and all variables hold references to the objects. The references values
are according to the functions; as a result you cannot change the value of the references. However,
you can change the objects if it is mutable.
They are syntax constructions to ease the creation of a Dictionary or List based on existing iterable.
Disadvantages