PP Lab Manual
PP Lab Manual
Aim:
Program:
largest = num1
largest = num2
else:
largest = num3
return largest
Output:
defis_prime(n):
if n <= 1:
return False
if n % i == 0:
return False
return True
deffind_primes(start, end):
ifis_prime(num):
Output:
2 3 5 7
Experiment 3:Write a program to swap two numbers without using a temporary
variable.
Defis_prime(n):
if n <= 1:
return False
if n % i == 0:
return False
return True
deffind_primes(start, end):
ifis_prime(num):
find_primes(start, end)
Output:
defdemonstrate_operators():
# Arithmetic Operators
a = 10
b = 3
print(f"Arithmetic Operators:")
# Relational Operators
print(f"Relational Operators:")
print(f"a == b: {a == b}")
print(f"a != b: {a != b}")
# Assignment Operators
print(f"Assignment Operators:")
a = 10
print(f"a = {a}")
a += 5
print(f"a += 5: {a}")
a -= 3
print(f"a -= 3: {a}")
a *= 2
print(f"a *= 2: {a}")
a /= 4
print(f"a /= 4: {a}")
a //= 2
a %= 3
print(f"a %= 3: {a}")
a **= 2
# Logical Operators
x = True
y = False
print(f"Logical Operators:")
print(f"x or y: {x or y}")
# Bitwise Operators
a = 10 # 1010 in binary
b = 4 # 0100 in binary
print(f"Bitwise Operators:")
print(f"a | b: {a | b}")
print(f"a ^ b: {a ^ b}")
print(f"~a: {~a}")
# Ternary Operator
a = 10
b = 20
print(f"Ternary Operator:")
print(result + "\n")
# Membership Operators
my_list = [1, 2, 3, 4, 5]
print(f"Membership Operators:")
# Identity Operators
print(f"Identity Operators:")
a = 10
b = 10
c = a
print(f"a is b: {a is b}")
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1
demonstrate_operators()
Output:
Arithmetic Operators:
Addition: 10 + 3 = 13
Subtraction: 10 - 3 = 7
Multiplication: 10 * 3 = 30
Division: 10 / 3 = 3.3333333333333335
Floor Division: 10 // 3 = 3
Modulus: 10 % 3 = 1
Exponentiation: 10 ** 3 = 1000
Relational Operators:
a == b: False
a != b: True
a > b: True
a < b: False
a >= b: True
a <= b: False
Assignment Operators:
a = 10
a += 5: 15
a -= 3: 12
a *= 2: 24
a /= 4: 6.0
a //= 2: 3.0
a %= 3: 0.0
a **= 2: 0.0
Logical Operators:
x and y: False
x or y: True
not x: False
Bitwise Operators:
a& b: 0
a | b: 14
a ^ b: 14
~a: -11
a<< 1: 20
a>> 1: 5
Ternary Operator:
b is greater
Membership Operators:
3 in my_list: True
Identity Operators:
a is b: True
a is not c: False
Experiment 6:
defadd_complex(c1, c2):
return c1 + c2
defmultiply_complex(c1, c2):
return c1 * c2
# Example usage
Output:
Enter the first complex number (in the form a+bj): 5+6j
Enter the second complex number (in the form a+bj): 2+3j
defprint_multiplication_table(n, upto=10):
# Example usage
print_multiplication_table(number, upto)
Output:
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15
3 x 6 = 18
3 x 7 = 21
3 x 8 = 24
3 x 9 = 27
3 x 10 = 30
Experiment 7:
defcalculate_operations(a, b):
addition = a + b
subtraction = a - b
multiplication = a * b
if b != 0:
division = a / b
else:
# Example usage
else:
print(f"Division of {num1} by {num2} is not possible (division
by zero)")
Output:
print(greet("Gandhi"))
print(greet("Nehru", greeting="Hi"))
Output:
Hello, Gandhi!
Hi, Nehru!
Hello, Sundhar!!
Experiment 9:
deffind_string_length(input_string):
length = 0
length += 1
return length
# Example usage
length = find_string_length(string)
Output:
Hello, Gandhi!
Hi, Nehru!
Good morning, Modi.
Hello, Sundhar!!
Experiment 10:
defcheck_substring(main_string, substring):
if substring in main_string:
return True
else:
return False
# Example usage
ifcheck_substring(main_string, substring):
else:
Output:
defperform_operations():
# Initial list
my_list = [1, 2, 3, 4, 5]
element_to_add = 6
my_list.append(element_to_add)
element_to_insert = 10
position_to_insert = 2
my_list.insert(position_to_insert, element_to_insert)
end_index = 4
sliced_list = my_list[start_index:end_index]
perform_operations()
Output:
Experiment 12:
defperform_builtin_functions(my_list):
length = len(my_list)
maximum = max(my_list)
minimum = min(my_list)
total_sum = sum(my_list)
my_list = [5, 3, 8, 6, 2, 7, 4, 1]
perform_builtin_functions(my_list)
Output:
Experiment 13:
print(f"Member 1: {member1}")
print(f"Member 2: {member2}")
Output:
defcount_vowels(s):
vowels = 'aeiouAEIOU'
# Example usage
vowel_count = count_vowels(input_string)
Output:
defcheck_key_exists(dictionary, key):
sample_dict = {
"name": "Alice",
"age": 25,
ifcheck_key_exists(sample_dict, key_to_check):
Output:
dictionary[key] = value
return dictionary
# Example usage
sample_dict = {
"name": "Alice",
"age": 25,
defsum_dictionary_values(dictionary):
return sum(dictionary.values())
# Example usage
sample_dict = {
"item1": 10,
"item2": 25,
"item3": 30,
"item4": 45
print(f"Dictionary: {sample_dict}")
total_sum = sum_dictionary_values(sample_dict)
Output:
defsort_and_lowercase_words(input_filename, output_filename):
try:
words = file.read().split()
words.sort()
except Exception as e:
# Example usage
input_filename = 'source.txt'
output_filename = 'sorted_words.txt'
sort_and_lowercase_words(input_filename, output_filename)
Output:
Source.txt
Sorted_words.txt
Experiment 19:
defprint_lines_in_reverse(input_filename):
try:
lines = file.readlines()
reversed_line = line.strip()[::-1]
print(reversed_line)
except Exception as e:
# Example usage
input_filename = 'source.txt'
print_lines_in_reverse(input_filename)
Output:
dlroWolleH
eliFtseT a sisihT
sdroWesaCreppUemoShtiW
Experiment 20:
defcount_file_contents(input_filename):
try:
lines = file.readlines()
num_lines = len(lines)
except Exception as e:
# Example usage
input_filename = 'source.txt'
count_file_contents(input_filename)
Output:
Number of lines: 3
Number of words: 11
Number of characters: 58
Experiment 21:
import array
defdisplay_array(arr):
print("Array:", arr.tolist())
def main():
print("Initial array:")
display_array(arr)
arr.append(6)
print("\nArray after appending 6:")
display_array(arr)
display_array(arr)
arr.reverse()
if __name__ == "__main__":
main()
Output:
Initial array:
Array: [1, 2, 3, 4, 5]
Array: [1, 2, 3, 4, 5, 6]
Array: [1, 2, 9, 3, 4, 5, 6]
Array: [6, 5, 4, 3, 9, 2, 1]
Experiment 22:
importnumpy as np
defadd_matrices(matrix1, matrix2):
return result
deftranspose_matrix(matrix):
return result
defmultiply_matrices(matrix1, matrix2):
return result
defprint_matrix(matrix):
print(row)
# Example matrices
matrix1 = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
matrix2 = [
[9, 8, 7],
[6, 5, 4],
[3, 2, 1]
print("Matrix 1:")
print_matrix(matrix1)
print("\nMatrix 2:")
print_matrix(matrix2)
# Adding matrices
# Transposing matrix1
transpose_matrix1 = transpose_matrix(matrix1)
print_matrix(transpose_matrix1)
# Multiplying matrices
print_matrix(product_matrix)
Output:
Matrix 1:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
Matrix 2:
[9, 8, 7]
[6, 5, 4]
[3, 2, 1]
Transpose of Matrix 1:
[1, 4, 7]
[2, 5, 8]
[3, 6, 9]
import math
class Shape:
def area(self):
pass
def perimeter(self):
pass
class Circle(Shape):
def area(self):
returnmath.pi * self.radius ** 2
def perimeter(self):
class Triangle(Shape):
self.b = b
self.c = c
def area(self):
def perimeter(self):
class Square(Shape):
self.side = side
def area(self):
returnself.side ** 2
def perimeter(self):
return 4 * self.side
# Example usage
shapes = [
Circle(5),
Triangle(3, 4, 5),
Square(4)
]
for shape in shapes:
print(f"{shape.__class__.__name__}:")
print()
Output:
Circle:
Area: 78.54
Perimeter: 31.42
Triangle:
Area: 6.00
Perimeter: 12.00
Square:
Area: 16.00
Perimeter: 16.00
Experiment 24:
importjson
defcheck_json_complexity(json_str):
try:
parsed_json = json.loads(json_str)
exceptjson.JSONDecodeError:
return False
# Example usage
json_str1 = '{"name": "Alice", "age": 30, "address": {"city":
"Wonderland", "zip": "12345"}}'
Experiment 25:
importnumpy as np
# Create a 1D array
print("1D Array:")
print(arr1)
print()
print(arr2)
print()
# Create a 3D array
print(arr3)
Output:
1D Array:
[1 2 3 4 5]
2D Array (Matrix):
[[1 2 3]
[4 5 6]
[7 8 9]]
3D Array:
[[[1 2]
[3 4]]
[[5 6]
[7 8]]]
Experiment 26:
importnumpy as np
# Create a 1D array
print("1D Array:")
print("Array:", arr1)
print("Dimensions:", arr1.ndim)
print("Shape:", arr1.shape)
print("Size:", arr1.size)
print()
print(arr2)
print("Dimensions:", arr2.ndim)
print("Shape:", arr2.shape)
print("Size:", arr2.size)
print()
# Create a 3D array
print("3D Array:")
print("Array:")
print(arr3)
print("Dimensions:", arr3.ndim)
print("Shape:", arr3.shape)
print("Size:", arr3.size)
Output:
1D Array:
Array: [1 2 3 4 5]
Dimensions: 1
Shape: (5,)
Size: 5
2D Array (Matrix):
Array:
[[1 2 3]
[4 5 6]
[7 8 9]]
Dimensions: 2
Shape: (3, 3)
Size: 9
3D Array:
Array:
[[[1 2]
[3 4]]
[[5 6]
[7 8]]]
Dimensions: 3
Shape: (2, 2, 2)
Size: 8
Experiment 27:
importnumpy as np
# Basic slicing
print("Slicing Examples:")
print()
# Integer indexing
print()
# Boolean indexing
Output:
Original Array: [1 2 3 4 5]
Slicing Examples:
arr[2:5] = [3 4 5]
arr[:3] = [1 2 3]
arr[3:] = [4 5]
arr[0] = 1
arr[-1] = 5
arr[[1, 3, 4]] = [2 4 5]
arr[mask] = [1 3 5]
Experiment 28:
importnumpy as np
min_value = np.min(arr)
max_value = np.max(arr)
print("Maximum value:", max_value)
sum_value = np.sum(arr)
cumsum_values = np.cumsum(arr)
Output:
Minimum value: 1
Maximum value: 9
Sum of elements: 25
Experiment 29:
import pandas as pd
importnumpy as np
data_dict = {
'B': np.random.rand(10),
df = pd.DataFrame(data_dict)
print("DataFrame:")
print(df)
print()
print(df.head())
print()
print("Selection Operations:")
print(df[['A', 'C']])
print()
print(df[df['D']])
print()
print()
Output:
DataFrame:
A B C D E
Head of DataFrame:
A B C D E
Selection Operations:
A C
0 30 apple
1 20 banana
2 82 cherry
3 97 date
4 59 elderberry
5 83 fig
6 38 grape
7 31 honeydew
8 79imbe
9 10 jackfruit
Selecting rows where column D is True:
A B C D E
B E
0 0.926616 2023-01-01
1 0.734918 2023-01-02
3 0.834334 2023-01-04
Experiment 30:
import pandas as pd
importnumpy as np
importmatplotlib.pyplot as plt
data_dict = {
'B': np.random.rand(10),
df = pd.DataFrame(data_dict)
x_column = 'A'
y_column = 'B'
# Scatter plot
plt.figure(figsize=(8, 6))
plt.scatter(df[x_column], df[y_column], color='blue',
label='Data Points')
plt.xlabel(x_column)
plt.ylabel(y_column)
plt.legend()
plt.grid(True)
plt.show()
# Line plot
plt.figure(figsize=(8, 6))
plt.xlabel(x_column)
plt.ylabel(y_column)
plt.legend()
plt.grid(True)
plt.show()
Output: