0% found this document useful (0 votes)
20 views

Python Lab Manual

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Python Lab Manual

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

MYSORE UNIVERSITY SCHOOL OF

ENGINEERING
3/3/2024

Python for System


Programming lab
21BRL66

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.

Check Matrix operations using numpy.


7 a) diagonal(), max(), min(), sum(), mean(), sort(), transpose()
b) Arithmetic operations on matrix using arithmetic operators.
Handle data using pandas: Create an excel sheet and
8 a) Display statistical information, Perform queries on data.
b) Modify the index of the data, Sort the index.

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 1


2 Python for System Programming lab

c) Fill missing data.

9 Interface SenseHAT to Raspberry Pi.

10 Interface stepper motor to Raspberry Pi.

11 Interface dc motor to Raspberry Pi and control its speed using PWM.

12 Interface display device to Raspberry Pi.

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 2


3 Python for System Programming lab

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

radians() :The radians() function is a mathematical function that converts an angle


measured in degrees to radians. Radians are a unit of angular measurement used
in mathematics and physics, where a full circle corresponds to 2π radians.
radians(θ)= π /180*θ
For example: radians(90)=π/180×90= π /2 and radians(45)= π /180×45=π/4

import math
degree_angle = 45
radian_angle = math.radians(degree_angle)
print("radians({}) = {}".format(degree_angle, radian_angle))
# Output: radians(45) = 0.7853

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 3


4 Python for System Programming lab

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

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 4


5 Python for System Programming lab

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

• 𝒍𝒐𝒈𝟏𝟎 (𝟏𝟎𝟎) = 𝟐 𝒃𝒆𝒄𝒂𝒖𝒔𝒆 𝟏𝟎𝟐 = 𝟏𝟎𝟎


• 𝒍𝒐𝒈𝟏𝟎 (𝟏𝟎𝟎𝟎) = 𝟑 𝒃𝒆𝒄𝒂𝒖𝒔𝒆 𝟏𝟎𝟑 = 𝟏𝟎𝟎𝟎
import math
x = 100
result = math.log10(x)
print("log10({}) = {}".format(x, result)) # Output: log10(100) = 2.0

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),

satisfies the following properties:


1. gcd(a,b) divides both a and b.
2. Any common divisor of a and b is also a divisor of gcd(a,b).
3. gcd(a,b) is the largest such integer.
For example:
• gcd(12,18)=6 because 6 is the largest integer that divides both 12 and 18 without
leaving a remainder.
• gcd(9,15)=3gcd(9,15)=3, because 3 is the largest integer that divides both 9 and 15
without leaving a remainder.

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

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 5


6 Python for System Programming lab

whole number part.


import math
fractional, integer = math.modf(3.14)
print("Fractional part:", fractional) # Output: Fractional part:
0.14000000000000012
print("Integer part:", integer) # Output: Integer part: 3.0

vi. sqrt(x) : This function returns the square root of x.


import math
result = math.sqrt(16)
print("Square root of 16:", result) # Output: Square root of
16: 4.0

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)

def temperature_converter(value, from_unit, to_unit):


if from_unit == "C" and to_unit == "F":

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 6


7 Python for System Programming lab

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}")

b) Display all the even/odd numbers between given two numbers

def display_even_or_odd(start, end, even=True):


numbers = []
if even:
for num in range(start, end + 1):
if num % 2 == 0:
numbers.append(num)
else:
for num in range(start, end + 1):
if num % 2 != 0:
numbers.append(num)
return numbers

# Example usage:
start_num = int(input("Enter the start number: "))
end_num = int(input("Enter the end number: "))

print("Which numbers do you want to display?")


choice = input("Enter 'even' for even numbers or 'odd' for odd numbers: ")

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)

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 7


8 Python for System Programming lab

print("Odd numbers between", start_num, "and", end_num, "are:", numbers)


else:
print("Invalid choice!")

#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]

=== Code Execution Successful ===

c) Check whether the given number is a prime or not.

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

# Taking input from the user


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

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

=== Code Execution Successful ===

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 8


9 Python for System Programming lab

