Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Python for System Programming Lab
(21BRL67)
Laboratory Manual with Experiments
Name of the Student:
Register Number:
Branch:
Semester:
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM.
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Department of Bio Medical and Robotic Engineering
Laboratory Certificate
This is to certify that Mr. / Ms. ______________________________________________
bearing Register Number _______________________, Branch: Bio Medical and Robotic
Engineering has satisfactorily completed all the experiments in the course: Python for
System Programming Laboratory course code: 21BRL67 prescribed by the School of
Engineering for 6th Semester B.E Program of the academic year 20____ -20____
_________________________________
Signature of the Candidate
Marks obtained in words:__________________________________________________________
_________________________________ _________________________________
Signature of Faculty Head of the Department
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM.
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Course Content
Introduction to Python
List of Experiments
Observation
E.No. Experiment Date
(20 Marks)
Check math functions.
1 a) floor(), ceil(), trunc(), radians(), degrees(), sin(), cos(), tan().
b) fmod(), log10(), gcd(), pow(), modf().sqrt(), exp().
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
2 c) Check whether the given number is a prime or not.
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) Find(), 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.
6 c) union(), intersection(), difference(), symmetrical_difference().
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
a) Display statistical information, Perform queries on data.
8
b) Modify the index of the data, Sort the index.
c) Fill missing data.
Final Average for 20 Marks
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM.
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Introduction to Python
To install Python and PyCharm, first download the latest Python version from python.org and install it, making
sure to add Python to your system's PATH. Then, download the PyCharm Community Edition
from JetBrains and follow the installation wizard.
Installing Python:
• Download Python: Go to python.org/downloads and download the appropriate installer for your
operating system (Windows, macOS, or Linux).
• Run the Installer: Double-click the downloaded installer and follow the on-screen instructions.
• Add Python to PATH (Important): During installation, make sure to check the box that says "Add
Python to PATH". This allows you to run Python from the command line.
• Verify Installation: Open a command prompt or terminal and type python --version or python3 --
version to confirm that Python is installed and accessible.
Installing PyCharm:
• Download PyCharm: Go to JetBrains' website and download the PyCharm Community Edition (free
and open-source) or the Professional Edition (paid, with more features).
• Run the Installer: Double-click the downloaded installer and follow the on-screen instructions.
• Configure PyCharm: After installation, open PyCharm and create a new project. PyCharm will guide
you through setting up a Python interpreter and virtual environment.
• Testing PyCharm: Create a new Python file and write a simple "Hello, World!" program to test that
PyCharm is working correctly.
Creating Your First Project in PyCharm
When you first use PyCharm, you'll be welcomed by its startup screen.
To create a blank Python project, click on "New project." PyCharm will now prompt you to configure the
Python project:
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM.
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
For the virtual environment, select Conda. PyCharm
automatically makes the virtual environment's name match
the project name, and this is something we wish to keep as
it makes things less confusing.
The setup page also asks if you want to create
a main.py welcome script; for this project, you should keep
this option checked. This will have PyCharm create a basic
Python file for you instead of just preparing a blank
directory. Once the setup is complete, click "Create."
After creating your project, you'll land in the main PyCharm interface.
For now, let's run this file:
This opens the "Run" panel at the bottom of the window, displaying the output:
The text "Process finished with exit code 0" indicates that the program ran without errors. Our main.py code
is designed to display "Hi, PyCharm," and it has executed correctly.
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM.
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Basic Python Commands
Here are some basic Python commands and concepts for beginners:
1. Printing to the Console: The print() function is used to output text or data to the console.
print("Hello, World!")
2. Variables and Data Types: Variables are used to store data, and Python supports various data types,
including strings, integers, and floats.
# Integer
x=5
# Float
y = 3.14
# String
name = "Alice"
# Boolean
is_active = True
3. Input from the User: You can use input() to get input from the user, which is always returned as a string.
name = input("Enter your name: ")
age = int(input("Enter your age: ")) # Convert to integer
print(f"Hello {name}, you are {age} years old.")
4. Basic Arithmetic Operations: Python supports basic arithmetic operations like addition, subtraction,
multiplication, division, and more.
a = 10
b=5
sum_result = a + b # Addition
diff_result = a - b # Subtraction
prod_result = a * b # Multiplication
div_result = a / b # Division
5. Conditional Statements (if, elif, else): You can control the flow of your program with conditions.
age = 18
if age >= 18:
print("You are an adult.")
elif age > 12:
print("You are a teenager.")
else:
print("You are a child.")
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM.
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
6. Loops (for, while): Loops allow you to repeat actions multiple times.
for loop example:
# Print numbers 1 to 5
for i in range(1, 6):
print(i)
while loop example:
# Print numbers from 1 to 5
i=1
while i <= 5:
print(i)
i += 1
7. Lists: A list stores multiple items in an ordered collection. You can use indexing to access elements.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: apple
You can add, remove, or modify elements in a list:
fruits.append("orange") # Add to the end
fruits.remove("banana") # Remove item
8. Functions:
A function is a reusable block of code that performs a specific task.
def greet(name):
print(f"Hello, {name}!")
greet("Alice") # Calling the function
9. Dictionaries:
A dictionary stores key-value pairs. You can use a key to access the corresponding value.
person = {"name": "Alice", "age": 25}
print(person["name"]) # Output: Alice
10. Comments:
Comments are used to explain code and are not executed by the program.
# This is a single-line comment
"""
This is a multi-line comment
"""
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM.
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
11. Basic String Operations: You can perform operations on strings like concatenation, slicing,
and more.
greeting = "Hello"
name = "Alice"
message = greeting + " " + name # Concatenation
print(message) # Output: Hello Alice
# Slicing
print(message[0:5]) # Output: Hello
12. Type Conversion: You can convert data types in Python using functions like int(), float(), and str().
x = "10"
y = int(x) # Convert string to integer
z = float(x) # Convert string to float
13. Indentation: Python uses indentation (whitespace) to define the structure of the program, such as blocks
of code inside loops, conditionals, and functions.
if True:
print("This is indented correctly.")
14. Error Handling (try, except): To handle errors and exceptions, you can use try and except.
try:
number = int(input("Enter a number: "))
print(10 / number)
except ValueError:
print("That's not a valid number!")
except ZeroDivisionError:
print("You cannot divide by zero!")
Key Concepts Recap:
1. Variables: Used to store data.
2. Data Types: Integer, Float, String, Boolean, etc.
3. Control Flow: if, elif, else, for, while.
4. Functions: Blocks of reusable code.
5. Collections: Lists, Dictionaries.
6. Error Handling: try, except
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM.
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment No: 01
Aim: To Check math functions: floor(), ceil(), trunc(), radians(), degrees(), sin(), cos(), tan(). fmod(),
log10(), gcd(), pow(), modf().sqrt(), exp().
import math
# Sample number
num = 45.67
num2 = 8
num3 = 16
num4 = 2
# 1. floor() - returns the largest integer less than or equal to the number
floor_value = math.floor(num)
print(f"floor({num}) = {floor_value}")
# 2. ceil() - returns the smallest integer greater than or equal to the number
ceil_value = math.ceil(num)
print(f"ceil({num}) = {ceil_value}")
# 3. trunc() - returns the truncated integer part of the number
trunc_value = math.trunc(num)
print(f"trunc({num}) = {trunc_value}")
# 4. radians() - converts degrees to radians
radians_value = math.radians(45)
print(f"radians(45) = {radians_value}")
# 5. degrees() - converts radians to degrees
degrees_value = math.degrees(math.pi / 4)
print(f"degrees(math.pi/4) = {degrees_value}")
# 6. sin() - returns the sine of a number (argument in radians)
sin_value = math.sin(math.radians(30)) # 30 degrees converted to radians
print(f"sin(30 degrees) = {sin_value}")
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 1
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
# 7. cos() - returns the cosine of a number (argument in radians)
cos_value = math.cos(math.radians(60)) # 60 degrees converted to radians
print(f"cos(60 degrees) = {cos_value}")
# 8. tan() - returns the tangent of a number (argument in radians)
tan_value = math.tan(math.radians(45)) # 45 degrees converted to radians
print(f"tan(45 degrees) = {tan_value}")
# 9. fmod() - returns the remainder of the division of the two numbers
fmod_value = math.fmod(num, num2)
print(f"fmod({num}, {num2}) = {fmod_value}")
# 10. log10() - returns the base-10 logarithm of the number
log10_value = math.log10(num3)
print(f"log10({num3}) = {log10_value}")
# 11. gcd() - returns the greatest common divisor of two integers
gcd_value = math.gcd(num2, 12)
print(f"gcd({num2}, 12) = {gcd_value}")
# 12. pow() - returns the value of the first number raised to the power of the second number
pow_value = math.pow(num2, 3) # 8 raised to the power of 3
print(f"pow({num2}, 3) = {pow_value}")
# 13. modf() - returns the fractional and integer parts of a number as a tuple
modf_value = math.modf(num)
print(f"modf({num}) = {modf_value}")
# 14. sqrt() - returns the square root of the number
sqrt_value = math.sqrt(num3)
print(f"sqrt({num3}) = {sqrt_value}")
# 15. exp() - returns e raised to the power of the number
exp_value = math.exp(2) # e^2
print(f"exp(2) = {exp_value}")
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 2
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Explanation:
1. floor(): Rounds down to the nearest integer.
2. ceil(): Rounds up to the nearest integer.
3. trunc(): Removes the decimal part of the number.
4. radians(): Converts degrees to radians.
5. degrees(): Converts radians to degrees.
6. sin(), cos(), tan(): Trigonometric functions (input should be in radians).
7. fmod(): Returns the remainder after division (like modulus but with floating-point numbers).
8. log10(): Base-10 logarithm of a number.
9. gcd(): Greatest common divisor of two integers.
10. pow(): Raises the first number to the power of the second number.
11. modf(): Returns the fractional and integer parts of a number as a tuple.
12. sqrt(): Computes the square root of a number.
13. exp(): Returns the value of e raised to the power of the input.
Sample Output:
floor(45.67) = 45
ceil(45.67) = 46
trunc(45.67) = 45
radians(45) = 0.7853981633974483
degrees(0.7853981633974483) = 45.0
sin(30 degrees) = 0.49999999999999994
cos(60 degrees) = 0.49999999999999994
tan(45 degrees) = 0.9999999999999999
fmod(45.67, 8) = 5.669999999999998
log10(16) = 1.2041199826559193
gcd(8, 12) = 4
pow(8, 3) = 512.0
modf(45.67) = (0.6700000000000017, 45.0)
sqrt(16) = 4.0
exp(2) = 7.3890560989306495
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 3
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment No: 01
Students Signature: Staff Signature: Marks:
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 4
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment No: 01
Students Signature: Staff Signature: Marks:
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 5
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment No: 02
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
c) Check whether the given number is a prime or not.
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.
These exercises will help you practice various control flow concepts such as conditional statements (if, else),
loops (for, while), and handling user input. Each program contains a simple user interface for input and
provides an immediate output. You can extend these exercises by adding error handling and more complex
features later on.
a) Convert the temperature value from one unit to another
Write a program that converts a temperature from Celsius to Fahrenheit or vice versa, depending on the user's
choice.
def convert_temperature():
print("Temperature Conversion:")
print("1. Celsius to Fahrenheit")
print("2. Fahrenheit to Celsius")
choice = int(input("Choose an option (1 or 2): "))
if choice == 1:
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius} Celsius is equal to {fahrenheit} Fahrenheit")
elif choice == 2:
fahrenheit = float(input("Enter temperature in Fahrenheit: "))
celsius = (fahrenheit - 32) * 5/9
print(f"{fahrenheit} Fahrenheit is equal to {celsius} Celsius")
else:
print("Invalid choice! Please select either 1 or 2.")
# Run the function
convert_temperature()
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 6
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
b) Display all the even/odd numbers between given two numbers
Write a program that displays all even or odd numbers between two given numbers.
def display_even_odd_numbers():
start = int(input("Enter the starting number: "))
end = int(input("Enter the ending number: "))
choice = input("Display even or odd numbers? (even/odd): ").lower()
if choice == "even":
print(f"Even numbers between {start} and {end} are:")
for num in range(start, end + 1):
if num % 2 == 0:
print(num, end=" ")
elif choice == "odd":
print(f"Odd numbers between {start} and {end} are:")
for num in range(start, end + 1):
if num % 2 != 0:
print(num, end=" ")
else:
print("Invalid choice! Please enter 'even' or 'odd'.") # Run the function
display_even_odd_numbers()
c) Check whether the given number is a prime or not
Write a program to check whether a given number is prime.
def is_prime():
num = int(input("Enter a number: "))
if num <= 1:
print(f"{num} is not a prime number.")
return
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
print(f"{num} is not a prime number.")
return
print(f"{num} is a prime number.") # Run the function
is_prime()
d) Find the sum of all the numbers between given two numbers
Write a program that calculates the sum of all numbers between two given numbers.
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 7
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
def sum_between_numbers():
start = int(input("Enter the starting number: "))
end = int(input("Enter the ending number: "))
total = 0
for num in range(start, end + 1):
total += num
print(f"The sum of numbers between {start} and {end} is: {total}") # Run the function
sum_between_numbers()
e) Find whether the given number is an Armstrong number or not
Write a program that checks if a given number is an Armstrong number (also known as a narcissistic number).
def is_armstrong():
num = int(input("Enter a number: "))
num_str = str(num)
num_digits = len(num_str)
total = sum(int(digit) ** num_digits for digit in num_str)
if total == num:
print(f"{num} is an Armstrong number.")
else:
print(f"{num} is not an Armstrong number.") # Run the function
is_armstrong()
f) Display first n Fibonacci numbers
Write a program to display the first n Fibonacci numbers.
def fibonacci_numbers():
n = int(input("Enter the number of Fibonacci numbers you want to display: "))
a, b = 0, 1
print(f"The first {n} Fibonacci numbers are:")
for _ in range(n):
print(a, end=" ")
a, b = b, a + b # Run the function
fibonacci_numbers()
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 8
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment No: 02
Students Signature: Staff Signature: Marks:
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 9
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment No: 02
Students Signature: Staff Signature: Marks:
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 10
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment No: 02
Students Signature: Staff Signature: Marks:
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 11
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment No: 02
Students Signature: Staff Signature: Marks:
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 12
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment No: 02
Students Signature: Staff Signature: Marks:
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 13
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment No: 02
Students Signature: Staff Signature: Marks:
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 14
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment No: 03
Implement user defined functions.
a) Function to find LCM of a number.
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.
a) Function to Find LCM of a Number
The LCM (Least Common Multiple) of two numbers is the smallest number that is a multiple of both
numbers.
def lcm(x, y):
# Find the greater number
greater = max(x, y)
while True:
if greater % x == 0 and greater % y == 0:
return greater
greater += 1
# Test the function
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print(f"LCM of {num1} and {num2} is {lcm(num1, num2)}")
b) Function to Find HCF of a Number
The HCF (Highest Common Factor), also called the GCD (Greatest Common Divisor), is the largest
number that divides both numbers.
def hcf(x, y):
# Loop until we find the common divisor
smaller = min(x, y)
for i in range(smaller, 0, -1):
if x % i == 0 and y % i == 0:
return i
# Test the function
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print(f"HCF of {num1} and {num2} is {hcf(num1, num2)}")
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 15
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
c) Recursive Function to Find Sum of All Numbers Up to a Given Number
This function uses recursion to calculate the sum of all numbers from 1 to n.
def sum_of_numbers(n): # Base case: when n is 0, the sum is 0
if n == 0:
return 0
else:
return n + sum_of_numbers(n - 1) # Test the function
num = int(input("Enter a number: "))
print(f"Sum of all numbers up to {num} is {sum_of_numbers(num)}")
d) Recursive Function to Find Factorial of a Number
This recursive function calculates the factorial of a number, where the factorial of n is
𝑛 ∗ (𝑛 − 1) ∗ (𝑛 − 2) ∗ . . .∗ 1.
def factorial(n): # Base case: factorial of 0 or 1 is 1
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1) # Test the function
num = int(input("Enter a number: "))
print(f"Factorial of {num} is {factorial(num)}")
Explanation of Each Function:
1. LCM Function:
o The function calculates the LCM by starting from the greater of the two numbers and checking
if it's divisible by both numbers. It continues this process by incrementing the greater number
until it finds the LCM.
2. HCF Function:
o The function finds the HCF by checking divisibility starting from the smaller of the two
numbers and working downwards until it finds the largest common divisor.
3. Recursive Sum Function:
o This function uses recursion to add all numbers from n down to 0. The base case is when n is
0, at which point the recursion stops.
4. Recursive Factorial Function:
o The function calculates the factorial of n recursively. The base case is when n is 0 or 1, where
the factorial is defined as 1.
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 16
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment No: 03
Students Signature: Staff Signature: Marks:
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 17
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment No: 03
Students Signature: Staff Signature: Marks:
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 18
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment No: 03
Students Signature: Staff Signature: Marks:
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 19
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment No: 03
Students Signature: Staff Signature: Marks:
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 20
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment No: 04
Check String Operations:
a) len(), split(), join(), upper(), lower(), swapcase(), title(),
b) Find(), index(), count(), replace(), sorted(), strip().
c) String slicing.
a) String Operations: len(), split(), join(), upper(), lower(), swapcase(), title()
# Sample string
text = "hello world! Welcome to Python programming."
# len() - Returns the length of the string
print(f"Length of the string: {len(text)}")
# split() - Splits the string into a list of words
words = text.split()
print(f"Split the string: {words}")
# join() - Joins a list of words into a single string
joined_text = " ".join(words)
print(f"Join the words: {joined_text}")
# upper() - Converts all characters to uppercase
upper_text = text.upper()
print(f"Uppercase: {upper_text}")
# lower() - Converts all characters to lowercase
lower_text = text.lower()
print(f"Lowercase: {lower_text}")
# swapcase() - Swaps the case of all characters
swapcase_text = text.swapcase()
print(f"Swapcase: {swapcase_text}")
# title() - Converts the first character of each word to uppercase
title_text = text.title()
print(f"Title case: {title_text}")
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 21
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
b) String Operations: find(), index(), count(), replace(), sorted(), strip()
# Sample string
text = " hello world! welcome to Python programming"
# find() - Returns the lowest index of the substring if found, else returns -1
find_result = text.find("world")
print(f"Index of 'world': {find_result}")
# index() - Similar to find(), but raises an error if the substring is not found
try:
index_result = text.index("Python")
print(f"Index of 'Python': {index_result}")
except ValueError:
print("Substring 'Python' not found using index()")
# count() - Returns the number of occurrences of a substring
count_result = text.count("o")
print(f"Count of 'o' in the string: {count_result}")
# replace() - Replaces a substring with another substring
replaced_text = text.replace("world", "universe")
print(f"Replaced 'world' with 'universe': {replaced_text}")
# sorted() - Sorts the characters of the string (returns a list)
sorted_text = sorted(text)
print(f"Sorted characters in the string: {sorted_text}")
# strip() - Removes leading and trailing spaces
stripped_text = text.strip()
print(f"Stripped string: '{stripped_text}'")
c) String Slicing
# Sample string
text = "hello world!"
# Slicing a string (start, stop, step)
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 22
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
substring1 = text[0:5] # From index 0 to 4 (not including index 5)
substring2 = text[6:] # From index 6 to the end
substring3 = text[:5] # From the beginning to index 4
substring4 = text[::2] # Every second character from the string
print(f"Substring from index 0 to 4: {substring1}")
print(f"Substring from index 6 to the end: {substring2}")
print(f"Substring from the beginning to index 4: {substring3}")
print(f"Every second character: {substring4}")
Explanation of Each Operation:
1. len(): Returns the length of the string (number of characters).
2. split(): Splits the string into a list of words (default is splitting by spaces).
3. join(): Joins a list of words back into a single string, with a specified separator.
4. upper(): Converts all characters in the string to uppercase.
5. lower(): Converts all characters in the string to lowercase.
6. swapcase(): Swaps the case of each character (lowercase becomes uppercase and vice versa).
7. title(): Converts the first character of each word to uppercase, and the rest to lowercase.
b) String Search and Manipulation:
1. find(): Returns the lowest index of the substring if found, else returns -1.
2. index(): Similar to find(), but raises an error if the substring is not found.
3. count(): Counts the number of occurrences of a substring in the string.
4. replace(): Replaces occurrences of a substring with another substring.
5. sorted(): Sorts the characters of the string alphabetically and returns them as a list.
6. strip(): Removes leading and trailing whitespace from the string.
c) String Slicing:
1. Slicing allows you to extract substrings from a string by specifying the start, stop, and step indices.
o text[start:end]: Extracts characters from index start to end-1.
o text[start:]: Extracts from index start to the end.
o text[:end]: Extracts from the start to index end-1.
o text[::step]: Extracts every step-th character.
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 23
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment No: 04
Students Signature: Staff Signature: Marks:
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 24
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment No: 04
Students Signature: Staff Signature: Marks:
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 25
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment No: 04
Students Signature: Staff Signature: Marks:
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 26
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment No: 05
Check List and Tuple Operations.
a) len(), append(), extend(), insert(), remove().
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.
a) List Operations: len(), append(), extend(), insert(), remove()
# List operations
my_list = [1, 2, 3, 4, 5]
# len() - Find the length of the list
print(f"Length of the list: {len(my_list)}")
# append() - Adds a single element to the end of the list
my_list.append(6)
print(f"List after append: {my_list}")
# extend() - Adds elements from another list to the end of the list
my_list.extend([7, 8, 9])
print(f"List after extend: {my_list}")
# insert() - Inserts an element at a specific position (index)
my_list.insert(2, 'a') # Insert 'a' at index 2
print(f"List after insert: {my_list}")
# remove() - Removes the first occurrence of a specific element
my_list.remove(4) # Remove element 4
print(f"List after remove: {my_list}")
b) List Operations: reverse(), clear(), sort(), sorted(), count()
# List operations
my_list = [5, 2, 9, 1, 5, 6]
# reverse() - Reverses the order of the elements in the list
my_list.reverse()
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 27
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
print(f"List after reverse: {my_list}")
# clear() - Removes all elements from the list
my_list.clear()
print(f"List after clear: {my_list}")
# sort() - Sorts the list in ascending order
my_list = [5, 2, 9, 1, 5, 6]
my_list.sort()
print(f"List after sort: {my_list}")
# sorted() - Returns a new sorted list without modifying the original list
sorted_list = sorted(my_list, reverse=True) # Sorted in descending order
print(f"Sorted list (descending): {sorted_list}")
# count() - Returns the count of the specified element
count_five = my_list.count(5)
print(f"Count of 5 in the list: {count_five}")
c) List Comprehension: Creating List, Creating Matrix, Transpose of a Matrix, Addition, Difference,
and Scalar Multiplication of Two Matrices
# List Comprehension: Creating List
squares = [x**2 for x in range(1, 6)] # List of squares from 1 to 5
print(f"List of squares: {squares}")
# Creating a Matrix using List Comprehension
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(f"Matrix: {matrix}")
# Transpose of a Matrix
transpose = [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]
print(f"Transpose of the matrix: {transpose}")
# Addition of Two Matrices
matrix_a = [[1, 2, 3], [4, 5, 6]]
matrix_b = [[7, 8, 9], [10, 11, 12]]
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 28
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
addition_result = [[matrix_a[i][j] + matrix_b[i][j] for j in range(len(matrix_a[0]))] for i in
range(len(matrix_a))]
print(f"Matrix addition result: {addition_result}")
# Difference of Two Matrices
difference_result = [[matrix_a[i][j] - matrix_b[i][j] for j in range(len(matrix_a[0]))] for i
in range(len(matrix_a))]
print(f"Matrix difference result: {difference_result}")
# Scalar Multiplication of a Matrix
scalar = 2
scalar_multiplication_result = [[scalar * matrix_a[i][j] for j in range(len(matrix_a[0]))]
for i in range(len(matrix_a))]
print(f"Scalar multiplication result (by {scalar}): {scalar_multiplication_result}")
Explanation of Each Operation:
1. List Operations:
o len(): Returns the number of elements in the list.
o append(): Adds an element to the end of the list.
o extend(): Adds multiple elements (from another list) to the end of the list.
o insert(): Inserts an element at a specified position (index) in the list.
o remove(): Removes the first occurrence of a specified element from the list.
2. More List Operations:
o reverse(): Reverses the order of elements in the list.
o clear(): Removes all elements from the list.
o sort(): Sorts the list in ascending order (modifies the list).
o sorted(): Returns a sorted version of the list (without modifying the original).
o count(): Counts how many times a specified element appears in the list.
3. List Comprehension:
o List comprehensions provide a concise way to create lists. The general syntax is [expression
for item in iterable].
o Matrix creation involves creating lists of lists, and we can perform operations like addition,
difference, and scalar multiplication using list comprehensions.
o Matrix Transpose: Transposing a matrix swaps rows with columns.
o Matrix Addition and Difference: Element-wise operations between two matrices.
o Scalar Multiplication: Each element of the matrix is multiplied by a scalar (constant).
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 29
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment No: 05
Students Signature: Staff Signature: Marks:
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 30
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment No: 05
Students Signature: Staff Signature: Marks:
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 31
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment No: 05
Students Signature: Staff Signature: Marks:
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 32
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment No: 06
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().
Understand File Handling in Python
a) Read data from a file.
b) Write data into a file.
Dictionary Operations
a) Add element, Modify element, Delete element, clear(), copy()
# Dictionary operations
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
# Add an element
my_dict["profession"] = "Engineer"
print(f"Dictionary after adding an element: {my_dict}")
# Modify an element
my_dict["age"] = 26
print(f"Dictionary after modifying an element: {my_dict}")
# Delete an element
del my_dict["city"]
print(f"Dictionary after deleting an element: {my_dict}")
# clear() - Clears the entire dictionary
my_dict.clear()
print(f"Dictionary after clear(): {my_dict}")
# copy() - Creates a shallow copy of the dictionary
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
copy_dict = my_dict.copy()
print(f"Original dictionary: {my_dict}")
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 33
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
print(f"Copied dictionary: {copy_dict}")
b) get() values, keys(), items()
# Dictionary for operations
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
# get() - Get value for a specific key
name = my_dict.get("name")
print(f"Value for 'name': {name}")
# keys() - Get all the keys of the dictionary
keys = my_dict.keys()
print(f"Keys in the dictionary: {keys}")
# items() - Get all key-value pairs in the dictionary
items = my_dict.items()
print(f"Key-Value pairs in the dictionary: {items}")
Set Operations: c) union(), intersection(), difference(), symmetric_difference()
# Set operations
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}
# union() - Returns a new set containing all elements from both sets
union_set = set_a.union(set_b)
print(f"Union of set_a and set_b: {union_set}")
# intersection() - Returns a new set containing common elements from both sets
intersection_set = set_a.intersection(set_b)
print(f"Intersection of set_a and set_b: {intersection_set}")
# difference() - Returns a new set containing elements of set_a that are not in set_b
difference_set = set_a.difference(set_b)
print(f"Difference between set_a and set_b: {difference_set}")
# symmetric_difference() - Returns a new set with elements that are in either set_a or set_b but not both
symmetric_difference_set = set_a.symmetric_difference(set_b)
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 34
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
print(f"Symmetric difference between set_a and set_b:
{symmetric_difference_set}")
File Handling in Python
a) Read Data from a File
# Read data from a file
filename = "sample.txt" # Make sure this file exists with some data
try:
with open(filename, "r") as file:
content = file.read()
print(f"Content of the file:\n{content}")
except FileNotFoundError:
print(f"The file {filename} was not found.")
b) Write Data into a File
# Write data to a file
filename = "output.txt"
data = "This is a test line in the file."
with open(filename, "w") as file:
file.write(data)
print(f"Data written to {filename}")
# Append data to the same file
additional_data = "\nThis is an additional line."
with open(filename, "a") as file:
file.write(additional_data)
print(f"Additional data appended to {filename}")
Explanation of Each Operation:
Dictionary Operations:
1. Add element: You can add a new key-value pair using dict[key] = value.
2. Modify element: You can modify an existing key's value using dict[key] = new_value.
3. Delete element: You can delete a key-value pair using del dict[key].
4. clear(): Removes all key-value pairs in the dictionary.
5. copy(): Returns a shallow copy of the dictionary.
Set Operations:
1. union(): Combines all elements from both sets, without duplicates.
2. intersection(): Finds the common elements between two sets.
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 35
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
3. difference(): Finds elements in the first set but not in the second.
4. symmetric_difference(): Finds elements that are in either set, but not in both.
File Handling in Python:
1. Reading data from a file: You can open a file in read mode ("r") and read its content.
2. Writing data into a file: You can open a file in write mode ("w") to overwrite or append mode ("a")
to add content to a file.
o Use with open(filename, "w") for automatic file closing after the operation.
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 36
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment No: 06
Students Signature: Staff Signature: Marks:
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 37
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment No: 06
Students Signature: Staff Signature: Marks:
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 38
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment No: 06
Students Signature: Staff Signature: Marks:
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 39
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment No: 07
Check Matrix operations using NumPy.
a) diagonal(), max(), min(), sum(), mean(), sort(), transpose()
b) Arithmetic operations on matrix using arithmetic operators.
Make sure you have NumPy installed in your Python environment (pip install numpy).
a) Matrix Operations using NumPy
import numpy as np
# Create a sample matrix
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# diagonal() - Extracts the diagonal of the matrix
diagonal_elements = np.diagonal(matrix)
print(f"Diagonal elements of the matrix: {diagonal_elements}")
# max() - Find the maximum element in the entire matrix
max_value = np.max(matrix)
print(f"Maximum value in the matrix: {max_value}")
# min() - Find the minimum element in the entire matrix
min_value = np.min(matrix)
print(f"Minimum value in the matrix: {min_value}")
# sum() - Sum of all elements in the matrix
sum_value = np.sum(matrix)
print(f"Sum of all elements in the matrix: {sum_value}")
# mean() - Mean (average) of all elements in the matrix
mean_value = np.mean(matrix)
print(f"Mean value of the matrix: {mean_value}")
# sort() - Sort the elements of the matrix
sorted_matrix = np.sort(matrix, axis=None) # Flatten the matrix and sort it
print(f"Sorted elements of the matrix: {sorted_matrix}")
# transpose() - Transpose the matrix
transposed_matrix = np.transpose(matrix)
print(f"Transposed matrix:\n{transposed_matrix}")
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 40
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
b) Arithmetic Operations on Matrix using Arithmetic Operators
import numpy as np
# Create two matrices
matrix_a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix_b = np.array([[9, 8, 7], [6, 5, 4], [3, 2, 1]])
# Addition of matrices (using + operator)
addition_result = matrix_a + matrix_b
print(f"Matrix addition result:\n{addition_result}")
# Subtraction of matrices (using - operator)
subtraction_result = matrix_a - matrix_b
print(f"Matrix subtraction result:\n{subtraction_result}")
# Multiplication of matrices (using * operator - element-wise)
multiplication_result = matrix_a * matrix_b
print(f"Matrix multiplication result (element-wise):\n{multiplication_result}")
# Division of matrices (using / operator - element-wise)
division_result = matrix_a / matrix_b
print(f"Matrix division result (element-wise):\n{division_result}")
# Matrix multiplication (using @ operator for dot product)
dot_product_result = matrix_a @ matrix_b
print(f"Matrix multiplication result (dot product):\n{dot_product_result}")
Explanation of Each Operation:
a) Matrix Operations using NumPy:
1. diagonal(): Returns the diagonal elements of the matrix.
2. max(): Returns the maximum value of the matrix.
3. min(): Returns the minimum value of the matrix.
4. sum(): Returns the sum of all elements in the matrix.
5. mean(): Returns the mean (average) value of all elements in the matrix.
6. sort(): Sorts the elements of the matrix
7. transpose(): Returns the transpose of the matrix (flips rows and columns).
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 41
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
b) Arithmetic Operations on Matrices:
1. Addition (+): Adds two matrices element-wise.
2. Subtraction (-): Subtracts two matrices element-wise.
3. Multiplication (*): Multiplies two matrices element-wise.
4. Division (/): Divides two matrices element-wise.
5. Matrix multiplication (@): Computes the dot product of two matrices (this is the matrix
multiplication, not element-wise).
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 42
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment No: 07
Students Signature: Staff Signature: Marks:
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 43
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment No: 07
Students Signature: Staff Signature: Marks:
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 44
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment No: 07
Students Signature: Staff Signature: Marks:
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 45
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment No: 08
Handle data using pandas: Create an excel sheet and
a) Display statistical information, Perform queries on data.
b) Modify the index of the data, Sort the index.
c) Fill missing data.
Install the required libraries:
Before starting, make sure you have pandas and openpyxl installed, as these are needed to handle Excel files:
pip install pandas openpyxl
Sample Python Program using pandas:
import pandas as pd
import numpy as np
# Sample Data: Create a DataFrame
data = {
'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],
'Age': [24, np.nan, 30, 22, 29],
'Salary': [50000, 60000, np.nan, 45000, 70000],
'Department': ['HR', 'Finance', 'IT', 'HR', 'Finance']
}
df = pd.DataFrame(data)
a) Create an Excel file from DataFrame and Display Statistical Information
df.to_excel("employee_data.xlsx", index=False)
# Display statistical information about the DataFrame
print("\nStatistical Information:")
print(df.describe())
# Perform queries on the data (e.g., employees older than 25)
filtered_data = df[df['Age'] > 25]
print("\nEmployees older than 25:")
print(filtered_data)
b) Modify the index of the data, Sort the index
# Modifying the index by setting the 'Name' column as the index
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 46
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
df.set_index('Name', inplace=True)
print("\nDataFrame with 'Name' as index:")
print(df)
# Sorting the DataFrame by index (alphabetically)
sorted_df = df.sort_index()
print("\nSorted DataFrame by index:")
print(sorted_df)
c) Fill Missing Data (fill NaN values with a specific value)
# Filling missing 'Age' with the mean of the column, and 'Salary' with the median
df['Age'].fillna(df['Age'].mean(), inplace=True)
df['Salary'].fillna(df['Salary'].median(), inplace=True)
print("\nDataFrame after filling missing data:")
print(df)
# Save the modified DataFrame back to Excel
df.to_excel("modified_employee_data.xlsx", index=True)
Explanation of Each Part:
1. Create a DataFrame: We create a sample DataFrame df containing employee information, including
names, ages, salaries, and departments. We introduce some NaN (missing) values in the 'Age' and
'Salary' columns.
2. Create an Excel File: The to_excel() function is used to write the DataFrame to an Excel file
(employee_data.xlsx). Make sure you have openpyxl installed, as it's needed to handle .xlsx files.
3. Display Statistical Information: The describe() function generates descriptive statistics that
summarize the central tendency, dispersion, and shape of the dataset's distribution, excluding NaN
values.
4. Perform Queries: We filter employees whose age is greater than 25 using a simple query df[df['Age']
> 25].
5. Modify the Index: We change the index of the DataFrame to the 'Name' column using set_index().
This modifies the structure of the DataFrame by setting 'Name' as the index. The sort_index() function
is then used to sort the DataFrame by its index.
6. Fill Missing Data: The fillna() function is used to fill the missing values (NaN) in the 'Age' column
with the mean of that column and the 'Salary' column with the median. This is a common technique to
handle missing data.
7. Save Modified Data: After making the modifications, the to_excel() function is used again to save the
updated DataFrame to a new Excel file (modified_employee_data.xlsx).
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 47
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Sample Output:
Statistical Information:
Age Salary
count 5.000000 5.000000
mean 27.000000 57000.000000
std 3.162278 12247.448933
min 22.000000 45000.000000
25% 24.000000 50000.000000
50% 26.000000 60000.000000
75% 29.000000 65000.000000
max 30.000000 70000.000000
Employees older than 25:
Name Age Salary Department
Charlie 30.0 60000 IT
Eve 29.0 70000 Finance
DataFrame with 'Name' as index:
Name Age Salary Department
Alice 24.0 50000 HR
Bob NaN 60000 Finance
Charlie 30.0 NaN IT
David 22.0 45000 HR
Eve 29.0 70000 Finance
Sorted DataFrame by index:
Name Age Salary Department
Alice 24.0 50000 HR
Bob NaN 60000 Finance
Charlie 30.0 NaN IT
David 22.0 45000 HR
Eve 29.0 70000 Finance
DataFrame after filling missing data:
Name Age Salary Department
Alice 24.0 50000 HR
Bob 27.75 60000 Finance
Charlie 30.0 57500 IT
David 22.0 45000 HR
Eve 29.0 70000 Finance
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 48
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment No: 08
Students Signature: Staff Signature: Marks:
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 49
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment No: 08
Students Signature: Staff Signature: Marks:
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 50
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Experiment No: 08
Students Signature: Staff Signature: Marks:
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 51
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
Viva Question and Answers
1. What is Python?
o Python is a high-level, interpreted, general-purpose programming language.
2. What are the key features of Python?
o Python is easy to learn, interpreted, dynamically typed, and supports multiple programming
paradigms.
3. What is the difference between Python 2 and Python 3?
o Python 3 is the latest version, and it has better support for Unicode and changes in print,
division, and string handling.
4. What is a variable in Python?
o A variable in Python is a name that refers to a value in memory.
5. What are data types in Python?
o Python data types include int, float, string, list, tuple, dictionary, set, and boolean.
6. What is a list in Python?
o A list is a mutable, ordered collection of items in Python.
7. What is a tuple in Python?
o A tuple is an immutable, ordered collection of items in Python.
8. What is the difference between a list and a tuple?
o Lists are mutable (can be changed), while tuples are immutable (cannot be changed).
9. What are the different ways to create a dictionary in Python?
o A dictionary can be created using curly braces {} or the dict() constructor.
10. What is a set in Python?
o A set is an unordered collection of unique elements.
11. What is a function in Python?
o A function is a block of reusable code that performs a specific task.
12. What is the use of the return statement in Python?
o The return statement exits a function and returns a value to the caller.
13. What are loops in Python?
o Loops allow code to be executed repeatedly, such as for and while loops.
14. What is an if statement in Python?
o An if statement is used to execute a block of code based on a condition.
15. What is the purpose of the pass keyword in Python?
o pass is a placeholder used when no action is required in a block of code.
16. What is a Python module?
o A Python module is a file containing Python definitions and statements.
17. What is the difference between “==” and “is” in Python?
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 52
Mysore University School of Engineering
8J99+QC7, Manasa Gangothiri, Mysuru, Karnataka 570006
o “==” compares values, while “is” compares object identity.
18. What is exception handling in Python?
o Exception handling is done using try, except, and optionally finally to catch and handle errors.
19. What is the purpose of the lambda function in Python?
o A lambda function is an anonymous function defined with the lambda keyword.
20. What is the difference between append() and extend() in a list?
o append() adds a single element, while extend() adds multiple elements to the list.
Prepared by: Mr Thanmay J S, Assistant Professor, BMRE Department, SOE-UoM 53