CP Assignment-5
CP Assignment-5
COMPUTER PROGRAMMING
ASSIGNMENT - 5
UNIT 1
1) Give names of important data types in Python. What is the correct way to declare and
initialize a variable in Python?
2)Explain the significance of using comments in Python code and provide best practices for
writing effective comments. How do you write a multiline comment in Python?
Ans2) Comments in Python are essential for making your code more understandable and
maintainable. They help you and others understand the purpose and functionality of the code,
making it easier to debug and update in the future.
print("Third Division")
else:
print("Fail")
5)Describe the main difference between lists and tuples in Python. Explain the concept of a
set in Python and provide an example of when you might use a set instead of a list or tuple.
6)Discuss the significance of keys and values in Python dictionaries and provide an example
scenario where dictionaries are useful.
Ans6) Significance of Keys and Values in Python Dictionaries
In Python, dictionaries are collections of key-value pairs. Each key is unique and is used to
access the corresponding value. Here are some key points about the significance of keys and
values in dictionaries:
• Keys: Keys are unique identifiers that are used to access the values in a dictionary.
They must be immutable types, such as strings, numbers, or tuples.
• Values: Values are the data associated with the keys. They can be of any data type
and can be duplicated.
UNIT 2
1) Explain the concept of inheritance and its type in object-oriented programming. Provide a
scenario where inheritance can be effectively utilized to promote code reuse and
extensibility.
Ans1) Concept of Inheritance in Object-Oriented Programming
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a
class (called a child or subclass) to inherit attributes and methods from another class (called a
parent or superclass). This promotes code reuse and helps in creating a hierarchical
relationship between classes.
Types of Inheritance
1. Single Inheritance: A subclass inherits from one superclass.
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def bark(self):
print("Dog barks")
2) What is Object-Oriented Programming in Python? Create a class named Person, use the
_init_() function to assign values for name and age. Create a display function to dislay the
values.
• Abstraction: Hiding the complex implementation details and showing only the
necessary features of an object.
Here's how you can create a class named Person in Python, use the __init__() function to
assign values for name and age, and create a display function to display the values:
python
class Person:
self.name = name
self.age = age
def display(self):
person1.display()
In this example:
• The display() function is a method that prints the values of the name and age
attributes.
• An instance of the Person class is created with the name "Alice" and age 30, and the
display() method is called to print these values.
3) What is a Lambda Function ? Why there are used ? Give example also.
A lambda function in Python is a small, anonymous function defined using the lambda
keyword. Unlike regular functions defined using the def keyword, lambda functions are
typically used for short, simple operations and are often used as arguments to higher-order
functions (functions that take other functions as arguments).
1. Conciseness: Lambda functions allow you to write small functions in a single line of
code, making your code more concise.
2. Readability: They can make your code more readable when used appropriately,
especially in cases where a simple function is needed temporarily.
# Regular function
return x + y
# Lambda function
add_lambda = lambda x, y: x + y
result = add_lambda(5, 3)
print(result) # Output: 8
4) Explain 4 pillars of OOPs in Python .
1. Encapsulation:
2. Inheritance:
3. Polymorphism:
4. Abstraction:
1)Why are NumPy arrays preferred over Python lists for numerical computations? How do
you create a NumPy array containing the numbers 1, 2, 3, and 4?
Ans1) NumPy Arrays are Preferred Over Python Lists for Numerical Computations :-
1. Performance: NumPy arrays are more efficient than Python lists for numerical
computations because they are implemented in C and optimized for performance.
They use contiguous memory blocks, which allows for faster access and manipulation
of data.
2. Memory Efficiency: NumPy arrays consume less memory compared to Python lists.
This is because NumPy arrays store elements of the same data type, whereas Python
lists can store elements of different data types, leading to additional overhead.
To create a NumPy array containing the numbers 1, 2, 3, and 4, you can use the
numpy.array() function.
import numpy as np
array = np.array([1, 2, 3, 4])
print(array)
2) Create 3 arrays of 1-dimension of different sizes. Find sum of the 3rd and 4th elements of
all the 3 arrays together.
Ans2)
import numpy as np
# Finding the sum of the 3rd and 4th elements of all three arrays
print("Sum of the 3rd and 4th elements of all three arrays:", sum_elements)
3) How does indexing work in NumPy arrays? How do you extract the third element from a
NumPy array named arr?
Indexing in NumPy arrays works similarly to indexing in Python lists. It allows you to access
individual elements or a range of elements within an array. NumPy arrays are zero-indexed,
meaning the first element is at index 0, the second element is at index 1, and so on.
import numpy as np
third_element = arr[2]
print(third_element) # Output: 30
4) Explain the difference between indexing and slicing in the context of NumPy arrays.
Indexing and slicing are two fundamental techniques for accessing elements in NumPy
arrays, but they serve different purposes and have distinct behaviors.
Indexing
• Syntax: You use square brackets [] with the index of the element you want to access.
Slicing
• Syntax: You use the colon : operator within square brackets to specify the start, stop,
and step of the slice.
Key Differences
1. Access Type:
2. Syntax:
3. Output:
4. Mutability:
import numpy as np
data = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
How would you access the element at the second row and third column of the array data
using indexing?
Answer: data[1, 2]
7) Create a dataframe to store details of a product like name, product id, company along with
their values.
Ans7)
import pandas as pd
product_data = {'Name': ['Product A', 'Product B', 'Product C'],'Product ID': [101, 102, 103],
'Company': ['Company X', 'Company Y', 'Company Z']}
product_df = pd.DataFrame(product_data)
print(product_df)
8)Write a Python program to find all words starting with 'a' or 'e' in the given string.
Ans8)
import re
def ae(text):
# Use regular expression to find words starting with 'a' or 'e'
words = re.findall(r'\b[a|e]\w*', text, re.IGNORECASE)
return words
# Example string
text = "An apple a day keeps everyone engaged and energetic."
# Find words starting with 'a' or 'e'
words = ae(text)
print("Words starting with 'a' or 'e':", words)
UNIT 4
1) What are the different types of files and how they can be opened in python.
3. CSV Files: These files contain comma-separated values and are often used to store
tabular data.
import csv
# Opening a CSV file in read mode
with open('example.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
# Opening a CSV file in write mode
with open('example.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Name', 'Age', 'City'])
writer.writerow(['Alice', 30, 'New York'])
2) What are exceptions in Python, and how are they used to handle errors in code? Explain
the purpose of the 'try' and 'except' statements in exception handling.
try:
# Code that might raise an exception
numerator = int(input("Enter the numerator: "))
denominator = int(input("Enter the denominator: "))
result = numerator / denominator
print(f"The result is {result}")
except ZeroDivisionError:
# Handling division by zero error
print("Error: Division by zero is not allowed.")
except ValueError:
# Handling invalid input error
print("Error: Invalid input. Please enter a valid number.")
except Exception as e:
# Handling any other exceptions
print(f"An unexpected error occurred: {e}")
3) Explain the difference between reading, writing, and appending data to files in Python.
When would you use each operation?
Ans3) Reading, Writing, and Appending Data to Files in Python
In Python, you can perform various operations on files, including reading, writing, and
appending data. Each operation serves a different purpose and is used in different scenarios.
Reading Data from Files
• Purpose: Reading data from a file allows you to access and process the contents of
the file.
• Mode: 'r' (read mode)
• Usage: Use this mode when you need to read the contents of a file without modifying
it.
with open('example.txt', 'r') as file:
content = file.read()
print(content)
4) Explain the significance of the finally clause in exception handling in Python. How does it
differ from the except block, and when would you use it.
Ans4) Significance of the finally Clause in Exception Handling
The finally clause in Python is used in conjunction with try and except blocks to ensure that
certain code is always executed, regardless of whether an exception occurs or not. This is
particularly useful for cleaning up resources, such as closing files or releasing locks, that
need to be handled properly even if an error occurs.
Difference Between finally and except Blocks
• except Block:
o Purpose: The except block is used to catch and handle specific exceptions
that occur in the try block. You can specify different except blocks for
different types of exceptions.
o Execution: The code inside the except block is executed only if an exception
of the specified type occurs in the try block.
o Example:
python
try:
result = 10 / 0
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
• finally Block:
o Purpose: The finally block is used to define cleanup actions that must be
executed under all circumstances, whether an exception is raised or not.
o Execution: The code inside the finally block is always executed after the try
block, regardless of whether an exception was raised or handled.
o Example:
python
try:
file = open('example.txt', 'r')
content = file.read()
except FileNotFoundError:
print("Error: File not found.")
finally:
file.close()
print("File closed.")
When to Use the finally Clause
You would use the finally clause when you need to ensure that certain cleanup actions are
performed, regardless of whether an exception occurs. Common scenarios include:
1. Resource Management: Ensuring that files are closed, network connections are
terminated, or database transactions are committed or rolled back.
2. Releasing Locks: Ensuring that locks are released to avoid deadlocks in multi-
threaded applications.
3. Logging: Ensuring that certain log messages are written, regardless of the outcome of
the try block.
Example Scenario
Here's an example that demonstrates the use of the finally clause for resource management:
python
try:
file = open('example.txt', 'r')
content = file.read()
print(content)
except FileNotFoundError:
print("Error: File not found.")
finally:
file.close()
print("File closed.")
In this example:
• The try block attempts to open and read a file.
• The except block handles the FileNotFoundError if the file does not exist.
• The finally block ensures that the file is closed, regardless of whether an exception
occurred or not.
Using the finally clause helps maintain the integrity of your program by ensuring that
necessary cleanup actions are always performed.
5)Write a Python program that reads a file and counts the occurrences of each word in the
given text. The program should print out the count of each word found.
Input:
sample_text = 'The quick brown fox jumps over the quick red fox.'
Output:
The: 2
Quick: 2
Brown: 1
'fox': 2
'dog': 1
Jumps: 1
Over: 1
Red: 1
Ans5)
def count_word_occurrences(text):
word_counts = {}
words = text.split()
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1
print(f"{word.capitalize()}: {count}")
# Example usage
sample_text = 'The quick brown fox jumps over the quick red fox.'
count_word_occurrences(sample_text)
UNIT 5
Ans2) create a simple HTML form for course registration and a backend Flask script to
handle the form submission and display the registered courses.
HTML Form
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Course Registration</title>
</head>
<body>
<label for="name">Name:</label>
<label for="courses">Courses:</label><br>
<label for="course1">Mathematics</label><br>
<label for="course2">Physics</label><br>
<input type="checkbox" id="course3" name="courses" value="Chemistry">
<label for="course3">Chemistry</label><br>
<label for="course4">Biology</label><br><br>
</form>
</body>
</html>
python
app = Flask(__name__)
@app.route('/')
def index():
return render_template_string('''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Course Registration</title>
</head>
<body>
<h1>Course Registration Form</h1>
<label for="name">Name:</label>
<label for="courses">Courses:</label><br>
<label for="course1">Mathematics</label><br>
<label for="course2">Physics</label><br>
<label for="course3">Chemistry</label><br>
<label for="course4">Biology</label><br><br>
</form>
</body>
</html>
''')
@app.route('/register', methods=['POST'])
def register():
name = request.form['name']
student_id = request.form['student_id']
courses = request.form.getlist('courses')
return render_template_string('''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Registration Confirmation</title>
</head>
<body>
<h1>Registration Confirmation</h1>
<p>Registered Courses:</p>
<ul>
{% endfor %}
</ul>
</body>
</html>
if __name__ == '__main__':
app.run(debug=True)
Explanation
1. HTML Form: The HTML form includes fields for the student's name, student ID,
and checkboxes for selecting courses. The form uses the POST method to submit data
to the /register endpoint.
To run the Flask application, save the backend script as app.py and run it using the command
python app.py. Open your web browser and navigate to http://127.0.0.1:5000/ to access the
course registration form.
Ans3)
import matplotlib.pyplot as plt
# Data
age_intervals = ['20-30', '30-40', '40-50', '50-60']
no_of_people = [10, 22, 64, 70]
Ans4)
URL Routing Using GET and POST Methods
URL routing is a crucial aspect of web development that involves mapping URLs to specific
functions or handlers in a web application. In Python, the Flask framework is commonly used
for this purpose. Flask allows you to define routes and handle HTTP requests using different
methods, such as GET and POST.
GET Method
• Purpose: The GET method is used to request data from a server. It is typically used
to retrieve information without making any changes to the server's state.
• Characteristics:
o Data is sent in the URL as query parameters.
o It is idempotent, meaning multiple identical requests should have the same
effect as a single request.
o It is safe, as it does not modify the server's state.
• Example:
python
from flask import Flask, request
app = Flask(__name__)
@app.route('/greet', methods=['GET'])
def greet():
name = request.args.get('name', 'World')
return f'Hello, {name}!'
if __name__ == '__main__':
app.run(debug=True)
In this example, the /greet route handles GET requests. The name parameter is passed in the
URL as a query parameter, and the server responds with a greeting message.
POST Method
• Purpose: The POST method is used to send data to the server to create or update
resources. It is typically used for form submissions and other actions that modify the
server's state.
• Characteristics:
o Data is sent in the body of the HTTP request.
o It is not idempotent, meaning multiple identical requests can have different
effects.
o It is used for actions that change the server's state.
• Example:
python
from flask import Flask, request
app = Flask(__name__)
@app.route('/submit', methods=['POST'])
def submit():
name = request.form['name']
return f'Thank you, {name}, for your submission!'
if __name__ == '__main__':
app.run(debug=True)
In this example, the /submit route handles POST requests. The name parameter is sent in the
body of the request, typically from a form submission, and the server responds with a thank-
you message.
5)What is the advantage of matplotlib library? Write the inbuilt functions of drawing various
diagrams.
Ans5)
Matplotlib is a widely-used plotting library in Python that provides a flexible and powerful
way to create static, animated, and interactive visualizations. Here are some of the key
advantages of using Matplotlib:
1. Versatility: Matplotlib supports a wide range of plots and charts, including line plots,
bar charts, histograms, scatter plots, and more. This makes it suitable for various
types of data visualization needs.
3. Integration: Matplotlib integrates well with other libraries in the scientific Python
ecosystem, such as NumPy, Pandas, and SciPy. This makes it easy to visualize data
directly from these libraries.
Flask is a micro web framework written in Python. It is designed to be simple, flexible, and
easy to use, making it a popular choice for web developers who want to build web
applications quickly and efficiently. Flask is often referred to as a "micro" framework
because it does not require particular tools or libraries and has no database abstraction layer,
form validation, or other components where pre-existing third-party libraries provide
common functions.
1. Simplicity and Flexibility: Flask provides a simple and flexible core that allows
developers to build web applications with minimal setup. It gives you the freedom to
choose the components you want to use and how you want to structure your
application.
2. Lightweight: Flask is lightweight and has a small footprint, which makes it easy to
learn and use. It does not impose any dependencies beyond what is necessary,
allowing you to keep your application lean.
3. Extensibility: Flask is highly extensible, meaning you can add extensions to handle
various tasks such as database integration, form validation, authentication, and more.
This modularity allows you to build applications that are tailored to your specific
needs.
4. Built-in Development Server: Flask comes with a built-in development server and
debugger, which makes it easy to test and debug your application during
development.
6. Community and Documentation: Flask has a large and active community, along
with comprehensive documentation and numerous tutorials. This makes it easier to
find help and resources when needed.
Example of a Simple Flask Application
python
app = Flask(__name__)
@app.route('/')
def home():
if __name__ == '__main__':
app.run(debug=True)
In this example:
• We define a route for the home page (/) and a function that returns a simple message.
• We run the application in debug mode, which provides helpful error messages and a
built-in debugger.