d) Find the sum of all the numbers between given two numbers.

def sum_of_numbers_between(start, end):


total = 0
for num in range(start, end + 1):
total += num
return total

def main():
start = int(input("Enter the starting number: "))
end = int(input("Enter the ending number: "))

if start > end:


print("Starting number should be less than or equal to the ending number.")
else:
result = sum_of_numbers_between(start, end)
print("The sum of numbers between", start, "and", end, "is:", result)

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

=== Code Execution Successful ===

e) Find whether the given number is an Armstrong number or not.

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

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 9


10 Python for System Programming lab

# Check if the sum of cubes is equal to the original number


return sum_of_cubes == num

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.

=== Code Execution Successful ===

f) Display first n Fibonacci numbers.

F(n)=F(n−1)+F(n−2) with initial conditions: F(0)=0 & F(1)=1

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__":

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 10


11 Python for System Programming lab

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]

=== Code Execution Successful ===

Implement user defined functions.


a. Function to find LCM of a number.

Step 1:- To find the LCM of 12 and 18:

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).

Step 2: Calculate the LCM using the formula:


LCM (12,18) =12×186=2166=36 So, the LCM of 12 and 18 is 36.

def gcd(x, y):


while(y):
x, y = y, x % y
return x

def lcm(x, y):


return (x * y) // gcd(x, y)

def main():
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

if num1 <= 0 or num2 <= 0:


print("Please enter positive integers.")
else:
result = lcm(num1, num2)
print("LCM of", num1, "and", num2, "is:", result)

if __name__ == "__main__":
main()

#OUTPUT
Enter first number: 12
Enter second number: 18
LCM of 12 and 18 is: 36

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 11


12 Python for System Programming lab

=== Code Execution Successful ===

b. Function to find HCF of a number.


def hcf(x, y):
while(y):
x, y = y, x % y
return x

def main():
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

if num1 <= 0 or num2 <= 0:


print("Please enter positive integers.")
else:
result = hcf(num1, num2)
print("HCF of", num1, "and", num2, "is:", result)

if __name__ == "__main__":
main()

#OUTPUT
Enter first number: 24
Enter second number: 36
HCF of 24 and 36 is: 12

=== Code Execution Successful ===

c. Recursive function to find sum of all numbers up to a given number.


To find the sum of all numbers up to 5 recursively:
sum_up_to_n_recursive(5) =5+sum_up_to_n_recursive(4)
=5+(4+sum_up_to_n_recursive(3))
=5+(4+(3+sum_up_to_n_recursive(2)))
=5+(4+(3+(2+sum_up_to_n_recursive(1))))
=5+(4+(3+(2+(1+sum_up_to_n_recursive(0)))))

=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:

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 12


13 Python for System Programming lab

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

=== Code Execution Successful ===

d. Recursive function to find factorial of a number.


def factorial_recursive(n):
if n == 0:
return 1
else:
return n * factorial_recursive(n - 1)

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

=== Code Execution Successful ===

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 13


14 Python for System Programming lab

Check String Operations:


a) len(), split(), join(), upper(), lower(), swapcase(), title(),
def string_operations(text):
print("Original string:", text)
print("Length of the string:", len(text))
print("Splitting the string:", text.split())
print("Joining the string with '_':", '_'.join(text.split()))
print("Uppercase:", text.upper())
print("Lowercase:", text.lower())
print("Swapping case:", text.swapcase())
print("Title case:", text.title())

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?

=== Code Execution Successful ===

b) Find(), index(), count(), replace(), sorted(), strip().


def string_operations(text):
print("Original string:", text)
print("Finding 'world':", text.find('world'))
print("Index of 'world':", text.index('world'))
print("Count of 'o':", text.count('o'))
print("Replacing 'world' with 'Python':", text.replace('world', 'Python'))
print("Sorted characters:", sorted(text))
print("Stripped string:", text.strip())

def main():
text = " hello world! "
string_operations(text)

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 14


15 Python for System Programming lab

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?

=== Code Execution Successful ===

Here's the output for each operation:

1. find(): Finds the first occurrence of a substring within the string.


