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

Python programs

Uploaded by

suyogtaware229
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Python programs

Uploaded by

suyogtaware229
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Python :

Practical 1 Perform python program to implement all list operations.

# Initialize an empty list


my_list = []

# Adding elements to the list


my_list.append(10) # Adding a single element
my_list.extend([20, 30, 40]) # Adding multiple elements
my_list.insert(2, 15) # Inserting an element at a speci c position

print("List after adding elements:", my_list)

# Removing elements from the list


my_list.remove(20) # Removing a speci c element by value
popped_element = my_list.pop() # Removing the last element and storing it
my_list.pop(1) # Removing an element by index

print("List after removing elements:", my_list)


print("Popped element:", popped_element)

# Accessing elements
rst_element = my_list[0]
last_element = my_list[-1]
print("First element:", rst_element)
print("Last element:", last_element)

# Slicing the list


sub_list = my_list[1:3] # Getting a slice of the list
print("Sliced list:", sub_list)

# Sorting the list


my_list.sort() # Sort in ascending order
print("Sorted list:", my_list)

my_list.sort(reverse=True) # Sort in descending order


print("List sorted in descending order:", my_list)

# Other useful list operations


print("Length of the list:", len(my_list)) # Getting the length of the list
print("Maximum element:", max(my_list)) # Finding the maximum element
print("Minimum element:", min(my_list)) # Finding the minimum element
print("Sum of elements:", sum(my_list)) # Finding the sum of elements

# Clearing the list


my_list.clear()
print("List after clearing:", my_list)

1
fi

fi
fi
fi
Practical 2 : Perform python program to implement all dictionary
operations.
# Initialize an empty dictionary
my_dict = {}

# Adding key-value pairs


my_dict['name'] = 'Alice'
my_dict['age'] = 25
my_dict['city'] = 'New York'

print("Dictionary after adding elements:", my_dict)

# Updating an existing key


my_dict['age'] = 26
print("Dictionary after updating age:", my_dict)

# Accessing elements by key


name = my_dict.get('name') # Using get() method to access value
print("Accessed name:", name)

# Using the key directly (raises KeyError if key doesn't exist)


city = my_dict['city']
print("Accessed city:", city)

# Removing elements
my_dict.pop('city') # Removes a key and returns its value
print("Dictionary after removing 'city':", my_dict)

# Removing an item using del


del my_dict['age'] # Deletes the speci ed key-value pair
print("Dictionary after deleting 'age':", my_dict)

# Adding multiple key-value pairs using update()


my_dict.update({'country': 'USA', 'gender': 'Female'})
print("Dictionary after update with multiple elements:", my_dict)

# Checking if a key exists


if 'name' in my_dict:
print("The key 'name' exists in the dictionary.")

# Iterating over the dictionary


print("Keys and values in the dictionary:")
for key, value in my_dict.items():
print(f"{key}: {value}")

2

fi
# Dictionary keys, values, and items
keys = my_dict.keys() # Getting all keys
values = my_dict.values() # Getting all values
items = my_dict.items() # Getting all key-value pairs

print("Keys:", keys)
print("Values:", values)
print("Items:", items)

# Length of the dictionary


print("Number of items in the dictionary:", len(my_dict))

# Clearing all elements in the dictionary


my_dict.clear()
print("Dictionary after clearing all elements:", my_dict)

Practical 3 Perform python program to implement all set


operations.
# Initialize two sets
set_a = {1, 2, 3, 4, 5}
set_b = {4, 5, 6, 7, 8}

print("Initial sets:")
print("Set A:", set_a)
print("Set B:", set_b)

# Adding elements to a set


set_a.add(6) # Add a single element
set_a.update([7, 8]) # Add multiple elements

print("\nSet A after adding elements:", set_a)

# Removing elements from a set


set_a.discard(8) # Removes an element, does nothing if the element is not found
set_a.remove(7) # Removes an element, raises KeyError if not found
print("Set A after removing elements:", set_a)

# Set Union
union_set = set_a | set_b # or use set_a.union(set_b)
print("\nUnion of Set A and Set B:", union_set)

# Set Intersection
intersection_set = set_a & set_b # or use set_a.intersection(set_b)
print("Intersection of Set A and Set B:", intersection_set)

# Set Di erence

3

ff
di erence_set = set_a - set_b # or use set_a.di erence(set_b)
print("Di erence of Set A and Set B (A - B):", di erence_set)

# Symmetric Di erence
symmetric_di _set = set_a ^ set_b # or use set_a.symmetric_di erence(set_b)
print("Symmetric Di erence of Set A and Set B:", symmetric_di _set)

# Checking subset and superset


is_subset = set_a <= union_set # or use set_a.issubset(union_set)
is_superset = union_set >= set_a # or use union_set.issuperset(set_a)
print("\nIs Set A a subset of Union Set?:", is_subset)
print("Is Union Set a superset of Set A?:", is_superset)

# Checking element existence


print("\nIs 3 in Set A?", 3 in set_a)
print("Is 10 in Set A?", 10 in set_a)

# Clearing all elements in a set


set_a.clear()
print("\nSet A after clearing all elements:", set_a)

Practical 4 To implement all tuple operations


empty_tuple = ()
print("Empty Tuple:", empty_tuple)

# Creating a tuple with one element (note the comma)


single_element_tuple = (42,)
print("Single Element Tuple:", single_element_tuple)

# Creating a tuple with multiple elements


my_tuple = (10, 20, 30, 40, 50)
print("Original Tuple:", my_tuple)

# Creating a tuple without parentheses


another_tuple = 60, 70, 80
print("Another Tuple:", another_tuple)

# 2. Accessing Elements
# Accessing elements by index
rst_element = my_tuple[0]
third_element = my_tuple[2]
last_element = my_tuple[-1]
print("\nAccessed Elements:")
print("First Element:", rst_element)
print("Third Element:", third_element)
print("Last Element:", last_element)

4
fi

ff
ff
ff
ff
ff
fi
ff
ff
ff
ff
# 3. Slicing Tuples
# Slicing to get a sub-tuple
sub_tuple = my_tuple[1:4] # Elements at indices 1, 2, 3
print("\nSliced Tuple (indices 1 to 3):", sub_tuple)

# Slicing with step


step_slice = my_tuple[::2] # Every second element
print("Sliced Tuple with Step 2:", step_slice)

# 4. Concatenation and Repetition


# Concatenating two tuples
concatenated_tuple = my_tuple + another_tuple
print("\nConcatenated Tuple:", concatenated_tuple)

# Repeating a tuple
repeated_tuple = my_tuple * 2
print("Repeated Tuple:", repeated_tuple)

# 5. Membership Testing
# Checking if an element exists in a tuple
print("\nMembership Testing:")
print("Is 20 in my_tuple?", 20 in my_tuple)
print("Is 100 in my_tuple?", 100 in my_tuple)

# 6. Iteration
# Iterating through a tuple
print("\nIterating through my_tuple:")
for item in my_tuple:
print(item)

# 7. Tuple Methods
# Using count() method
count_20 = my_tuple.count(20)
print("\nNumber of times 20 appears in my_tuple:", count_20)

# Using index() method


index_30 = my_tuple.index(30)
print("Index of element 30 in my_tuple:", index_30)

# 8. Nested Tuples
# Creating a nested tuple
nested_tuple = (1, 2, (3, 4), 5)
print("\nNested Tuple:", nested_tuple)

# Accessing elements in a nested tuple


nested_element = nested_tuple[2][1]
print("Accessed Nested Element (3rd tuple's 2nd element):", nested_element)

# 9. Unpacking Tuples

5

# Unpacking tuple elements into variables
a, b, c, d, e = my_tuple
print("\nUnpacked Tuple Elements:")
print("a =", a)
print("b =", b)
print("c =", c)
print("d =", d)
print("e =", e)

# Unpacking with * (star) operator


fruits = ("apple", "banana", "cherry", "date")
rst, *middle, last = fruits
print("\nUnpacked with * operator:")
print("First Fruit:", rst)
print("Middle Fruits:", middle)
print("Last Fruit:", last)

# 10. Immutability of Tuples


