Python Lab Manual
Unit-1
1. Write a program to find the largest element among three Numbers.
num1 = input("Enter first number: ")
num2 = input("Enter second number: ")
num3 = input("Enter third number: ")
if (num1 >= num2) and (num1 >= num3):
largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3
print("The largest number is", largest)
output:
2. Write a Program to display all prime numbers within an interval.
a = int(input ("Enter the Lowest Range Value: "))
b = int(input ("Enter the Upper Range Value: "))
print ("The Prime Numbers in the range are: ")
for number in range (a, b + 1):
if number > 1:
for i in range (2, number):
if (number % i) == 0:
break
else:
print (number)
output:
3. Write a program to swap two numbers without using a temporary variable.
x=5
y = 10
x, y = y, x
print("x =", x)
print("y =", y)
output:
x = 10
y=5
4.Write a program to add and multiply complex numbers
c1=(4+3j)
c2=(3-7j)
print("Addition of two complex numbers : ",c1+c2)
print("Multiplication of two complex numbers : ",c1*c2)
output:
Addition of two complex numbers : (7-4j)
Multiplication of two complex numbers : (33-19j)
5. Write a program to print multiplication table of a given number.
num = 5
for i in range(1, 11):
print(num, 'x', i, '=', num*i)
output:
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
Unit-2
1.Write a program to define a function with multiple return values.
def calculate_statistics(numbers):
# Calculate sum, average, and count of numbers
total_sum = sum(numbers)
average = total_sum / len(numbers)
count = len(numbers)
# Return multiple values as a tuple
return total_sum, average, count
# Example usage of the function
numbers_list = [10, 20, 30, 40, 50]
total, avg, count = calculate_statistics(numbers_list)
# Displaying the results
print(f"Total sum: {total}")
print(f"Average: {avg}")
print(f"Count of numbers: {count}")
2.Write a program to define a function using default arguments.
def greet(name, message="Hello,"):
print(f"{message} {name}!")
# Example usage of the function
greet("Alice") # Uses default message: Hello, Alice!
greet("Bob", "Hi") # Uses custom message: Hi Bob!
Output:
Hello, Alice!
Hi Bob!
3.Write a program to find the length of the string without using any library functions.
def find_string_length(input_string):
length = 0
for char in input_string:
length += 1
return length
# Example usage
input_string = "Hello, World!"
length = find_string_length(input_string)
print(f"The length of the string '{input_string}' is: {length}")
**Output**:
The length of the string 'Hello, World!' is: 13
4.Write a program to check if the substring is present in a given string or not.
def is_substring_present(main_string, substring):
main_len = len(main_string)
sub_len = len(substring)
for i in range(main_len - sub_len + 1):
if main_string[i:i + sub_len] == substring:
return True
return False
# Example usage
main_string = "Hello, World!"
substring1 = "World"
substring2 = "Python"
if is_substring_present(main_string, substring1):
print(f"'{substring1}' is present in '{main_string}'")
else:
print(f"'{substring1}' is not present in '{main_string}'")
if is_substring_present(main_string, substring2):
print(f"'{substring2}' is present in '{main_string}'")
else:
print(f"'{substring2}' is not present in '{main_string}'")
**Output**:
'World' is present in 'Hello, World!'
'Python' is not present in 'Hello, World!'
5.Write a program to perform the given operations on a list:
i. Addition ii. Insertion iii. slicing
# Define a list
numbers = [1, 2, 3, 4, 5]
# i. Addition operation
# Append an element to the end of the list
numbers.append(6)
print("List after addition:", numbers) # Output: [1, 2, 3, 4, 5, 6]
# ii. Insertion operation
# Insert an element at a specific position
numbers.insert(2, 10) # Insert 10 at index 2
print("List after insertion:", numbers) # Output: [1, 2, 10, 3, 4, 5, 6]
# iii. Slicing operation
# Extract a sublist using slicing
sublist = numbers[1:4] # Slice from index 1 to 3 (exclusive)
print("Sublist:", sublist) # Output: [2, 10, 3]
# Modify an element using slicing
numbers[3:5] = [8, 9] # Replace elements at index 3 and 4
print("Modified list:", numbers) # Output: [1, 2, 10, 8, 9, 6]
Output:
List after addition: [1, 2, 3, 4, 5, 6]
List after insertion: [1, 2, 10, 3, 4, 5, 6]
Sublist: [2, 10, 3]
Modified list: [1, 2, 10, 8, 9
Unit-3
1.Write a program to create tuples (name,age,address,college) fo atleast two members and
concatenate the tuples and print the concatenated tuples.
def main():
# Creating tuples for two members
member1 = ("Alice", 25, "123 Street, CityA", "ABC College")
member2 = ("Bob", 28, "456 Avenue, CityB", "XYZ College")
# Concatenating the tuples
concatenated_tuple = member1 + member2
# Printing the concatenated tuple
print("Concatenated Tuple:")
print(concatenated_tuple)
if __name__ == "__main__":
main()
OUTPUT:
Concatenated Tuple:
('Alice', 25, '123 Street, CityA', 'ABC College', 'Bob', 28, '456 Avenue, CityB', 'XYZ College')
2. Write a program to count the number of vowels in a string (No controlflow allowed).
def count_vowels(s):
# Define the vowels in a set for quick lookup
vowels = {'a', 'e', 'i', 'o', 'u'}
# Count vowels using set intersection with the input string
num_vowels = sum(1 for char in s if char.lower() in vowels)
return num_vowels
def main():
# Input string for testing
input_string = "Hello World, How are you?"
# Count vowels in the input string
num_vowels = count_vowels(input_string)
# Print the result
print(f"Number of vowels in the string: {num_vowels}")
if __name__ == "__main__":
main()
Output:
Number of vowels in the string: 7
3.Write a program to check if a given key exists in a dictionary or not.
def check_key_in_dict(dictionary, key):
# Using the 'in' keyword to check if the key exists in the dictionary
if key in dictionary:
return True
else:
return False
def main():
# Example dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}
# Key to check
key_to_check = 'b'
# Check if key exists in the dictionary
if check_key_in_dict(my_dict, key_to_check):
print(f"The key '{key_to_check}' exists in the dictionary.")
else:
print(f"The key '{key_to_check}' does not exist in the dictionary.")
if __name__ == "__main__":
main()
Output: The key 'b' exists in the dictionary.
4.Write a program to add a new key-value pair to an existing dictionary.
Def add_to_dictionary(dictionary, key, value):
# Adding a new key-value pair to the dictionary
dictionary[key] = value
def main():
# Existing dictionary
my_dict = {‘a’: 1, ‘b’: 2, ‘c’: 3}
# Key-value pair to add
new_key = ‘d’
new_value = 4
# Adding new key-value pair to the dictionary
add_to_dictionary(my_dict, new_key, new_value)
# Printing the updated dictionary
print(“Updated Dictionary:”, my_dict)
if __name__ == “__main__”:
main()
Output:
Updated Dictionary: {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}
5.Write a program to sum all the items in a given dictionary.
def sum_dictionary_items(d):
total_sum = sum(d.values())
return total_sum
# Example usage
my_dict = {'a': 100, 'b': 200, 'c': 300}
print("Sum of all items in the dictionary:", sum_dictionary_items(my_dict))
OUTPUT:
Sum of all items in the dictionary: 600
Unit-4
1.Write a 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.
def sort_words(input_file, output_file):
# Read words from input file
with open(input_file, 'r') as f:
words = f.read().split()
# Convert all words to lowercase
words = [word.lower() for word in words]
# Sort the words alphabetically
words.sort()
# Write sorted words to output file
with open(output_file, 'w') as f:
for word in words:
f.write(word + '\n')
print(f"Sorted words have been written to {output_file}")
# Example usage:
input_file = r'C:\Users\kotes\OneDrive\Desktop\example.txt' # Replace with your input file
name
output_file = r'C:\Users\kotes\OneDrive\Desktop\output.txt' # Replace with your desired output
file name
sort_words(input_file, output_file)
output:
2.Python program to print each line of a file in reverse order.
file=input("Enter file name with extension:")
try:
f=open(file,'r')
print("Reverse of each and every line from given file is:")
for i in f.readlines():
print(i[::-1],end='')
f.close()
except FileNotFoundError as e:
print("File or directory not exist")
3.Python program to compute the number of characters, words and lines in a file.
file=input("Enter file name with extension:")
v=w=c=0
try:
f=open(file,'r')
m=list(f.read())
for i in m:
if i=='\n':
v=v+1
if i==' ' or i=='\n':
w=w+1
if i.isalpha():
c=c+1
f.close()
print("No. of characters: ",c)
print("No. of words: ",w+1)
print("No. of lines: ",v+1)
except FileNotFoundError as e:
print("File or directory not exist")
OR
file=input("Enter file name with extension:")
v=w=c=0
try:
f=open(file,'r')
m=f.readlines()
for i in m:
v=v+1
for j in i.split():
w=w+1
for k in j:
if k.isalpha():
c=c+1
f.close()
print("No. of characters: ",c)
print("No. of words: ",w)
print("No. of lines: ",v)
except FileNotFoundError as e:
print("File
or
directory
not exist")
4.Write a 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.
import math
class Shape:
def area(self):
raise NotImplementedError("Subclass must implement this method")
def perimeter(self):
raise NotImplementedError("Subclass must implement this method")
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 Square(Shape):
def __init__(self, side_length):
self.side_length = side_length
def area(self):
return self.side_length ** 2
def perimeter(self):
return 4 * self.side_length
class Triangle(Shape):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def area(self):
# Using Heron's formula
s = (self.a + self.b + self.c) / 2
return math.sqrt(s * (s - self.a) * (s - self.b) * (s - self.c))
def perimeter(self):
return self.a + self.b + self.c
def main():
shapes = [
Circle(5),
Square(4),
Triangle(3, 4, 5)
]
for shape in shapes:
print(f"{shape.__class__.__name__}:")
print(f" Area: {shape.area()}")
print(f" Perimeter: {shape.perimeter()}\n")
if __name__ == "__main__":
main()
Output:
Unit-5
1.Write a python Program to check whether a JSON string contains a complex object or
not.
import json
def is_complex_num(objct):
if '__complex__' in objct:
return complex(objct['real'], objct['img'])
return objct
complex_object =json.loads('{"__complex__": true, "real": 4, "img": 5}', object_hook =
is_complex_num)
simple_object =json.loads('{"real": 4, "img": 3}', object_hook = is_complex_num)
print("Complex_object: ",complex_object)
print("Without complex object: ",simple_object)
output:
Complex_object: (4+5j)
Without complex object: {'real': 4, 'img': 3}
2.Write a Python program to demonstrate numpy arrays creation using array ().
Program:
import numpy as np
# Creating a 1D array
array_1d = np.array([1, 2, 3, 4, 5])
print("1D Array:")
print(array_1d)
# Creating a 2D array
array_2d = np.array([[1, 2, 3], [4, 5, 6]])
print("\n2D Array:")
print(array_2d)
# Creating a 3D array
array_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print("\n3D Array:")
print(array_3d)
# Specifying the data type
array_float = np.array([1, 2, 3], dtype=float)
print("\nArray with specified data type (float):")
print(array_float)
Output:
1D Array:
[1 2 3 4 5]
2D Array:
[[1 2 3]
[4 5 6]]
3D Array:
[[[1 2]
[3 4]]
[[5 6]
[7 8]]]
Array with specified data type (float):
[1. 2. 3.]
3.python program to demonstrate use of NDIM ,shape, size ,*dtype
import numpy as np
# Creating a 1D array
array_1d = np.array([1, 2, 3, 4, 5])
print("1D Array:")
print(array_1d)
print("Number of dimensions (ndim):", array_1d.ndim)
print("Shape:", array_1d.shape)
print("Size (number of elements):", array_1d.size)
print("Data type (dtype):", array_1d.dtype)
print("\n" + "-"*30 + "\n")
# Creating a 2D array
array_2d = np.array([[1, 2, 3], [4, 5, 6]])
print("2D Array:")
print(array_2d)
print("Number of dimensions (ndim):", array_2d.ndim)
print("Shape:", array_2d.shape)
print("Size (number of elements):", array_2d.size)
print("Data type (dtype):", array_2d.dtype)
print("\n" + "-"*30 + "\n")
# Creating a 3D array
array_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print("3D Array:")
print(array_3d)
print("Number of dimensions (ndim):", array_3d.ndim)
print("Shape:", array_3d.shape)
print("Size (number of elements):", array_3d.size)
print("Data type (dtype):", array_3d.dtype)
print("\n" + "-"*30 + "\n")
# Creating an array with a specified data type
array_float = np.array([1.0, 2.0, 3.0], dtype=float)
print("Array with specified data type (float):")
print(array_float)
print("Number of dimensions (ndim):", array_float.ndim)
print("Shape:", array_float.shape)
print("Size (number of elements):", array_float.size)
print("Data type (dtype):", array_float.dtype)
Output:
1D Array:
[1 2 3 4 5]
Number of dimensions (ndim): 1
Shape: (5,)
Size (number of elements): 5
Data type (dtype): int64
------------------------------
2D Array:
[[1 2 3]
[4 5 6]]
Number of dimensions (ndim): 2
Shape: (2, 3)
Size (number of elements): 6
Data type (dtype): int64
------------------------------
3D Array:
[[[1 2]
[3 4]]
[[5 6]
[7 8]]]
Number of dimensions (ndim): 3
Shape: (2, 2, 2)
Size (number of elements): 8
Data type (dtype): int64
------------------------------
Array with specified data type (float):
[1. 2. 3.]
Number of dimensions (ndim): 1
Shape: (3,)
Size (number of elements): 3
Data type (dtype): float64
=== Code Execution Successful ===
4.Python program to demonstrate basic slicing,integer and Boolean indexing
import numpy as np
# Creating a 2D array
array_2d = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]])
print("Original 2D Array:")
print(array_2d)
# Basic slicing
print("\nBasic Slicing:")
# Slicing to get the first two rows and first three columns
sliced_array = array_2d[:2, :3]
print(sliced_array)
# Integer indexing
print("\nInteger Indexing:")
# Accessing specific elements
indexed_array = array_2d[[0, 1], [1, 3]] # Get elements (0,1) and (1,3)
print(indexed_array)
# Boolean indexing
print("\nBoolean Indexing:")
# Creating a boolean mask for elements greater than 6
boolean_mask = array_2d > 6
print("Boolean Mask:")
print(boolean_mask)
# Using the boolean mask to index the array
filtered_array = array_2d[boolean_mask]
print("Filtered Array (elements > 6):")
print(filtered_array)
Output:
Original 2D Array:
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
Basic Slicing:
[[1 2 3]
[5 6 7]]
Integer Indexing:
[2 8]
Boolean Indexing:
Boolean Mask:
[[False False False False]
[False False True True]
[ True True True True]]
Filtered Array (elements > 6):
[ 7 8 9 10 11 12]
=== Code Execution Successful ===
5. Python Program to find Min,Max, Sum,Cumilative sum of array
import numpy as np
# Creating a NumPy array
array = np.array([1, 2, 3, 4, 5])
print("Original Array:")
print(array)
# Finding the minimum value
min_value = np.min(array)
print("\nMinimum Value:", min_value)
# Finding the maximum value
max_value = np.max(array)
print("Maximum Value:", max_value)
# Finding the sum of all elements
total_sum = np.sum(array)
print("Sum of all elements:", total_sum)
# Finding the cumulative sum
cumulative_sum = np.cumsum(array)
print("Cumulative Sum:")
print(cumulative_sum)
Output:
Original Array:
[1 2 3 4 5]
Minimum Value: 1
Maximum Value: 5
Sum of all elements: 15
Cumulative Sum:
[ 1 3 6 10 15]
6.Create a Dictionary with atleast 5 keys and each key represent a value as a list
where this list contains atleast n values and convert this dictionary as a pandas
data frame and explore the data through the data frame as follows
a.Apply head() to 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 5 keys
data_dict = {
'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eva'],
'Age': [24, 30, 22, 35, 28],
'City': ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Phoenix'],
'Salary': [70000, 80000, 50000, 120000, 95000],
'Department': ['HR', 'IT', 'Finance', 'Marketing', 'IT']
}
# Step 2: Convert the dictionary to a DataFrame
df = pd.DataFrame(data_dict)
# Step 3a: Apply head() to view the first few rows of the DataFrame
print("DataFrame Head:")
print(df.head())
# Step 3b: Perform various data selection operations
# Select a single column
print("\nSelect 'Name' column:")
print(df['Name'])
# Select multiple columns
print("\nSelect 'Name' and 'Age' columns:")
print(df[['Name', 'Age']])
# Select rows based on condition (Age > 25)
print("\nSelect rows where Age > 25:")
print(df[df['Age'] > 25])
# Select rows based on multiple conditions (Salary > 60000 and Age < 30)
print("\nSelect rows where Salary > 60000 and Age < 30:")
print(df[(df['Salary'] > 60000) & (df['Age'] < 30)])
# Select a specific row by index
print("\nSelect the row with index 2:")
print(df.iloc[2])
# Select a specific element (Salary of 'Charlie')
print("\nSelect the Salary of Charlie:")
print(df.loc[df['Name'] == 'Charlie', 'Salary'].values[0])
Ouput:
DataFrame Head:
Name Age City Salary Department
0 Alice 24 New York 70000 HR
1 Bob 30 Los Angeles 80000 IT
2 Charlie 22 Chicago 50000 Finance
3 David 35 Houston 120000 Marketing
4 Eva 28 Phoenix 95000 IT
Select 'Name' column:
0 Alice
1 Bob
2 Charlie
3 David
4 Eva
Name: Name, dtype: object
Select 'Name' and 'Age' columns:
Name Age
0 Alice 24
1 Bob 30
2 Charlie 22
3 David 35
4 Eva 28
Select rows where Age > 25:
Name Age City Salary Department
1 Bob 30 Los Angeles 80000 IT
3 David 35 Houston 120000 Marketing
4 Eva 28 Phoenix 95000 IT
Select rows where Salary > 60000 and Age < 30:
Name Age City Salary Department
0 Alice 24 New York 70000 HR
4 Eva 28 Phoenix 95000 IT
Select the row with index 2:
Name Charlie
Age 22
City Chicago
Salary 50000
Department Finance
Name: 2, dtype: object
Select the Salary of Charlie:
50000
=== Code Execution Successful ===
7.Select any two coloums 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
# Sample DataFrame
data = {
'column1': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'column2': [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
}
df = pd.DataFrame(data)
# Scatter Plot
plt.figure(figsize=(10, 6))
plt.scatter(df['column1'], df['column2'], color='blue', alpha=0.5)
plt.title('Scatter Plot of Column1 vs Column2')
plt.xlabel('Column 1')
plt.ylabel('Column 2')
plt.grid()
plt.show()
# Line Plot
plt.figure(figsize=(10, 6))
plt.plot(df['column1'], df['column2'], marker='o', linestyle='-', color='red')
plt.title('Line Plot of Column1 vs Column2')
plt.xlabel('Column 1')
plt.ylabel('Column 2')
plt.grid()
plt.show()