o Output: Finding 'world': 6
2. index(): Returns the index of the first occurrence of a substring within the string.
Raises a ValueError if the substring is not found.
o Output: Index of 'world': 6
3. count(): Counts the number of occurrences of a substring within the string.
o Output: Count of 'o': 3
4. replace(): Replaces occurrences of a substring with another substring.
o Output: Replacing 'world' with 'Python': hello Python! How are you today?
5. sorted(): Sorts the characters of the string alphabetically and returns a list.
o Output: Sorted characters: [' ', ' ', ' ', '!', 'H', 'a', 'd', 'e', 'e', 'h', 'l', 'l', 'o', 'o', 'o', 'r',
'r', 't', 'w', 'y']
6. strip(): Removes leading and trailing whitespace characters.
o Output: 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)

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 15


16 Python for System Programming lab

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

=== Code Execution Successful ===

Check List and Tuple Operations.


a. len(), append(), extend(), insert(), remove().

#Returns the number of items in a list. len()


my_list = [1, 2, 3, 4, 5]
print(len(my_list)) # Output: 5

# Adds a single element to the end of the list. append()


my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]

#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]

#Inserts an element at a specified position insert()


my_list = [1, 2, 4]
my_list.insert(2, 3)
print(my_list) # Output: [1, 2, 3, 4]

#Removes the first occurrence of a specified value remove()


my_list = [1, 2, 3, 4, 3]
my_list.remove(3)
print(my_list) # Output: [1, 2, 4, 3]

b. reverse(), clear(), sort(), sorted(), count().


#Reverses the elements of the list in place reverse()
my_list = [1, 2, 3, 4]
my_list.reverse()
print(my_list) # Output: [4, 3, 2, 1]

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 16


17 Python for System Programming lab

#Removes all items from the list. clear()


my_list = [1, 2, 3, 4]
my_list.clear()
print(my_list) # Output: []

#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]

#Returns the number of occurrences of a specified value in the list


count()
my_list = [1, 2, 3, 2, 2, 4]
print(my_list.count(2)) # Output: 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 the number of items in a tuple. len()


my_tuple = (1, 2, 3, 4, 5)
print(len(my_tuple)) # Output: 5

#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]

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 17


18 Python for System Programming lab

#Returns the number of occurrences of a specified value in the tuple


count()
my_tuple = (1, 2, 3, 2, 2, 4)
print(my_tuple.count(2)) # Output: 3

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

# Creating a list of squares of numbers from 0 to 9


squares = [x**2 for x in range(10)]
print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

i. Creating a Matrix
A list of lists representing a matrix.

# Creating a 3x3 matrix


matrix = [[j for j in range(3)] for i in range(3)]
print(matrix) # Output: [[0, 1, 2], [0, 1, 2], [0, 1, 2]]

ii. Transpose of a Matrix


Interchanging rows and columns of a matrix.

# Transposing a 3x3 matrix


matrix = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
transpose = [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]
print(transpose) # Output: [[0, 3, 6], [1, 4, 7], [2, 5, 8]]

iii. Addition of Two Matrices


Adding corresponding elements of two matrices.
# Adding two 3x3 matrices
matrix1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix2 = [[9, 8, 7], [6, 5, 4], [3, 2, 1]]
addition = [[matrix1[i][j] + matrix2[i][j] for j in range(len(matrix1[0]))] for i in
range(len(matrix1))]
print(addition) # Output: [[10, 10, 10], [10, 10, 10], [10, 10, 10]]

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 18


19 Python for System Programming lab

iv. Difference of Two Matrices


Subtracting corresponding elements of two matrices.

# Subtracting two 3x3 matrices


matrix1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix2 = [[9, 8, 7], [6, 5, 4], [3, 2, 1]]
difference = [[matrix1[i][j] - matrix2[i][j] for j in range(len(matrix1[0]))] for i in
range(len(matrix1))]
print(difference) # Output: [[-8, -6, -4], [-2, 0, 2], [4, 6, 8]]

v. Scalar Multiplication of a Matrix