# Attempting to modify a tuple (will raise TypeError)
print("\nAttempting to modify a tuple:")
try:
my_tuple[1] = 25
except TypeError as e:
print("Error:", e)

# However, you can create a new tuple by concatenation


new_tuple = my_tuple + (60,)
print("New Tuple after Concatenation:", new_tuple)

# 11. Built-in Functions with Tuples


# Using len() to get the number of elements
tuple_length = len(my_tuple)
print("\nLength of my_tuple:", tuple_length)

# Using max() and min()


max_element = max(my_tuple)
min_element = min(my_tuple)
print("Maximum element in my_tuple:", max_element)
print("Minimum element in my_tuple:", min_element)

# Using sorted() to get a sorted list from the tuple


sorted_list = sorted(my_tuple)
print("Sorted List from my_tuple:", sorted_list)

# Converting a list to a tuple


sample_list = [100, 200, 300]
converted_tuple = tuple(sample_list)
print("\nConverted Tuple from List:", converted_tuple)

6
fi

fi
# Converting a tuple to a list
converted_list = list(my_tuple)
print("Converted List from Tuple:", converted_list)

Practical 5 Perform python program to implement all string


operations.

# Initialize strings
str1 = "Hello"
str2 = "World"
sentence = " Python programming is fun! "

# Basic operations
concat = str1 + " " + str2
repeat = str1 * 3
length = len(str1)

# Accessing elements
rst_char = str1[0]
last_char = str1[-1]

# Slicing
substring = sentence[2:10]
reverse_str1 = str1[::-1]

# String case methods


upper_case = str1.upper()
lower_case = str2.lower()
title_case = sentence.title()
capitalize_case = sentence.capitalize()

# Trimming whitespace
stripped = sentence.strip()
lstrip = sentence.lstrip()
rstrip = sentence.rstrip()

# Finding substrings
index_prog = sentence. nd("programming")
count_o = str1.count('o')
starts_with_hello = sentence.startswith("Hello")
ends_with_fun = sentence.endswith("fun!")

# Replacing
replace_python = sentence.replace("Python", "Java")

# Splitting and joining

7
fi

fi
words = sentence.split()
comma_joined = ", ".join(words)

# Testing for characters


is_alpha = str1.isalpha()
is_digit = "12345".isdigit()
is_alnum = "abc123".isalnum()

# Formatting strings
name = "Alice"
age = 25
formatted_string = f"My name is {name} and I am {age} years old."

# Encoding and decoding


encoded = str1.encode("utf-8")
decoded = encoded.decode("utf-8")

# Output results
print("Concatenation:", concat)
print("Repetition:", repeat)
print("Length:", length)
print("First character:", rst_char)
print("Last character:", last_char)
print("Substring:", substring)
print("Reversed str1:", reverse_str1)
print("Upper case:", upper_case)
print("Lower case:", lower_case)
print("Title case:", title_case)
print("Capitalized case:", capitalize_case)
print("Stripped:", stripped)
print("Left stripped:", lstrip)
print("Right stripped:", rstrip)
print("Index of 'programming':", index_prog)
print("Count of 'o':", count_o)
print("Starts with 'Hello':", starts_with_hello)
print("Ends with 'fun!':", ends_with_fun)
print("Replaced 'Python' with 'Java':", replace_python)
print("Words in sentence:", words)
print("Comma joined:", comma_joined)
print("Is alpha:", is_alpha)
print("Is digit:", is_digit)
print("Is alphanumeric:", is_alnum)
print("Formatted string:", formatted_string)
print("Encoded:", encoded)
print("Decoded:", decoded)

8

fi
Practical 6 Perform python program to display Armstrong
numbers in range from 1-1000

# Display Armstrong numbers from 1 to 1000

for num in range(1, 1001):


# Convert number to string to get number of digits
power = len(str(num))

# Calculate sum of digits raised to the power


sum_of_powers = sum(int(digit) ** power for digit in str(num))

# Check if the number is an Armstrong number


if num == sum_of_powers:
print(num)

Practical 7 Perform python program to display prime numbers in


range from 1-100

# Display prime numbers from 1 to 100

