Python Skill Course Lab Manual
Python Skill Course Lab Manual
Experiment 1
Program:
#static input
num1, num2, num3 = 10 , 30 , 20
if num1 >= num2 and num1 >= num3:
print(num1)
elif num2 >= num1 and num2 >= num3:
print(num2)
else:
print(num3)
#Dynamic input
num1=int(input("Enter First Number: "))
num2=int(input("Enter Second Number: "))
num3=int(input("Enter Third Number: "))
if num1 >= num2 and num1 >= num3:
print(num1)
elif num2 >= num1 and num2 >= num3:
print(num2)
else:
print(num3)
Output:
30
Enter First Number: 55
Enter Second Number: 11
Enter Third Number: 99
99
Experiment 2
2.Write a Program to display all prime numbers within an interval
Program:
Output:
Experiment 3
3.Write a program to swap two numbers without using a temporary variable
Program:
# Initial values
a=5
b = 10
# Display original values
print("Before swapping:")
print("a =", a)
print("b =", b)
# Swapping using tuple unpacking
a, b = b, a
# Display swapped values
print("After swapping:")
print("a =", a)
print("b =", b)
Output:
Before swapping:
a=5
b = 10
After swapping:
a = 10
b=5
Experiment 4
4. Demonstrate the following Operators in Python with suitable examples. i) Arithmetic
Operators ii) Relational Operators iii) Assignment Operators iv) Logical Operators v) Bit
wise Operators vi) Ternary Operator vii) Membership Operators viii) Identity Operators
Aim: Demonstrate the following operators i) Arithmetic Operators ii) Relational Operators iii)
Assignment Operators iv) Logical Operators v) Bit wise Operators vi) Ternary Operator vii)
Membership Operators viii) Identity Operators
Program:
# Arithmetic Operators
a, b = 10, 5
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Floor Division:", a // b)
print("Modulus:", a % b)
print("Exponentiation:", a ** b)
# Relational Operators
x, y = 15, 10
print("Equal to:", x == y)
print("Not equal to:", x != y)
print("Greater than:", x > y)
print("Less than:", x < y)
print("Greater than or equal to:", x >= y)
print("Less than or equal to:", x <= y)
# Assignment Operators
a = 10
a += 5
print("Add and assign (a += 5):", a)
a -= 3
print("Subtract and assign (a -= 3):", a)
a *= 2
print("Multiply and assign (a *= 2):", a)
a /= 4
print("Divide and assign (a /= 4):", a)
a %= 2
print("Modulus and assign (a %= 2):", a)
# Logical Operators
a, b = True, False
print("AND (a and b):", a and b)
print("OR (a or b):", a or b)
# Bitwise Operators
x, y = 10, 4
print("Bitwise AND (x & y):", x & y)
print("Bitwise OR (x | y):", x | y)
print("Bitwise XOR (x ^ y):", x ^ y)
print("Bitwise NOT (~x):", ~x)
print("Left Shift (x << 1):", x << 1)
print("Right Shift (x >> 1):", x >> 1)
# Ternary Operator
x, y = 10, 20
result = "x is greater" if x > y else "y is greater or equal"
print("Ternary Operator result:", result)
# Membership Operators
list = [1, 2, 3, 4, 5]
print("5 in list:", 5 in list)
print("10 not in list:", 10 not in list)
# Identity Operators
a, b = [1, 2, 3], [1, 2, 3]
print("a is b:", a is b)
print("a is not b:", a is not b)
Output:
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0
Floor Division: 2
Modulus: 0
Exponentiation: 100000
Equal to: False
Not equal to: True
Greater than: True
Less than: False
Greater than or equal to: True
Less than or equal to: False
Add and assign (a += 5): 15
Subtract and assign (a -= 3): 12
Multiply and assign (a *= 2): 24
Divide and assign (a /= 4): 6.0
Modulus and assign (a %= 2): 0.0
AND (a and b): False
OR (a or b): True
NOT (not a): False
Experiment 5
5.Write a program to add and multiply complex numbers
Aim: To add and multiply complex numbers(Enter first complex number i.e. 3+4j not 3+4i)
Program:
Output:
Experiment 6
6.Write a program to print multiplication table of a given number
Program:
Output:
Enter a number : 5
Table of: 5 is
5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
5 x 11 = 55
5 x 12 = 60
5 x 13 = 65
5 x 14 = 70
5 x 15 = 75
5 x 16 = 80
5 x 17 = 85
5 x 18 = 90
5 x 19 = 95
5 x 20 = 100
Experiment 7
7.Writehow to Handle specific exceptions – like division of a number by zero in python
Program:
try:
# Prompt the user to enter two numbers
numerator = float(input("Enter the numerator: "))
denominator = float(input("Enter the denominator: "))
# Perform division
result = numerator / denominator
except ZeroDivisionError:
# Handle the specific exception for division by zero
print("Error: Cannot divide by zero!")
except ValueError:
# Handle a different specific exception for invalid input
print("Error: Please enter valid numbers!")
else:
# This block runs if no exceptions are raised
print("Result:", result)
finally:
# This block always executes, regardless of an exception
print("Execution complete.")
Output:
Enter the numerator: 10
Enter the denominator: 0
Error: Cannot divide by zero!
Execution complete.
Experiment 8
8. Write a program to define a function with multiple return values
Program:
def fun():
str = "Aditya college of Engineering & Technology"
x = 20
return str, x
str, x = fun()
print(str)
print(x)
Output:
Experiment 9
9.Write a program to define a function using default arguments
Program:
Output:
Sum: 5
Sum: 10
Sum: 15
Experiment 10
10.Write a program to find the length of the string without using any library functions
Aim: To find the length of the string without using any library functions
Program:
string = 'Hello'
count = 0
for i in string:
count+=1
print(count)
Output: 5
Experiment 11
10.Write a program to check if the substring is present in a given string or not
Program:
Output:
Experiment 12
12.Write a program to perform the given operations on a list: i. Addition ii. Insertion
iii. Slicing
Aim: To perform the given operations on a list: i. Addition ii. Insertion iii. Slicing
Program:
list = [1,2,3,4,5]
print("list", list)
#Addition
list.append(6)
print(F" After appending of 6, list is {list}")
#insertion
list.insert(1, 10)
print(F" After insertion 10 in 1 index, list is {list}")
#slicing
print(F" Slicing of list is {list[3:6]}")
Output:
list [1, 2, 3, 4, 5]
After appending of 6, list is [1, 2, 3, 4, 5, 6]
After insertion 10 in 1 index, list is [1, 10, 2, 3, 4, 5, 6]
Slicing of list is [3, 4, 5]
Experiment 13
13.Write a program to perform any 5 built-in functions by taking any list
Program:
Output:
Experiment 14
14.Write a program to create tuples (name, age, address, college) for at least two members
and concatenate the tuples and print the concatenated tuples
Aim:To create tuples (name, age, address, college) for at least two members and concatenate the
tuples and print the concatenated tuples
Program:
Output:
Experiment 15
15. Write a program to count the number of vowels in a string (No control flow allowed)
Aim: To count the number of vowels in a string (No control flow allowed)
Program:
Output:
Experiment 16
16.Write a program to check if a given key exists in a dictionary or not
Program:
Output:
True
False
Experiment 17
17.Write a program to add a new key-value pair to an existing dictionary
Program:
Output:
{'key1': 'Python', 'key2': 'is a ', 'key3': 'versatile', 'key4': ‘and powerful ', 'key5': 'programming', 'key6':
'language'}
Experiment 18
18.Write a program to sum all the items in a given dictionary
Program:
def returnSum(myDict):
list = []
for i in myDict:
list.append(myDict[i])
final = sum(list)
return final
# Driver Function
dict = {'a': 100, 'b': 200, 'c': 300}
print("Sum :", returnSum(dict))
Output:
Sum : 600
Experiment 19
19. Write a python program to sort words in a file and put them in another file. The output
file should have only lower-case words, so any upper-case words from source must be lowered.
Aim: To sort words in a file and put them in another file. The output file should have only lower-
case words, so any upper-case words from source must be lowered.
Program:
except FileNotFoundError:
print(f"The file {input_file} does not exist.")
except Exception as e:
print(f"An error occurred: {e}")
# Get input file and output file names from the user
input_file = input("Enter the input file name (with extension): ")
output_file = input("Enter the output file name (with extension): ")
sort_words_in_file(input_file, output_file)
ds_in_file(input_file, output_file)
Experiment 20
20. Python program to print each line of a file in reverse order.
Program:
print_lines_in_reverse(input_file_path, output_file_path)
Output:
Enter the full path to the input file (with extension): C:\Notepad\input.txt
Enter the full path to the output file (with extension): C:\Notepad\output.txt
Reversed lines successfully written to C:\Notepad\output.txt
Experiment 21
21. Python program to compute the number of characters, words and lines in a file
Program:
def count_file_contents():
# Get the file path from the user
file_path = input("Enter the full path to the input file (with extension): ")
try:
with open(file_path, 'r') as file:
lines = file.readlines() # Read all lines from the file
# Display results
print(f"Number of lines: {num_lines}")
print(f"Number of words: {num_words}")
print(f"Number of characters: {num_characters}")
except FileNotFoundError:
print(f"The file {file_path} does not exist.")
except Exception as e:
print(f"An error occurred: {e}")
Output:
Enter the full path to the input file (with extension): C:\Notepad\input.txt
Number of lines: 1
Number of words: 11
Number of characters: 47
Experiment 22
22. Python program to create, display, append, insert and reverse the order of the items in the
array
Aim: To create, display, append, insert and reverse the order of the items in the array
Program:
def create_array():
"""Create an array with initial items."""
return [1, 2, 3, 4, 5] # Example initial items
def display_array(arr):
"""Display the items in the array."""
print("Current array:", arr)
def reverse_array(arr):
"""Reverse the order of the items in the array."""
arr.reverse()
print("Array reversed.")
def main():
# Create an array
array = create_array()
while True:
print("\nMenu:")
print("1. Display array\t 2. Append item")
print("3. Insert item\t 4. Reverse array\t 5. Exit")
choice = input("Enter your choice (1-5): ")
if choice == '1':
display_array(array)
elif choice == '2':
item = input("Enter item to append: ")
if __name__ == "__main__":
main()
Output:
Menu:
1. Display array 2. Append item
3. Insert item 4. Reverse array 5. Exit
Enter your choice (1-5): 1
Current array: [1, 2, 3, 4, 5]
Menu:
1. Display array 2. Append item
3. Insert item 4. Reverse array 5. Exit
Enter your choice (1-5): 2
Enter item to append: 6, 9, 10
Item 6, 9, 10 appended to the array.
Menu:
1. Display array 2. Append item
3. Insert item 4. Reverse array 5. Exit
Enter your choice (1-5): 3
Enter index to insert at: 3
Enter item to insert: 20
Item 20 inserted at index 3.
Menu:
1. Display array 2. Append item
3. Insert item 4. Reverse array 5. Exit
Enter your choice (1-5): 4
Array reversed.
Menu:
1. Display array 2. Append item
3. Insert item 4. Reverse array 5. Exit
Menu:
1. Display array 2. Append item
3. Insert item 4. Reverse array 5. Exit
Enter your choice (1-5): 5
Exiting the program.
Experiment 23
23. Python program to add, transpose and multiply two matrices.
Program:
definput_matrix(rows, cols):
"""Input a matrix from the user."""
matrix = []
for _ in range(rows):
row = list(map(int, input("Enter row (space-separated): ").split()))
matrix.append(row)
return matrix
defadd_matrices(matrix1, matrix2):
"""Add two matrices."""
return [[matrix1[i][j] + matrix2[i][j] for j in range(len(matrix1[0]))] for i in range(len(matrix1))]
deftranspose_matrix(matrix):
"""Transpose a matrix."""
return [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]
defmultiply_matrices(matrix1, matrix2):
"""Multiply two matrices."""
result = []
for i in range(len(matrix1)):
row = []
for j in range(len(matrix2[0])):
sum = 0
for k in range(len(matrix2)):
sum += matrix1[i][k] * matrix2[k][j]
row.append(sum)
result.append(row)
return result
def main():
# Input first matrix
rows1 = int(input("Enter the number of rows for the first matrix: "))
cols1 = int(input("Enter the number of columns for the first matrix: "))
print("Enter the first matrix:")
matrix1 = input_matrix(rows1, cols1)
# Matrix Addition
if rows1 == rows2 and cols1 == cols2:
print("\nAddition of matrices:")
result_add = add_matrices(matrix1, matrix2)
for row in result_add:
print(row)
else:
print("Matrices cannot be added (dimensions do not match).")
# Matrix Transpose
print("\nTranspose of the first matrix:")
transposed1 = transpose_matrix(matrix1)
for row in transposed1:
print(row)
# Matrix Multiplication
if cols1 == rows2:
print("\nMultiplication of matrices:")
result_multiply = multiply_matrices(matrix1, matrix2)
for row in result_multiply:
print(row)
else:
print("Matrices cannot be multiplied (inner dimensions do not match).")
if __name__ == "__main__":
main()
Output:
Enter the number of rows for the first matrix: 2
Enter the number of columns for the first matrix: 2
Enter row (space-separated): 1 2
Enter row (space-separated): 3 4
Enter the number of rows for the second matrix: 2
Enter the number of columns for the second matrix: 2
Enter row (space-separated): 5 6
Enter row (space-separated): 7 8
Addition of matrices:
[6, 8]
[10, 12]
Multiplication of matrices:
[19, 22]
[43, 50]
Experiment 24
24. Python program to create a class that represents a shape. Include methods to calculate its
area and perimeter. Implement subclasses for different shapes like circle, triangle, and square.
Aim: To create a class that represents a shape. Include methods to calculate its area and perimeter.
Implement subclasses for different shapes like circle, triangle, and square.
Program:
import math
class Shape:
def area(self):
raise NotImplementedError
def perimeter(self):
raise NotImplementedError
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
def perimeter(self):
return 2 * math.pi * self.radius
class Triangle(Shape):
def __init__(self, base, height, side1, side2):
self.base = base
self.height = height
self.side1 = side1
self.side2 = side2
def area(self):
return 0.5 * self.base * self.height
def perimeter(self):
return self.base + self.side1 + self.side2
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
def perimeter(self):
return 4 * self.side
def main():
shapes = []
# Get Circle input
radius = float(input("Enter the radius of the circle: "))
shapes.append(Circle(radius))
# Get Triangle input
base = float(input("Enter the base of the triangle: "))
height = float(input("Enter the height of the triangle: "))
side1 = float(input("Enter the length of side 1 of the triangle: "))
side2 = float(input("Enter the length of side 2 of the triangle: "))
shapes.append(Triangle(base, height, side1, side2))
# Get Square input
side = float(input("Enter the side length of the square: "))
shapes.append(Square(side))
# Display area and perimeter for each shape
for shape in shapes:
print(f"{shape.__class__.__name__}: Area = {shape.area():.2f}, Perimeter =
{shape.perimeter():.2f}")
if __name__ == "__main__":
main()
Output:
Enter the radius of the circle: 4
Enter the base of the triangle: 4
Enter the height of the triangle: 4
Enter the length of side 1 of the triangle: 4
Enter the length of side 2 of the triangle: 4
Enter the side length of the square: 4
Circle: Area = 50.27, Perimeter = 25.13
Triangle: Area = 8.00, Perimeter = 12.00
Square: Area = 16.00, Perimeter = 16.00
Experiment 25
25. Python program to check whether a JSON string contains complex object or not.
import json
defis_complex_object(obj):
"""Check if the object is a complex object (dict or list)."""
return isinstance(obj, (dict, list))
defcheck_json_complexity(json_string):
try:
# Parse the JSON string
parsed_json = json.loads(json_string)
Output:
JSON String 1 is complex: True
JSON String 2 is complex: False
JSON String 3 is complex: False
Experiment 26
26. Python Program to demonstrate NumPy arrays creation using array () function.
Program:
import numpy as np
print(arr)
print(type(arr))
Output:
[1 2 3 4 5]
<class 'numpy.ndarray'>
Experiment 27
27. Python program to demonstrate use of ndim, shape, size, dtype.
Program:
import numpy as np
Output:
Array:
[[1 2 3]
[4 5 6]]
Experiment 28
28. Python program to demonstrate basic slicing, integer and Boolean indexing
Program:
import numpy as np
# Create a sample NumPy array
array = np.array([[10, 20, 30, 40],
[50, 60, 70, 80],
[90, 100, 110, 120]])
print("Original Array:")
print(array)
# Basic slicing
print("\nBasic Slicing (first two rows and first three columns):")
sliced_array = array[:2, :3]
print(sliced_array)
# Integer indexing
print("\nInteger Indexing (selecting specific elements):")
# Selecting elements at (0, 1), (1, 2), and (2, 3)
integer_indexed_array = array[[0, 1, 2], [1, 2, 3]]
print(integer_indexed_array)
# Boolean indexing
print("\nBoolean Indexing (selecting elements greater than 60):")
boolean_indexed_array = array[array > 60]
print(boolean_indexed_array)
Output:
Original Array:
[[ 10 20 30 40]
[ 50 60 70 80]
[ 90 100 110 120]]
Experiment 29
29. Python program to find min, max, sum, cumulative sum of array
Program:
import numpy as np
Output:
Minimum value in the array: 5
Maximum value in the array: 25
Sum of all elements in the array: 75
Cumulative sum of the array: [ 5 15 30 50 75]
Experiment 30
30. Create a dictionary with at least five keys and each key represent value as a list where this
list contains at least ten values and convert this dictionary as a pandas data frame and explore
the data through the data frame as follows:
a) Apply head () function to the pandas data frame.
b) Perform various data selection operations on Data Frame
Aim: To demonstrate dictionary with at least five keys and each key represent value as a list where
this list contains at least ten values and convert this dictionary as a pandas data frame and explore
the data through the data frame as follows:
a) Apply head () function to the pandas data frame.
b) Perform various data selection operations on Data Frame
Program:
import pandas as pd
# Step 1: Create a dictionary with at least five keys, each representing a list of ten values
data = {
'Product': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
'Price': [10.99, 12.50, 8.75, 5.00, 15.99, 7.50, 9.99, 20.00, 13.50, 11.25],
'Stock': [100, 200, 150, 300, 120, 80, 60, 40, 250, 10],
'Category': ['Electronics', 'Electronics', 'Home', 'Home', 'Fashion',
'Fashion', 'Toys', 'Toys', 'Books', 'Books'],
'Rating': [4.5, 4.0, 4.2, 3.8, 4.9, 4.0, 3.5, 4.3, 4.7, 4.1]
}
# Step 2: Convert the dictionary into a pandas DataFrame
df = pd.DataFrame(data)
# Step 3: Apply head() function to the pandas DataFrame
print("First five rows of the DataFrame:")
print(df.head())
# Step 4: Perform various data selection operations on the DataFrame
# 4a. Selecting a single column (Product)
print("\nSelecting the 'Product' column:")
product_column = df['Product']
print(product_column)
# 4b. Selecting multiple columns (Price and Stock)
print("\nSelecting 'Price' and 'Stock' columns:")
price_and_stock = df[['Price', 'Stock']]
print(price_and_stock)
# 4c. Selecting rows where Price is greater than 10
print("\nSelecting rows where Price > 10:")
high_price = df[df['Price'] > 10]
print(high_price)
Output:
First five rows of the DataFrame:
Product Price Stock Category Rating
0 A 10.99 100 Electronics 4.5
1 B 12.50 200 Electronics 4.0
2 C 8.75 150 Home 4.2
3 D 5.00 300 Home 3.8
4 E 15.99 120 Fashion 4.9
Experiment 31
31. Select any two columns from the above data frame, and observe the change in one
attribute with respect to other attribute with scatter and plot operations in matplotlib
Aim: Select any two columns from the above data frame, and observe the change in one attribute
with respect to other attribute with scatter and plot operations in matplotlib
Program:
import pandas as pd
import matplotlib.pyplot as plt
# Step 1: Create a dictionary with at least five keys, each representing a list of ten values
data = {
'Product': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
'Price': [10.99, 12.50, 8.75, 5.00, 15.99, 7.50, 9.99, 20.00, 13.50, 11.25],
'Stock': [100, 200, 150, 300, 120, 80, 60, 40, 250, 10],
'Category': ['Electronics', 'Electronics', 'Home', 'Home', 'Fashion',
'Fashion', 'Toys', 'Toys', 'Books', 'Books'],
'Rating': [4.5, 4.0, 4.2, 3.8, 4.9, 4.0, 3.5, 4.3, 4.7, 4.1]
}
Ouptut:
DataFrame:
Product Price Stock Category Rating
0 A 10.99 100 Electronics 4.5
1 B 12.50 200 Electronics 4.0
2 C 8.75 150 Home 4.2
3 D 5.00 300 Home 3.8
4 E 15.99 120 Fashion 4.9
5 F 7.50 80 Fashion 4.0
6 G 9.99 60 Toys 3.5
7 H 20.00 40 Toys 4.3
8 I 13.50 250 Books 4.7
9 J 11.25 10 Books 4.
Additional Experiment
Experiment 32
32. Python program to check whether a XML string contains complex object or not.
Program:
importxml.etree.ElementTree as ET
defis_complex_object(element):
# A complex object can be defined as:
# - Element has child elements, or
# - Element has attributes
Output:
The XML contains a complex object.