# Multiplying a 3x3 matrix by a scalar value 2
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
scalar = 2
scalar_multiplication = [[scalar * matrix[i][j] for j in range(len(matrix[0]))] for i in
range(len(matrix))]
print(scalar_multiplication) # Output: [[2, 4, 6], [8, 10, 12], [14, 16, 18]]
Note : To perform common matrix operations using list comprehensions in Python

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().

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}

ii. Modify Element


#Changing the value associated with a key
my_dict = {'a': 1, 'b': 2}
my_dict['a'] = 10 # Modifying existing element
print(my_dict) # Output: {'a': 10, 'b': 2}

iii. Delete Element


#Removing a key-value pair from the dictionary.
my_dict = {'a': 1, 'b': 2, 'c': 3}
del my_dict['b'] # Deleting element
print(my_dict) # Output: {'a': 1, 'c': 3}

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 19


20 Python for System Programming lab

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}

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 20


21 Python for System Programming lab

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}

Understand File Handling in Python


a. Read data from a file.
b. Write data into a file.

Prerequisite: A text file to created “tv99_news.txt”


"""TV99 News, Stay tuned for breaking news that breaks your trust. TV99 News, delivering drama
disguised as information."""

Following are the mode supported in python


f = open(filename, mode)
r: open an existing file for a read operation.
w: open an existing file for a write operation. If the file already contains some data, then
it will be overridden but if the file is not present then it creates the file as well.
a: open an existing file for append operation. It won’t override existing data.
r+: To read and write data into the file. The previous data in the file will be overridden.

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 21


22 Python for System Programming lab

w+: To write and read data. It will override existing data.


a+: To append and read data from the file. It won’t override existing data.
To read data from a file in Python, you can use the built-in open() function with the
mode 'r' for reading. The common methods used for reading data are read(),
readline(), and readlines().
a. Read Data from a File
file = open(' tv99_news.txt', 'r')

# This will print every line one by one in the file


for each in file:
print (each)
#output
TV99 News, Stay tuned for breaking news that breaks your trust. TV99 News,
delivering drama disguised as information

# Python code to illustrate read() mode


file = open("tv99_news.txt ", "r")
print (file.read())
#output
TV99 News, Stay tuned for breaking news that breaks your trust. TV99 News,
delivering drama disguised as information

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.

# Python code to illustrate read() mode character wise


file = open("tv99_news.txt ", "r")
print (file.read(4))
#output
TV99

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 22


23 Python for System Programming lab

# Python code to illustrate split() function


with open("tv99_news.txt ", "r") as file:
data = file.readlines()
for line in data:
word = line.split()
print (word)
#output
['TV99', 'News,', 'Stay', 'tuned', 'for', 'breaking', 'news', 'that', 'breaks', 'your', 'trust.',
'TV99', 'News,', 'delivering', 'drama', 'disguised', 'as', 'information.']

b. Write data into a file.


To write data to a file in Python, you can use the open() function with the mode
'w' for writing or 'a' for appending. The common methods used for writing data
are write() and writelines().

File with content “ fun.txt”

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!!!

iii. Working of Append Mode


# Python code to illustrate append() mode
file = open (‘fun.txt', 'a')
file.write("This will add this line")
file.close()

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 23


24 Python for System Programming lab

#output
Why did the scarecrow win an award? Because he was outstanding in his field! This will
add this line

// For understanding

# Step 1: Write Data into a File


content = """Python is a great programming language.
It is widely used in web development, data science, and automation.
Learning Python can be fun and rewarding."""

with open('example.txt', 'w') as file:


file.write(content)

print("Data written to 'example.txt' successfully.")

# Step 2: Read Data from a File


with open('example.txt', 'r') as file:
content = file.read()

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.

Check Matrix operations using numpy.


a. diagonal(), max(), min(), sum(), mean(), sort(), transpose()
b. Arithmetic operations on matrix using arithmetic operators.

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.

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 24


25 Python for System Programming lab

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

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 25


26 Python for System Programming lab

# 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]]

# Example matrices for arithmetic operations


matrix1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix2 = np.array([[9, 8, 7], [6, 5, 4], [3, 2, 1]])
print("\nMatrix 1:\n", matrix1)
print("Matrix 2:\n", matrix2)
#output
Matrix 1: [[1 2 3] [4 5 6] [7 8 9]]
Matrix 2: [[9 8 7] [6 5 4] [3 2 1]]

# 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]]

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 26


27 Python for System Programming lab

# 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. ]]

# Matrix Multiplication (Dot Product)


matrix_dot_product = np.dot(matrix1, matrix2)
print("Matrix Dot Product:\n", matrix_dot_product)
#output
Matrix Dot Product: [[ 30 24 18] [ 84 69 54] [138 114 90]]

Handle data using pandas:


a) Display statistical information, Perform queries on data.
b) Modify the index of the data, Sort the index.
c) Fill missing data.

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']
}

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 27


