PROGRAMS:
Exp 1:
Aim
To write a python program for checking the given number is odd or even.
Algorithm
1. Start
2. Read an integer number from the user and store it in num.
3. Check whether num is divisible by 2 (num % 2 == 0).
4. If the condition is true,
→ Display "Even number".
5. Else,
→ Display "Odd number".
6. Stop
Program
num = int(input("Enter a number: "))
if num % 2 == 0:
print("Even number")
else:
print("Odd number")
Output
Enter a number: 5
Odd number
Result
Thus the python program for checking the given number is odd or even has been written and executed
successfully.
EX. No. 1b FIND THE LARGEST OF THREE NUMBER
Aim
To write a python program to find the largest of three number.
Algorithm
1. Start
2. Read three integer values from the user and store them in variables a, b, and c.
3. Compare a with b and c.
4. If a is greater than or equal to both b and c,
→ Display "Largest is a".
5. Else if b is greater than or equal to both a and c,
→ Display "Largest is b".
6. Else,
→ Display "Largest is c".
7. Stop
Program
a = int(input("Enter a: "))
b = int(input("Enter b: "))
c = int(input("Enter c: "))
if a >= b and a >= c:
print("Largest is", a)
elif b >= a and b >= c:
print("Largest is", b)
else:
print("Largest is", c)
Output
Enter a: 5
Enter b: 6
Enter c: 4
Largest is 6
Result
Thus the python program to find the largest of three number has been written and executed successfully.
Exp 2:
AIM
To write a python program to perform list operations.
1. Start
2. Create a list my_list with elements: 10, 20, 30, 40, 50.
3. Display the initial list.
4. Append the element 60 to the end of the list.
5. Display the list after appending.
6. Insert the element 25 at index position 2.
7. Display the list after insertion.
8. Extend the list by adding elements 70 and 80.
9. Display the list after extending.
10. Remove the element 30 from the list.
11. Display the list after removal.
12. Remove the element at index position 3 using pop operation.
13. Display the list after pop operation.
14. Find and display the index of element 40.
15. Count and display the number of occurrences of element 20.
16. Sort the list in ascending order.
17. Display the sorted list.
18. Reverse the list.
19. Display the reversed list.
20. Copy the list into a new list new_list.
21. Display the copied list.
22. Find and display the length of the list.
23. Find and display the maximum element in the list.
24. Find and display the minimum element in the list.
25. Find and display the sum of all elements in the list.
26. Clear all elements from the list.
27. Display the empty list.
28. Stop
PROGRAM
# Creating a list
my_list = [10, 20, 30, 40, 50]
print("Initial List:", my_list)
# 1. Append (Add element at end)
my_list.append(60)
print("After append:", my_list)
# 2. Insert (Add element at specific position)
my_list.insert(2, 25)
print("After insert:", my_list)
# 3. Extend (Add multiple elements)
my_list.extend([70, 80])
print("After extend:", my_list)
# 4. Remove (Remove specific element)
my_list.remove(30)
print("After remove:", my_list)
# 5. Pop (Remove element using index)
my_list.pop(3)
print("After pop:", my_list)
# 6. Index (Find index of an element)
index = my_list.index(50)
print("Index of 40:", index)
# 7. Count (Count occurrences of an element)
count = my_list.count(20)
print("Count of 20:", count)
# 8. Sort (Ascending order)
my_list.sort()
print("After sort:", my_list)
# 9. Reverse
my_list.reverse()
print("After reverse:", my_list)
# 10. Copy list
new_list = my_list.copy()
print("Copied list:", new_list)
# 11. Length of list
print("Length of list:", len(my_list))
# 12. Maximum and Minimum
print("Maximum element:", max(my_list))
print("Minimum element:", min(my_list))
# 13. Sum of elements
print("Sum of elements:", sum(my_list))
# 14. Clear the list
my_list.clear()
print("After clear:", my_list)
OUTPUT
Initial List: [10, 20, 30, 40, 50]
After append: [10, 20, 30, 40, 50, 60]
After insert: [10, 20, 25, 30, 40, 50, 60]
After extend: [10, 20, 25, 30, 40, 50, 60, 70, 80]
After remove: [10, 20, 25, 40, 50, 60, 70, 80]
After pop: [10, 20, 25, 50, 60, 70, 80]
Index of 40: 3
Count of 20: 1
After sort: [10, 20, 25, 50, 60, 70, 80]
After reverse: [80, 70, 60, 50, 25, 20, 10]
Copied list: [80, 70, 60, 50, 25, 20, 10]
Length of list: 7
Maximum element: 80
Minimum element: 10
Sum of elements: 315
After clear: []
Result
Thus the python program to perform list operations has been written and executed
successfully.
TUPLE OPERATIONS
Aim
To write a python program to perform tuple operations.
Algorithm
1. Start
2. Create a tuple my_tuple with elements: 10, 20, 30, 40, 50, 20.
3. Display the initial tuple.
4. Find and display the length of the tuple.
5. Access and display the first element using index 0.
6. Access and display the last element using negative index -1.
7. Perform slicing from index 1 to 3 and display the sliced tuple.
8. Count and display the number of occurrences of element 20 in the tuple.
9. Find and display the index position of element 30.
10. Check whether element 40 is present in the tuple.
o If present, display an appropriate message.
11. Iterate through the tuple and display each element.
12. Find and display the maximum element in the tuple.
13. Find and display the minimum element in the tuple.
14. Find and display the sum of all elements in the tuple.
15. Create another tuple tuple2 with elements 60 and 70.
16. Concatenate my_tuple with tuple2 and display the new tuple.
17. Repeat my_tuple twice and display the repeated tuple.
18. Convert the tuple into a list to allow modification.
19. Append the element 100 to the list.
20. Convert the modified list back into a tuple and display it.
21. Create and display a nested tuple.
22. Delete the tuple my_tuple.
23. Display a message confirming successful deletion.
24. Stop
Program
# Creating a tuple
my_tuple = (10, 20, 30, 40, 50, 20)
print("Initial Tuple:", my_tuple)
# 1. Length of tuple
print("Length of tuple:", len(my_tuple))
# 2. Access elements using index
print("First element:", my_tuple[0])
print("Last element:", my_tuple[-1])
# 3. Slicing
print("Sliced tuple (1:4):", my_tuple[1:4])
# 4. Count occurrences of an element
print("Count of 20:", my_tuple.count(20))
# 5. Find index of an element
print("Index of 30:", my_tuple.index(30))
# 6. Check membership
if 40 in my_tuple:
print("40 is present in tuple")
# 7. Iterating through tuple
print("Tuple elements:")
for item in my_tuple:
print(item)
# 8. Maximum and Minimum
print("Maximum element:", max(my_tuple))
print("Minimum element:", min(my_tuple))
# 9. Sum of elements
print("Sum of elements:", sum(my_tuple))
# 10. Tuple concatenation
tuple2 = (60, 70)
new_tuple = my_tuple + tuple2
print("After concatenation:", new_tuple)
# 11. Tuple repetition
repeated_tuple = my_tuple * 2
print("After repetition:", repeated_tuple)
# 12. Convert tuple to list (to modify)
temp_list = list(my_tuple)
temp_list.append(100)
modified_tuple = tuple(temp_list)
print("Modified tuple:", modified_tuple)
# 13. Nested tuple
nested_tuple = ((1, 2), (3, 4))
print("Nested tuple:", nested_tuple)
# 14. Delete tuple
del my_tuple
print("Tuple deleted successfully")
Output
Initial Tuple: (10, 20, 30, 40, 50, 20)
Length of tuple: 6
First element: 10
Last element: 20
Sliced tuple (1:4): (20, 30, 40)
Count of 20: 2
Index of 30: 2
40 is present in tuple
Tuple elements:
10
20
30
40
50
20
Maximum element: 50
Minimum element: 10
Sum of elements: 170
After concatenation: (10, 20, 30, 40, 50, 20, 60, 70)
After repetition: (10, 20, 30, 40, 50, 20, 10, 20, 30, 40, 50, 20)
Modified tuple: (10, 20, 30, 40, 50, 20, 100)
Nested tuple: ((1, 2), (3, 4))
Tuple deleted successfully
Aim
To write a python program to perform set operations.
Algorithm
1. Start
2. Create two sets:
o set1 with elements {10, 20, 30, 40, 50}
o set2 with elements {30, 40, 60, 70}
3. Display the initial contents of both sets.
4. Add element 60 to set1.
5. Display set1 after adding the element.
6. Update set1 by adding multiple elements 70 and 80.
7. Display set1 after updating.
8. Remove element 20 from set1.
9. Display set1 after removal.
10. Discard element 100 from set1 (no error if element is not present).
11. Display set1 after discard operation.
12. Remove and display a random element from set1 using the pop operation.
13. Display set1 after popping an element.
14. Find and display the union of set1 and set2.
15. Find and display the intersection of set1 and set2.
16. Find and display the difference between set1 and set2.
17. Find and display the symmetric difference between set1 and set2.
18. Check and display whether set1 is a subset of set2.
19. Check and display whether set1 is a superset of set2.
20. Check whether element 30 is present in set1.
o If present, display an appropriate message.
21. Find and display the length of set1.
22. Create a copy of set1 and store it in set3.
23. Display the copied set.
24. Clear all elements from set1.
25. Display set1 after clearing.
26. Create and display a frozen set with elements {1, 2, 3, 4}.
27. Stop
Program
# Creating sets
set1 = {10, 20, 30, 40, 50}
set2 = {30, 40, 60, 70}
print("Initial Set 1:", set1)
print("Initial Set 2:", set2)
# 1. Add element
[Link](60)
print("After add:", set1)
# 2. Update (add multiple elements)
[Link]([70, 80])
print("After update:", set1)
# 3. Remove element
[Link](20)
print("After remove:", set1)
# 4. Discard element (no error if not present)
[Link](100)
print("After discard:", set1)
# 5. Pop element
removed_element = [Link]()
print("Popped element:", removed_element)
print("After pop:", set1)
# 6. Union
print("Union:", [Link](set2))
# 7. Intersection
print("Intersection:", [Link](set2))
# 8. Difference
print("Difference (set1 - set2):", [Link](set2))
# 9. Symmetric Difference
print("Symmetric Difference:", set1.symmetric_difference(set2))
# 10. Subset and Superset
print("Is set1 subset of set2?", [Link](set2))
print("Is set1 superset of set2?", [Link](set2))
# 11. Check membership
if 30 in set1:
print("30 is present in set1")
# 12. Length of set
print("Length of set1:", len(set1))
# 13. Copy set
set3 = [Link]()
print("Copied set:", set3)
# 14. Clear set
[Link]()
print("After clear set1:", set1)
# 15. Frozen set (immutable set)
frozen = frozenset([1, 2, 3, 4])
print("Frozen set:", frozen)
Output
Initial Set 1: {50, 20, 40, 10, 30}
Initial Set 2: {40, 70, 60, 30}
After add: {50, 20, 40, 10, 60, 30}
After update: {80, 50, 20, 70, 40, 10, 60, 30}
After remove: {80, 50, 70, 40, 10, 60, 30}
After discard: {80, 50, 70, 40, 10, 60, 30}
Popped element: 80
After pop: {50, 70, 40, 10, 60, 30}
Union: {70, 40, 10, 50, 60, 30}
Intersection: {40, 60, 70, 30}
Difference (set1 - set2): {50, 10}
Symmetric Difference: {10, 50}
Is set1 subset of set2? False
Is set1 superset of set2? True
30 is present in set1
Length of set1: 6
Copied set: {50, 70, 40, 10, 60, 30}
After clear set1: set()
Frozen set: frozenset({1, 2, 3, 4})
Result
Thus the python program to perform set operations has been written and executed
successfully.
DICTIONARY OPERATIONS
Aim
To write a python program to perform dictionary operations.
ALGORITHM
1. Start
2. Create a dictionary my_dict with key–value pairs:
o "Name" : "Anuja"
o "Age" : 20
o "Course" : "Python"
3. Display the initial dictionary.
4. Access and display the value associated with the key "Name".
5. Add a new key–value pair "City" : "Hyderabad" to the dictionary.
6. Display the dictionary after adding the new element.
7. Update the value of the key "Age" to 21.
8. Display the dictionary after updating the value.
9. Remove the key "Course" using the pop() method and display the removed value.
10. Display the dictionary after the pop operation.
11. Remove the last inserted key–value pair using the popitem() method.
12. Display the popped item and the updated dictionary.
13. Display all keys present in the dictionary.
14. Display all values present in the dictionary.
15. Display all key–value pairs using the items() method.
16. Check whether the key "Name" exists in the dictionary.
o If it exists, display a confirmation message.
17. Find and display the length of the dictionary.
18. Create a copy of the dictionary and store it in new_dict.
19. Display the copied dictionary.
20. Clear all elements from the original dictionary.
21. Display the empty dictionary.
22. Create a new dictionary using fromkeys() with keys ["a", "b", "c"] and default
value 0.
23. Display the dictionary created using fromkeys().
24. Create and display a nested dictionary named student containing student details and
marks.
25. Iterate through the nested dictionary and display each key and its corresponding value.
26. Stop
Program
# Creating a dictionary
my_dict = {
"Name": "Anuja",
"Age": 20,
"Course": "Python"
}
print("Initial Dictionary:", my_dict)
# 1. Access values using keys
print("Name:", my_dict["Name"])
# 2. Add a new key-value pair
my_dict["City"] = "Hyderabad"
print("After adding City:", my_dict)
# 3. Update an existing value
my_dict["Age"] = 21
print("After updating Age:", my_dict)
# 4. Remove an element using pop()
removed = my_dict.pop("Course")
print("Removed Course:", removed)
print("After pop:", my_dict)
# 5. Remove last inserted item using popitem()
item = my_dict.popitem()
print("Popped item:", item)
print("After popitem:", my_dict)
# 6. Get all keys
print("Keys:", my_dict.keys())
# 7. Get all values
print("Values:", my_dict.values())
# 8. Get all key-value pairs
print("Items:", my_dict.items())
# 9. Check if key exists
if "Name" in my_dict:
print("Key 'Name' exists")
# 10. Length of dictionary
print("Length of dictionary:", len(my_dict))
# 11. Copy dictionary
new_dict = my_dict.copy()
print("Copied dictionary:", new_dict)
# 12. Clear dictionary
my_dict.clear()
print("After clear:", my_dict)
# 13. Create dictionary using fromkeys()
keys = ["a", "b", "c"]
value = 0
dict_from_keys = [Link](keys, value)
print("Dictionary from keys:", dict_from_keys)
# 14. Nested dictionary
student = {
"ID": 101,
"Name": "Anuja",
"Marks": {
"Math": 85,
"Science": 90
}
}
print("Nested Dictionary:", student)
# 15. Iterate through dictionary
print("Iterating dictionary:")
for key, value in [Link]():
print(key, ":", value)
Output
Initial Dictionary: {'Name': 'Anuja', 'Age': 20, 'Course': 'Python'}
Name: Anuja
After adding City: {'Name': 'Anuja', 'Age': 20, 'Course': 'Python', 'City': 'Hyderabad'}
After updating Age: {'Name': 'Anuja', 'Age': 21, 'Course': 'Python', 'City': 'Hyderabad'}
Removed Course: Python
After pop: {'Name': 'Anuja', 'Age': 21, 'City': 'Hyderabad'}
Popped item: ('City', 'Hyderabad')
After popitem: {'Name': 'Anuja', 'Age': 21}
Keys: dict_keys(['Name', 'Age'])
Values: dict_values(['Anuja', 21])
Items: dict_items([('Name', 'Anuja'), ('Age', 21)])
Key 'Name' exists
Length of dictionary: 2
Copied dictionary: {'Name': 'Anuja', 'Age': 21}
After clear: {}
Dictionary from keys: {'a': 0, 'b': 0, 'c': 0}
Nested Dictionary: {'ID': 101, 'Name': 'Anuja', 'Marks': {'Math': 85, 'Science': 90}}
Iterating dictionary:
ID : 101
Name : Anuja
Marks : {'Math': 85, 'Science': 90}
Result
Thus the python program to perform dicitonary operations has been written and executed
successfully.
String and Files
Aim: Write a python program using string and files
Python program using string and files
Program :
[Link]
[Link] a file in read mode
[Link] counters:
lines = 0
words = 0
characters = 0
[Link] the file line by line
[Link] each line:
Increment line count
Split the line into words and count them
Count characters in the line
[Link] the total number of lines, words, and characters
[Link]
Program:
# Open file
file = open("[Link]", "r")
lines = 0
words = 0
characters = 0
# Read file line by line
for line in file:
lines += 1
words += len([Link]())
characters += len(line)
# Close file
[Link]()
# Display results
print("Number of lines:", lines)
print("Number of words:", words)
print("Number of characters:", characters)
Sample Input File ([Link])
Hello world
Python is easy
File handling in Python
Output
Number of lines: 3
Number of words: 8
Number of characters: 49
Result:
Thus the above program has been executed successfully
Exp: 4.
Write a program to demonstrate a) arrays b) array indexing such as slicing, integer array
indexing
and Boolean array indexing along with their basic operations in NumPy.
A)ARRAYS
SOURCE CODE:
import numpy as np
a = [Link](42)
b = [Link]([1, 2, 3, 4, 5])
c = [Link]([[1, 2, 3], [4, 5, 6]])
d = [Link]([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print("entered array is:",a,"and its dimension is:",[Link])
print("entered array is:",b,"and its dimension is:",[Link])
print("entered array is:",c,"and its dimension is:",[Link])
print("entered array is:",d,"and its dimension is:",[Link])
OUTPUT:
entered array is: 42 and its dimension is: 0
entered array is: [1 2 3 4 5] and its dimension is: 1
entered array is: [[1 2 3]
[4 5 6]] and its dimension is: 2
entered array is: [[[1 2 3]
[4 5 6]]
[[1 2 3]
[4 5 6]]] and its dimension is: 3
RESULT: Thus the above program has been executed successfully
B)array indexing such as slicing, integer array indexing and Boolean array indexing along
with their basic operations in NumPy.
SOURCE CODE:
import numpy as np
a=[Link](10,1,-2)
print("a sequential array with nagative step value:",a)
newarr=[a[3],a[1],a[2]]
print("elements at these indices are:",newarr)
a=[Link](20)
print("Array is:",a)
print("a[-8:17:1]=",a[-8:17:1])
print("a[10:]=",a[10:])
OUTPUT:
a sequential array with nagative step value: [10 8 6 4 2]
elements at these indices are: [4, 8, 6]
Array is: [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
a[-8:17:1]= [12 13 14 15 16]
a[10:]= [10 11 12 13 14 15 16 17 18 19]
RESULT: The above program has been executed successfully
Exp: 6 Line, bar, histogram and bar plot using python
Aim:
Write a program to draw a Line, bar, histogram and bar plot using python
Algorithm:
[Link]
[Link] matplotlib library
[Link] data for plotting
[Link] a figure using figure()
[Link] the figure into 4 subplots using subplo()
[Link]:
Line plot using plot()
Bar chart using bar()
Histogram using hist()
Box plot using boxplot()
[Link] titles and labels for each plot
[Link] layout using tight_layout()
[Link] all plots using show()
[Link]
Program
import [Link] as plt
# Data
x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 25, 30]
categories = ['A', 'B', 'C', 'D']
values = [5, 7, 3, 8]
data = [10, 20, 20, 30, 30, 30, 40, 50]
# Create figure
[Link](figsize=(10, 8))
# 1. Line Plot
[Link](2, 2, 1)
[Link](x, y, marker='o')
[Link]("Line Plot")
[Link]("X-axis")
[Link]("Y-axis")
# 2. Bar Chart
[Link](2, 2, 2)
[Link](categories, values)
[Link]("Bar Chart")
[Link]("Categories")
[Link]("Values")
# 3. Histogram
[Link](2, 2, 3)
[Link](data, bins=5)
[Link]("Histogram")
[Link]("Value")
[Link]("Frequency")
# 4. Box Plot
[Link](2, 2, 4)
[Link](data)
[Link]("Box Plot")
# Adjust layout
plt.tight_layout()
# Show all plots
[Link]()
OUTPUT:
Line Plot:
Bar Plot:
Histogram Plot:
Box Plot:
Result:
Thus the program to draw a Line, bar, histogram and bar plot using python has been executed and verified
successfully.