Python assignment
Q)Develop a Python program to demonstrate creation of own module.
Create a calculation module and use it inside another program.
A user-defined module is a Python file created by the programmer to store
functions, classes or variables.
It helps to reuse code, makes the program easy to maintain and avoids
repeating the same [Link] to create and use own module
1. Create a module file
Create a file named [Link] and write required functions in it.
[Link]
# User defined module
def add(a, b):
return a + b
def sub(a, b):
return a - b
def mul(a, b):
return a * b
def div(a, b):
return a / b
2. Create another program and import the module
Create a file named [Link]
# importing user defined module
import calculation
a = 20
b = 10
print("Addition =", [Link](a, b))
print("Subtraction =", [Link](a, b))
print("Multiplication =", [Link](a, b))
print("Division =", [Link](a, b))
Output:
Addition = 30
Subtraction = 10
Multiplication = 200
Division = 2.0
Q)Differentiate between lists and NumPy arrays.
A List is a built-in Python data structure used to store multiple values.
A NumPy array is provided by the NumPy library and is mainly used for
numerical calculations and handling large data efficiently.
Q)Explain Creating NumPy arrays, shape, slicing with examples.
NumPy is a Python library used for numerical calculations.
It provides an array object which stores elements efficiently and supports
mathematical operations.
1) Creating NumPy arrays
A NumPy array is created using [Link]().
Syntax
import numpy as np
a = [Link]([elements])
Example -1D array
import numpy as np
a = [Link]([10, 20, 30, 40])
print(a)
output:
[10 20 30 40]
Example – 2D array
import numpy as np
b = [Link]([[1, 2, 3],
[4, 5, 6]])
print(b)
output:
[[1 2 3]
[4 5 6]]
2) Shape of NumPy array
In NumPy, shape represents the number of rows and columns (dimensions)
of an [Link] shape of an array is obtained using the .shape attribute.
Syntax: array_name.shape
Example:1D array
import numpy as np
a = [Link]([10, 20, 30, 40])
print([Link])
output: (4,)
• The array has 4 elements. Therefore, shape is (4,)
Example: 2D array
import numpy as np
b = [Link]([[2, 3, 8], [4, 5, 6]])
print([Link])
Output: (2, 3)
This means the array has 2 rows and 3 columns
3) Slicing in NumPy array
Slicing in NumPy is used to extract a portion of an array. It allows us to
access selected elements from the array.
Syntax:
array[start : stop : step]
which means ,
start → Starting index
stop → Ending index (not included)
step → Increment value
Example1:Slicing in 1D array
For 1D arrays, slicing works exactly like Python lists, where we use index
positions to access elements. Since Python uses zero-based indexing, the
first element is at index 0.
import numpy as np
a = [Link]([10, 20, 30, 40, 50, 60])
print(a[1:5])
output
[20 30 40 50]
explanation:
• Index starts from 1 and ends before 5.
Example 2: Slicing in 2D Array
import numpy as np
a = [Link]([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
print(a[0:2, 1:3])
output:
[[2 3]
[5 6]]
explanation:
• 0:2 → selects first and second rows
• 1:3 → selects second and third columns
Q)Write a program to Create a dictionary to store 5 student names
and age. Print all keys and values.
# Creating dictionary with student name and age
students = {
"Ravi": 18,
"Priya": 19,
"Asha": 20,
"Kiran": 18,
"Deepa": 19
}
# Print all keys
print("Student Names:")
for name in [Link]():
print(name)
# Print all values
print("Student Ages:")
for age in [Link]():
print(age)
Output:
Student Names:
Ravi
Priya
Asha
Kiran
Deepa
Student Ages:
18
19
20
18
19
Q) Compare & Contrast Pure & Modifier Function with respect to
List with suitable programming example.
A function that works on a list can be Pure or Modifier.
• A Pure function creates a new list and does not change the original
list.
• A Modifier function directly changes the original list.
Difference between pure and modifier function
Example of pure function
# Pure function
def double_values(lst):
new_list = []
for x in lst:
new_list.append(x * 2)
return new_list
a = [1, 2, 3]
b = double_values(a)
print("Original list:", a)
print("New list:", b)
Output:
Original list: [1, 2, 3]
New list: [2, 4, 6]
Here the original list is not changed.
Example of Modifier Function
# Modifier function
a = [10, 20, 30]
[Link](40)
print(a)
output:
[10, 20, 30, 40]
Here append() changes the original list directly.
LAB Program
Program-3a: Read N numbers from the console and create a list.
Develop a program to print mean, variance and standard deviation
with suitable messages.
Program:
import math
# Read number of elements
n = int(input("Enter number of elements: "))
numbers = []
# Read elements
for i in range(n):
num = float(input(f"Enter number {i+1}: "))
[Link](num)
# Calculate Mean
mean = sum(numbers) / n
# Calculate Variance
variance = sum((x - mean) ** 2 for x in numbers) / n
# Calculate Standard Deviation
std_dev = [Link](variance)
# Display results
print("\nNumbers:", numbers)
print("Mean =", mean)
print("Variance =", variance)
print("Standard Deviation =", std_dev)
Sample Output:
Run-1
Enter number of elements: 5
Enter number 1: 2
Enter number 2: 4
Enter number 3: 6
Enter number 4: 8
Enter number 5: 10
Numbers: [2.0, 4.0, 6.0, 8.0, 10.0]
Mean = 6.0
Variance = 8.0
Standard Deviation = 2.8284271247461903
Program-3b: Read a multi-digit number (as chars) from the console.
Develop a program to print the frequency of each digit with suitable
message.
Program:
# Read multi-digit number as characters
num = input("Enter a multi-digit number: ")
freq = {}
# Count frequency of each digit
for digit in num:
if digit in freq:
freq[digit] += 1
else:
freq[digit] = 1
# Display result
print("\nDigit Frequency:")
for digit in freq:
print(f"Digit {digit} appears {freq[digit]} time(s)")
Sample output:
Run-1
Enter a multi-digit number: 12234521
Digit Frequency:
Digit 1 appears 2 time(s)
Digit 2 appears 3 time(s)
Digit 3 appears 1 time(s)
Digit 4 appears 1 time(s)
Digit 5 appears 1 time(s)
4. A math app needs to determine the type of roots for a quadratic
equation based on user input. Develop a C program to calculate and
display the roots based on the given coefficients
Program:
import string
# Open and read file
file = open("[Link]", "r")
text = [Link]().lower()
[Link]()
# Remove punctuation
for char in [Link]:
text = [Link](char, "")
# Split into words
words = [Link]()
# Count frequency
freq = {}
for word in words:
if word in freq:
freq[word] += 1
else:
freq[word] = 1
# Sort by frequency (descending)
sorted_freq = sorted([Link](), key=lambda x: x[1], reverse=True)
# Display top 10 words
print("Top 10 Most Frequent Words:\n")
for word, count in sorted_freq[:10]:
print(word, "→", count)
Sample Output:
Run-1
Top 10 Most Frequent Words:
python → 4
is → 3
learning → 1
great → 1
easy → 1
to → 1
learn → 1
fun → 1
and → 1
powerful → 1
5. Develop a program to read 6 subject marks from the keyboard for a
student. Generate a report that displays the marks from the highest to
the lowest score attained by the student.
[Read the marks into a 1-Dimensional array and sort using the Bubble
Sort technique].
Program:
marks = []
# Read 6 subject marks
print("Enter marks of 6 subjects:")
for i in range(6):
m = float(input(f"Enter mark {i+1}: "))
[Link](m)
# Bubble Sort (Descending Order)
n = len(marks)
for i in range(n):
for j in range(0, n-i-1):
if marks[j] < marks[j+1]:
marks[j], marks[j+1] = marks[j+1], marks[j]
# Display sorted marks
print("\nMarks from Highest to Lowest:")
for mark in marks:
print(mark)
Sample Run
Run-1
Enter marks of 6 subjects:
Enter mark 1: 78
Enter mark 2: 85
Enter mark 3: 92
Enter mark 4: 67
Enter mark 5: 88
Enter mark 6: 74
Marks from Highest to Lowest:
92.0
88.0
85.0
78.0
74.0
67.0
Program 6: Develop a program to sort the contents of a text file and
write the sorted contents into a separate text file.
[Hint: Use string methods strip(), len(), list methods sort(), append(),
and file methods open(), readlines(), and write()]..
Program:
# Open input file
infile = open("[Link]", "r")
lines = [Link]()
[Link]()
clean_lines = []
# Remove extra spaces using strip()
for line in lines:
clean_line = [Link]()
clean_lines.append(clean_line)
# Sort lines
clean_lines.sort()
# Open output file
outfile = open("[Link]", "w")
# Write sorted lines
for line in clean_lines:
[Link](line + "\n")
[Link]()
print("File sorted successfully! Check '[Link]'")
Example Input File ([Link])
Banana
Apple
Mango
Grapes
Orange
Output File ([Link])
Apple
Banana
Grapes
Mango
Orange
Q) Explain the following dictionery operations with examples(Model
paper)
i) Creating Phone directory with three items
ii) Delete an item from dictionary
iii) Update the dictionary
iv)Add new item to dictionary
v) Access an element from the dictionary
i. Creating a Dictionary
A dictionary is created by placing key–value pairs inside { }, where each
key is followed by its value using a colon :.
Example:
phone_directory = {
"Rahul": "9876543210",
"Sneha": "9123456780",
"Arjun": "9988776655"
}
Output: {‘Rahul’: 9876543210,‘Sneha’: 9123456780,
‘Arjun’: 9988776655}
This creates a dictionary where names are keys and phone numbers are
values.
ii. Deleting an Item using del
The del statement removes a key and its value completely from the
dictionary.
Example
del phone_directory["Arjun"]
print(phone_directory)
Output:
After Deleting Arjun:
{‘Rahul’: 9876543210,‘Sneha’: 9123456780}
iii. Update the dictionary
Instead of deleting, you can change the value of an existing key.
Example:
phone_directory["Sneha"] = "9000011111"
print(phone_directory)
Output:
After Updating Sneha's Number:
{'Rahul': '9876543210', 'Sneha': '9000011111'}
[Link] a new item to the dictionery
#Adding a new contact
phone_directory["Kiran"] = "9012345678"
print(phone_directory)
output:
After Adding Kiran:
{'Rahul': '9876543210', 'Sneha': '9000011111',Kiran': '9012345678'}
v. Access an element from the dictionery
# Accessing a phone number
print("\nRahul's Number:", phone_directory["Rahul"])
output:
Rahul's Number: 9876543210
Q) Explain the different dictionery methods
i. keys() method
The keys() method is used to get all the keys from a dictionary. It does not
return a list directly, but a special object called a view, which can be
converted into a list if needed. This method is useful when you want to
access or work only with the keys of the dictionary.
Example:
inventory= {"apples": 430, "bananas": 312, "oranges": 525, "pears": 217}
print([Link]()) # dict_keys(['apples', 'bananas', 'oranges', 'pears'])
print(list([Link]())) #['apples', 'bananas', 'oranges', 'pears']
ii)values() method
The values() method returns all the values stored in the dictionary. Like
keys(), it returns a view object. It is helpful when we are interested only in
the values and not the keys.
Example:
inventory= {"apples": 430, "bananas": 312, "oranges": 525, "pears": 217}
values = list([Link]())
print(values)
Output:
[430, 312, 525, 217]
iii) items() method
The items() method returns both keys and values together in the form of
tuples. Eachelement is a pair consisting of a key and its corresponding
value. This is useful when we need to access both at the same time.
Example:
inventory= {"apples": 430, "bananas": 312, "oranges": 525, "pears": 217}
items = list([Link]())
print(items)
Output:
[('apples', 430), ('bananas', 312), ('oranges', 525), ('pears', 217)]
iv)Iterating over a dictionary
When we use a for loop directly on a dictionary, Python automatically goes
through its keys. That means we don’t always need to use the keys()
method explicitly. This makes iteration simple and efficient when we only
need keys.
Example:
inventory= {"apples": 430, "bananas": 312, "oranges": 525, "pears": 217}
for key in inventory:
print(key)
Output:
apples
bananas
oranges
pears
v) in and not in operators
These operators are used to check whether a key exists in the dictionary or
not. The in operator returns True if the key is present, and not in returns
True if the key is absent. These checks apply only to keys, not values.
Example:
“apples” in inventory # true
“apples” not in inventory # false
Q)What is module in python
A module in Python is a file that contains Python code such as functions,
variables, and classes, which can be reused in other Python programs.
Python comes with many built-in modules as part of its standard library,
which help programmers perform common tasks easily.
Q)Explain the working of random Module in Python with
example
The Python random module is used to generate random numbers and
perform random operations such as selecting random items, shuffling lists,
and generating random values.
Import the module using:
import random
Working of Random Module:
The random module contains several built-in functions that generate
pseudo-random values. Some of the common functions are:
1. random(): It is a built in method in random module .It returns a random
floating-point number between 0.0 and 1.0.
Syntax: [Link]()
Example:
import random
x = [Link]()
print(x)
output: 0.5678
2. randint(a, b): Returns a random integer between a and b (both
included).
Syntax: [Link](a, b)
Example:
import random
x = [Link](1, 10)
print(x)
output: 6
3. randrange() : Returns a random number from the specified range.
Syntax: [Link](start, stop, step)
Example:
import random
x = [Link](1, 20, 2)
print(x)
output: 11
4. choice(): Selects a random element from a list, tuple, or string.
Syntax: [Link](sequence)
Example:
import random
colors = ["Red", "Blue", "Green", "Yellow"]
x = [Link](colors)
print(x)
5. shuffle() :Randomly rearranges the elements of a list.
Syntax: [Link](list_name)
Example:
import random
numbers = [1, 2, 3, 4, 5]
[Link](numbers)
print(numbers)
Output: [4, 1, 5, 2, 3]
Applications of Random Module
1. Used in games for dice and card generation
2. Used in password generation
3. Used in simulations and testing
4. Used in lotteries and random sampling
5. Used in machine learning and data science
Q)Explain different import statement variants with syntax and
example
or
Describe different methods of importing modules in python with
example
Python provides few ways to import modules or names from modules into
the current namespace. Each method affects how names are accessed and
where they are placed.
1. Import the Entire Module (Recommended)
syntax: import module_name
Example:
import math
x = [Link](25)
output: 5
Explanation
• The entire module is imported.
• Functions are accessed using the dot operator
• (module_name.function()).
Advantages
• •Clear and explicit
• •Avoids name conflicts
• •Easy to understand which module a function comes from
• This is the preferred and safest method.
• 2. Importing Specific Functions or Variables
Syntax: from module_name import function_name
Example:
from math import sqrt
print(sqrt(49))
output:7
Advantages
• No need to write module name repeatedly.
• Makes code shorter and simpler.
• Faster access to required functions.
[Link] All Names from a Module
Syntax: from module_name import *
Example:
from math import *
print(sqrt(36))
print(pow(2,3))
output: 6.0
8.0
Advantages
• Easy to use all module functions directly.
• Reduces typing effort.
• Disadvantage
• May create naming conflicts.
Difficult to identify function origin.
[Link] Module with Alias
Syntax: import module_name as alias_name
Example:
import math as m
print([Link](81))
output:9
Advantages:
• Reduces long module names.
• Improves readability.
• Useful for large module names.