28 Python for System Programming lab

# Creating a DataFrame
df = pd.DataFrame(data)

# Displaying the DataFrame


print("Original DataFrame:\n", df)

Name Birth_Year Industry


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
Angelina Jolie 1975 Hollywood

# Display statistical information


print("\nStatistical Information:")
print(df.describe())

# Calculate mean birth year


mean_birth_year = df['Birth_Year'].mean()
print(f"\nMean Birth Year: {mean_birth_year}")
#output
mean 1978.111111

# Perform queries on data


print("\nBollywood Actors:")
print(df[df['Industry'] == 'Bollywood'])

#output
Bollywood Actors:
Name Birth_Year Industry
3 Deepika Padukone 1986 Bollywood
4 Shah Rukh Khan 1965 Bollywood
5 Aishwarya Rai 1973 Bollywood

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 28


29 Python for System Programming lab

print("\nActors born after 1980:")


print(df[df['Birth_Year'] > 1980])

Actors born after 1980:


Name Birth_Year Industry
1 Yash 1986 Kannada
3 Deepika Padukone 1986 Bollywood

# Removing Rakshit Shetty from the DataFrame


df = df[df['Name'] != ' Rakshit Shetty ']

Name Birth_Year Industry


Puneeth Rajkumar 1975 Kannada
Yash 1986 Kannada
Deepika Padukone 1986 Bollywood
Shah Rukh Khan 1965 Bollywood
Aishwarya Rai 1973 Bollywood
Leonardo DiCaprio 1974 Hollywood
Tom Hanks 1956 Hollywood
Angelina Jolie 1975 Hollywood

Part b) Modify Index of the Data and Sort the Index


# Modify index of the data
df.set_index('Name', inplace=True)
print("\nDataFrame with modified index:")
print(df)

#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

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 29


30 Python for System Programming lab

Angelina Jolie 1975 Hollywood

# Sort the index


df.sort_index(inplace=True)
print("\nDataFrame after sorting index:")
print(df)

Part c) Fill Missing Data


# Adding missing data for demonstration (hypothetical)
df.loc['Tom Hanks', 'Birth_Year'] = pd.NA
df.loc['Tom Hanks', 'Industry'] = pd.NA

# Display DataFrame with missing data


print("\nDataFrame with missing data:")
print(df)

# Fill missing data with forward fill method


df.fillna(method='ffill', inplace=True)
print("\nDataFrame after filling missing data:")
print(df)

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

Mean Birth Year: 1978.111111111111

Bollywood Actors:
Name Birth_Year Industry
3 Deepika Padukone 1986 Bollywood
4 Shah Rukh Khan 1965 Bollywood
5 Aishwarya Rai 1973 Bollywood

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 30


31 Python for System Programming lab

Actors born after 1980:


Name Birth_Year Industry
1 Yash 1986 Kannada
3 Deepika Padukone 1986 Bollywood

To get Excel data into Python, you can use the pandas library.

Install pandas and openpyxl

pip install pandas openpyxl

import pandas as pd # Import the necessary libraries

# Read the Excel file


df = pd.read_excel('path_to_your_file.xlsx', sheet_name='Sheet1')
#Display the DataFrame
print(df)

import pandas as pd

# Load the Excel file