for num in range(2, 101): # Start from 2, as 1 is not a prime number


is_prime = True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(num)

Practical 8 Perform python program to print nth Fibonacci


numbers. N is given by user.

n = int(input("Enter the position of the Fibonacci number you want: "))


def bonacci(n):
if n <= 0:
return "Invalid input"
elif n == 1:
return 0
elif n == 2:
return 1
else:
a, b = 0, 1

9

fi
for _ in range(3, n + 1):
a, b = b, a + b
return b
print(f"The {n}th Fibonacci number is: { bonacci(n)}")

Practical 9 Perform python program to perform matrix arithmetic


operations addition and multiplication for M by N size. M and N
should be entered by user

# Input dimensions for the matrices


M = int(input("Enter the number of rows (M): "))
N = int(input("Enter the number of columns (N): "))

# Function to input matrix elements


def input_matrix(M, N):
matrix = []
for i in range(M):
row = list(map(int, input(f"Enter row {i + 1} elements separated by spaces:
").split()))
if len(row) != N:
print("Error: Number of elements does not match the speci ed column
count.")
return None
matrix.append(row)
return matrix

# Input two matrices


print("Enter elements for Matrix 1:")
matrix1 = input_matrix(M, N)
print("Enter elements for Matrix 2:")
matrix2 = input_matrix(M, N)

# Check for successful input


if matrix1 is None or matrix2 is None:
print("Matrix input failed.")
else:
# Matrix Addition
addition_result = [[matrix1[i][j] + matrix2[i][j] for j in range(N)] for i in range(M)]

# Matrix Multiplication (only possible if square matrix M x M)


if M == N:
multiplication_result = [[sum(matrix1[i][k] * matrix2[k][j] for k in range(M)) for j in
range(N)] for i in range(M)]
else:
multiplication_result = None

# Output results

10

fi
fi
print("\nMatrix 1:")
for row in matrix1:
print(row)

print("\nMatrix 2:")
for row in matrix2:
print(row)

print("\nMatrix Addition Result:")


for row in addition_result:
print(row)

if multiplication_result:
print("\nMatrix Multiplication Result:")
for row in multiplication_result:
print(row)
else:
print("\nMatrix Multiplication is not possible for non-square matrices.")

Practical 10 Perform python program to implement linear search


on 20 random generated number.

import random

numbers = [random.randint(1, 100) for _ in range(20)]


print("Generated numbers:", numbers)

target = int(input("Enter the number to search for: "))

def linear_search(numbers, target):


for index, num in enumerate(numbers):
if num == target:
return index
return -1

result = linear_search(numbers, target)

if result != -1:
print(f"Number {target} found at index {result}")
else:
print(f"Number {target} not found in the list")

11

Practical 11 Perform python program to implement binary search
for strings.

def binary_search(arr, target):


low = 0
high = len(arr) - 1

while low <= high:


mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1

strings = ["apple", "banana", "cherry", "date", "elderberry", " g", "grape", "kiwi",
"lemon", "mango"]
strings.sort()

print("Sorted list of strings:", strings)

target = input("Enter the string to search for: ")

result = binary_search(strings, target)

if result != -1:
print(f"String '{target}' found at index {result}")
else:
print(f"String '{target}' not found in the list")

Practical 12 Perform python program to perform all operation of


random functions.

import random

# Generate random integer between 1 and 100


rand_int = random.randint(1, 100)

# Generate random oat between 0 and 1


rand_ oat = random.random()

# Generate random oat between 5 and 10


rand_uniform = random.uniform(5, 10)

12

fl
fl
fl
fi
# Generate random choice from a list
rand_choice = random.choice([10, 20, 30, 40, 50])

# Generate random sample of 3 elements from a list


rand_sample = random.sample([1, 2, 3, 4, 5, 6], 3)

# Shu e a list randomly


rand_list = [1, 2, 3, 4, 5]
random.shu e(rand_list)

# Generate random number from a range with a step


rand_range = random.randrange(0, 20, 5)

# Set a seed for reproducibility


random.seed(42)

# Generate random integer after setting the seed


rand_int_seed = random.randint(1, 100)

print(rand_int)
print(rand_ oat)
print(rand_uniform)
print(rand_choice)
print(rand_sample)
print(rand_list)
print(rand_range)
print(rand_int_seed)

Practical 13 Perform python program to perform all math


operations.
import math

# Square root
sqrt_value = math.sqrt(25)

# Factorial
factorial_value = math.factorial(5)

# Power
power_value = math.pow(2, 3)

# Logarithm
log_value = math.log(100, 10)

# Exponential
exp_value = math.exp(2)

13

ffl
fl
ffl
# Sine, Cosine, and Tangent
sin_value = math.sin(math.radians(30))
cos_value = math.cos(math.radians(60))
tan_value = math.tan(math.radians(45))

# Absolute value
abs_value = abs(-10)

# Greatest common divisor


gcd_value = math.gcd(36, 60)

# Rounding
round_value = round(3.14159, 2)

# Pi and Euler's number


pi_value = math.pi
e_value = math.e

print(sqrt_value)
print(factorial_value)
print(power_value)
print(log_value)
print(exp_value)
print(sin_value)
print(cos_value)
print(tan_value)
print(abs_value)
print(gcd_value)
print(round_value)
print(pi_value)
print(e_value)

Practical 14 Perform a python program to create user-de ned


functions with di erent types of function arguments for real
applications.

# Function with positional arguments


def add_numbers(a, b):
return a + b

# Function with default argument


def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"

# Function with keyword arguments


def student_info(name, age, grade):

14

ff
fi
return f"Name: {name}, Age: {age}, Grade: {grade}"

# Function with variable-length arguments (*args)


def sum_numbers(*args):
return sum(args)

# Function with arbitrary keyword arguments (**kwargs)


def print_person_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")

# Real-world application: Basic Calculator


def calculator(operation, *args):
if operation == "add":
return sum_numbers(*args)
elif operation == "multiply":
result = 1
for num in args:
result *= num
return result
else:
return "Invalid operation"

# Example uses
# Positional Arguments
print("Addition:", add_numbers(10, 20))

# Default Argument
print(greet("Alice"))
print(greet("Bob", "Hi"))

# Keyword Arguments
print(student_info(name="Charlie", age=17, grade="A"))

# Variable-Length Arguments
print("Sum of numbers:", sum_numbers(1, 2, 3, 4, 5))

# Arbitrary Keyword Arguments


print_person_info(name="John", age=30, occupation="Engineer", country="USA")

# Calculator Function
print("Sum of 5, 10, 15:", calculator("add", 5, 10, 15))
print("Product of 2, 3, 4:", calculator("multiply", 2, 3, 4))

15

Practical 15 Perform a python program to create packages and
import modules from di erent packages for any one real
application.

calculator/
__init__.py
add.py
subtract.py
multiply.py
divide.py
main.py

def add(a, b):


return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b != 0:
return a / b
else:
return "Cannot divide by zero"
from calculator.add import add
from calculator.subtract import subtract
from calculator.multiply import multiply
from calculator.divide import divide

num1 = 10
num2 = 5

print("Addition:", add(num1, num2))


print("Subtraction:", subtract(num1, num2))
print("Multiplication:", multiply(num1, num2))
print("Division:", divide(num1, num2))

16

ff
Practical 16 Perform a python program to Perform File
manipulations- open, close, read, write,append and copy from one
le to another for binary and text les.
# Writing to a text le

with open('text le.txt', 'w') as f:

f.write("Hello, this is a text le.\nThis is the second line.")

# Reading from a text le

with open('text le.txt', 'r') as f:

content = f.read()

print(content)

# Appending to a text le

with open('text le.txt', 'a') as f:

f.write("\nThis is an appended line.")

# Copying content from one text le to another

with open('text le.txt', 'r') as f:

content = f.read()

with open('copy_text le.txt', 'w') as f:

f.write(content)

# Writing to a binary le

with open('binary le.bin', 'wb') as f:

f.write(b'Hello, this is a binary le.')

# Reading from a binary le

17
fi

fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
with open('binary le.bin', 'rb') as f:

content = f.read()

print(content)

# Appending to a binary le

with open('binary le.bin', 'ab') as f:

f.write(b'\nAppending binary data.')

# Copying content from one binary le to another

with open('binary le.bin', 'rb') as f:

content = f.read()

with open('copy_binary le.bin', 'wb') as f:

f.write(content)

Practical 17 Perform a python program to handle user de ned


exceptions.

class NegativeValueError(Exception):

def __init__(self, message="Value cannot be negative"):

self.message = message

super().__init__(self.message)

def check_positive_value(value):

if value < 0:

raise NegativeValueError("Negative value provided")

return value

18

fi
fi
fi
fi
fi
fi
fi
try:

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

result = check_positive_value(num)

print(f"You entered: {result}")

except NegativeValueError as e:

print(f"Error: {e}")

except ValueError:

print("Error: Please enter a valid integer")

Practical 18 Perform a python program to handle di erent types of


exceptions with multiple options.

def divide_numbers():

try:

num1 = int(input("Enter the rst number: "))

num2 = int(input("Enter the second number: "))

result = num1 / num2

print(f"The result of division is: {result}")

except ZeroDivisionError:

print("Error: Division by zero is not allowed.")

except ValueError:

print("Error: Invalid input. Please enter valid integers.")

def read_ le():

try:

lename = input("Enter the lename to read: ")

with open( lename, 'r') as le:

19

fi
fi
fi
fi
fi
fi
ff
content = le.read()

print(content)

except FileNotFoundError:

print("Error: The le does not exist.")

except IOError:

print("Error: An error occurred while reading the le.")

def calculate_square_root():

try:

number = int(input("Enter a number to nd its square root: "))

if number < 0:

raise ValueError("Error: Cannot calculate the square root of a negative


number.")

result = number ** 0.5

print(f"The square root is: {result}")

except ValueError as e:

print(e)

def main():

while True:

print("\nChoose an option:")

print("1. Divide two numbers")

print("2. Read a le")

print("3. Calculate square root of a number")

print("4. Exit")

choice = input("Enter your choice (1/2/3/4): ")

20

fi
fi
fi
fi
fi
if choice == '1':

divide_numbers()

elif choice == '2':

read_ le()

elif choice == '3':

calculate_square_root()

elif choice == '4':

print("Exiting the program.")

break

else:

print("Invalid choice, please select a valid option.")

main()

Practical 19 Perform a python to create command line arguments


for solving binary search operation.

import sys

def binary_search(arr, target):

low = 0

high = len(arr) - 1

while low <= high:

mid = (low + high) // 2

if arr[mid] == target:

return mid

elif arr[mid] < target:

21

fi
low = mid + 1

else:

high = mid - 1

return -1

def main():

# Get the command line arguments (excluding the script name)

args = sys.argv[1:]

# Check if the user has entered enough arguments

if len(args) < 2:

print("Usage: python binary_search.py <sorted_list> <target_number>")

sys.exit(1)

# Convert the arguments into a sorted list and target number

arr = list(map(int, args[:-1])) # All except the last argument

target = int(args[-1]) # The last argument is the target number

# Sort the array (just in case it's not sorted)

arr.sort()

# Perform binary search

result = binary_search(arr, target)

# Output the result

if result != -1:

print(f"Element {target} found at index {result}")

else:

22

print(f"Element {target} not found in the list")

if __name__ == "__main__":

main()

Practical 20 Perform a python to nd the substring in given whole


string using using command line arguments.

import sys

def nd_substring(main_string, substring):

if substring in main_string:

return f"Substring '{substring}' found in the string."

else:

return f"Substring '{substring}' not found in the string."

def main():

# Get the command line arguments (excluding the script name)

args = sys.argv[1:]

# Check if there are enough arguments

if len(args) < 2:

print("Usage: python substring_search.py <main_string> <substring>")

sys.exit(1)

# First argument is the main string, second is the substring

main_string = args[0]

23

fi
fi
substring = args[1]

# Call the function to nd the substring

result = nd_substring(main_string, substring)

# Output the result

print(result)

if __name__ == "__main__":

main()

24

fi
fi

You might also like