file_path = 'example.xlsx' # Replace with your file path
sheet_name = 'Sheet1' # Replace with your sheet name if different

# Read the Excel file into a DataFrame


df = pd.read_excel(file_path, sheet_name=sheet_name)

# Display the DataFrame


print(df)

Create and display a graph:

Date Sales Profit Category Region


2024-01-01 100 30 A North
2024-01-02 150 50 B South
2024-01-03 200 70 A East
2024-01-04 130 40 C West
2024-01-05 170 60 B North

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 31


32 Python for System Programming lab

Read the Excel file and create various plots:


Line Plot: Sales over time.
Bar Plot: Sales over time.
Scatter Plot: Sales vs. Profit.
Histogram: Distribution of Sales.
Pie Chart: Distribution of Categories.

import pandas as pd
import matplotlib.pyplot as plt

# Load the Excel file


file_path = 'data.xlsx' # Replace with your file path

# Read the Excel file into a DataFrame


df = pd.read_excel(file_path)

# Display the DataFrame


print(df)

# Create a line plot


plt.figure(figsize=(10, 5))
plt.plot(df['Date'], df['Sales'], marker='o')
plt.title('Sales Over Time')
plt.xlabel('Date')
plt.ylabel('Sales')
plt.grid(True)
plt.show()

# Create a bar plot


plt.figure(figsize=(10, 5))
plt.bar(df['Date'], df['Sales'])
plt.title('Sales Over Time')
plt.xlabel('Date')
plt.ylabel('Sales')
plt.show()

# Create a scatter plot


plt.figure(figsize=(10, 5))
plt.scatter(df['Sales'], df['Profit'])
plt.title('Sales vs Profit')
plt.xlabel('Sales')

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 32


33 Python for System Programming lab

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()

# Create a pie chart


plt.figure(figsize=(8, 8))
df['Category'].value_counts().plot.pie(autopct='%1.1f%%')
plt.title('Category Distribution')
plt.ylabel('')
plt.show()

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 33


34 Python for System Programming lab

HARDWARE / SIMULATION PROGRAM


1. Interface SenseHAT to Raspberry Pi.

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:

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 34


35 Python for System Programming lab

o Boot up the Raspberry Pi.


o Open a terminal window.

3. Install Sense HAT Library:

sudo apt-get update


sudo apt-get install sense-hat

4. Python Script to Read Sensor Data:

from sense_hat import SenseHat

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

5. Run the Script:

python3 sense_hat_script.py

Observations:

Record the readings displayed on the terminal.

To send a message

from sense_hat import SenseHat


from time import sleep

# Initialize Sense HAT


sense = SenseHat()

# Message to display
message = "MUSE is the Best Engineering college in Mysore"

# Text color (red) and background color (black)


text_color = (255, 0, 0)
back_color = (0, 0, 0)

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 35


36 Python for System Programming lab

# Display the message


sense.show_message(message, text_colour=text_color, back_colour=back_color,
scroll_speed=0.1)

# Clear the display after the message has scrolled through


sense.clear()

Interfacing Stepper Motor with Raspberry Pi


Objective:

To interface a stepper motor with Raspberry Pi and control its rotation.

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).

2. Python Script to Control Stepper Motor:


import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
control_pins = [17, 18, 27, 22]

for pin in control_pins:


GPIO.setup(pin, GPIO.OUT)
GPIO.output(pin, 0)

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 36


37 Python for System Programming lab

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:

Record the rotation of the stepper motor.

Interfacing DC Motor with Raspberry Pi and Controlling its Speed using


PWM
Objective:

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.

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 37


38 Python for System Programming lab

3. Python Script to Control Stepper Motor:

import RPi.GPIO as GPIO


import time
GPIO.setmode(GPIO.BCM)
IN1 = 17
IN2 = 18
ENA = 22

GPIO.setup(IN1, GPIO.OUT)
GPIO.setup(IN2, GPIO.OUT)
GPIO.setup(ENA, GPIO.OUT)

pwm = GPIO.PWM(ENA, 1000) # PWM frequency


pwm.start(0) # Start PWM with 0% duty cycle

# Function to set motor direction and speed


def set_motor(speed):
if speed > 0:
GPIO.output(IN1, GPIO.HIGH)
GPIO.output(IN2, GPIO.LOW)
elif speed < 0:
GPIO.output(IN1, GPIO.LOW)
GPIO.output(IN2, GPIO.HIGH)
else:

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 38


39 Python for System Programming lab

GPIO.output(IN1, GPIO.LOW)
GPIO.output(IN2, GPIO.LOW)
pwm.ChangeDutyCycle(abs(speed))

# Set motor speed to 50%


set_motor(50)
time.sleep(5)

# Stop the motor


set_motor(0)
pwm.stop()
GPIO.cleanup()
Observations:

Record the speed of the DC motor at different PWM values.

Interfacing Display Device with Raspberry Pi


Objective:

To interface an OLED display with Raspberry Pi and display text.

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:

sudo apt-get update


sudo apt-get install python3-pip
pip3 install Adafruit-SSD1306
pip3 install Adafruit-GPIO
pip3 install Adafruit-BBIO
pip3 install Pillow

3. Python Script to Display Text on OLED:

import Adafruit_SSD1306
from PIL import Image, ImageDraw, ImageFont

# Raspberry Pi pin configuration:


RST = None

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 39


40 Python for System Programming lab

# 128x64 display with hardware I2C:


disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST)

# Initialize library.
disp.begin()

# Clear display.
disp.clear()
disp.display()

# Create blank image for drawing.


width = disp.width
height = disp.height
image = Image.new('1', (width, height))

# Get drawing object to draw on image.


draw = ImageDraw.Draw(image)

# Draw a black filled box to clear the image.


draw.rectangle((0,0,width,height), outline=0, fill=0)

# Load default font.


font = ImageFont.load_default()

# Draw text.
draw.text((0, 0), 'Hello, World!', font=font, fill=255)

# Display image.
disp.image(image)
disp.display()

Observations:

Observe the text displayed on the OLED screen.

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 40


41 Python for System Programming lab

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.

3) What is pickling and unpickling?

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.

4) How Python is interpreted?

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.

5) How memory is managed in Python?

• 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.

7) What are Python decorators?

A Python decorator is a specific change that we make in Python syntax to alter functions easily.

8) What is the difference between list and tuple?

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 41


42 Python for System Programming lab

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.

9) How are arguments passed by value or by reference?

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.

10) What is Dict and List comprehensions are?

They are syntax constructions to ease the creation of a Dictionary or List based on existing iterable.

11) What are the built-in type does python provides?

There are mutable and Immutable types of Pythons built in types

Mutable built-in types - • List • Sets • Dictionaries


Immutable built-in types - • Strings • Tuples • Numbers

File Handling in Python


ADVANTAGES
▪ Versatility: File handling in Python allows you to perform a wide range of
operations, such as creating, reading, writing, appending, renaming, and deleting
files.
▪ Flexibility: File handling in Python is highly flexible, as it allows you to work with
different file types (e.g. text files, binary files, CSV files, etc.), and to perform
different operations on files (e.g. read, write, append, etc.).
▪ User–friendly: Python provides a user-friendly interface for file handling, making
it easy to create, read, and manipulate files.
▪ Cross-platform: Python file-handling functions work across different platforms
(e.g. Windows, Mac, Linux), allowing for seamless integration and compatibility.

Disadvantages

• Error-prone: File handling operations in Python can be prone to errors, especially


if the code is not carefully written or if there are issues with the file system (e.g.
file permissions, file locks, etc.).
• Security risks: File handling in Python can also pose security risks, especially if
the program accepts user input that can be used to access or modify sensitive files
on the system.
• Complexity: File handling in Python can be complex, especially when working
with more advanced file formats or operations. Careful attention must be paid to
the code to ensure that files are handled properly and securely.
• Performance: File handling operations in Python can be slower than other
programming languages, especially when dealing with large files or performing
complex operations.

DEPT OF BIOMEDICAL AND ROBOTIC ENGINEERING 42

You might also like