0% found this document useful (0 votes)
14 views31 pages

CP Assignment-5

assignmenmt 5 of computer programming

Uploaded by

aakash411883
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)
14 views31 pages

CP Assignment-5

assignmenmt 5 of computer programming

Uploaded by

aakash411883
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/ 31

NAME – HARDIK SAINI

ROLL NUMBER – 2024UIT3147

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?

Ans1) In Python, some of the important data types include:


• Integers: Whole numbers, e.g., 5, -3
• Floats: Decimal numbers, e.g., 3.14, -0.001
• Strings: Text, e.g., "Hello, World!"
• Booleans: True or False values, e.g., True, False
• Lists: Ordered collections of items, e.g., [1, 2, 3]
• Tuples: Ordered, immutable collections of items, e.g., (1, 2, 3)
• Dictionaries: Key-value pairs, e.g., {"name": "Alice", "age": 25}
• Sets: Unordered collections of unique items, e.g., {1, 2, 3}

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.

3)Write a Python expression to calculate the remainder when dividing 10 by 3.


Ans3) remainder = 10 % 3
print(remainder) # Output will be 1
4)Write a Python expression that checks whether the marks entered by the user belongs to
first division or 2nd division or 3rd division or fail using if-else.

Ans4) # Get marks from the user


marks = int(input("Enter your marks: "))

# Check the division based on marks


if marks >= 60:
print("First Division")

elif marks >= 50:


print("Second Division")
elif marks >= 40:

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.

Ans5) Main Difference Between Lists and Tuples in Python


• Mutability: The primary difference between lists and tuples is that lists are mutable,
meaning you can change their content (add, remove, or modify elements) after they
are created. Tuples, on the other hand, are immutable, meaning once they are created,
their content cannot be changed.
• Syntax: Lists are defined using square brackets [], while tuples are defined using
parentheses ().
• Performance: Tuples can be more efficient in terms of performance because they are
immutable and thus can be optimized by the Python interpreter.
Concept of a Set in Python
A set is an unordered collection of unique elements. Sets are defined using curly braces {} or
the set() function. They are useful when you need to store a collection of items and ensure
that there are no duplicates.
When to Use a Set Instead of a List or Tuple
You might use a set instead of a list or tuple when you need to:
• Ensure Uniqueness: If you need to store a collection of items and ensure that there
are no duplicates, a set is the best choice.
• Perform Set Operations: Sets support mathematical operations like union,
intersection, and difference, which can be very useful in certain scenarios.

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. Multiple Inheritance: A subclass inherits from more than one superclass


class Father:
def work(self):
print("Father works")
class Mother:
def care(self):
print("Mother cares")
class Child(Father, Mother):
pass

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.

Ans3) Object-Oriented Programming in Python

Object-Oriented Programming (OOP) is a programming paradigm that uses objects and


classes to structure software programs. It allows for the creation of reusable and modular
code by encapsulating data and behavior into objects. The main concepts of OOP include:

• Classes and Objects: A class is a blueprint for creating objects. An object is an


instance of a class.

• Encapsulation: Bundling data (attributes) and methods (functions) that operate on


the data into a single unit (class).
• Inheritance: Creating new classes from existing ones, allowing for code reuse and
the creation of hierarchical relationships.

• Polymorphism: Allowing objects to be treated as instances of their parent class,


enabling the same operation to behave differently on different classes.

• Abstraction: Hiding the complex implementation details and showing only the
necessary features of an object.

Creating a Class Named Person

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:

def __init__(self, name, age):

self.name = name

self.age = age

def display(self):

print(f"Name: {self.name}, Age: {self.age}")

# Creating an instance of the Person class

person1 = Person("Alice", 30)

# Displaying the values

person1.display()

In this example:

• The __init__() function is a special method called a constructor. It is automatically


called when an instance of the class is created. It initializes the object's attributes
(name and age).

• 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.

Ans3) Lambda Functions in Python

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).

Why Use Lambda Functions?

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.

3. Functional Programming: Lambda functions are often used in functional


programming constructs like map(), filter(), and reduce().

# Regular function

def add(x, y):

return x + y

# Lambda function

add_lambda = lambda x, y: x + y

# Using the lambda function

result = add_lambda(5, 3)

print(result) # Output: 8
4) Explain 4 pillars of OOPs in Python .

Ans4) Four Pillars of Object-Oriented Programming (OOP) in Python

1. Encapsulation:

o Definition: Encapsulation is the concept of bundling data (attributes) and


methods (functions) that operate on the data into a single unit, or class. It
restricts direct access to some of the object's components, which can prevent the
accidental modification of data.

2. Inheritance:

• Definition: Inheritance allows a class (child class) to inherit attributes and


methods from another class (parent class). This promotes code reuse and
establishes a hierarchical relationship between classes.

3. Polymorphism:

• Definition: Polymorphism allows objects of different classes to be treated as


objects of a common superclass. It enables a single interface to represent
different underlying forms (data types).

4. Abstraction:

• Definition: Abstraction is the concept of hiding the complex implementation


details and showing only the necessary features of an object. It helps in reducing
programming complexity and effort.

5) Explain the significance of ‘super’ keyword in inheritance.


The super keyword in Python is used to call a method from a parent class within a child
class. It is particularly useful in inheritance for the following reasons:
1. Access Parent Class Methods: It allows you to call methods from the parent class,
which is essential when you want to extend or modify the behavior of the parent class
methods in the child class.
2. Avoid Code Duplication: By using super(), you can avoid duplicating code that is
already present in the parent class. This promotes code reuse and makes your code
more maintainable.
UNIT 3

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

# Creating three 1-dimensional arrays of different sizes

array1 = np.array([1, 2, 3, 4, 5])

array2 = np.array([10, 20, 30, 40])

array3 = np.array([100, 200, 300, 400, 500, 600])

# Finding the sum of the 3rd and 4th elements of all three arrays

sum_elements = array1[2] + array1[3] + array2[2] + array2[3] + array3[2] + array3[3]

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?

Ans3) Indexing in NumPy Arrays

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.

Extracting the Third Element from a NumPy Array

import numpy as np

# Example NumPy array

arr = np.array([10, 20, 30, 40, 50])

# Extracting the third element

third_element = arr[2]

print(third_element) # Output: 30

4) Explain the difference between indexing and slicing in the context of NumPy arrays.

Ans4) Indexing vs. Slicing in 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

• Purpose: Indexing is used to access a single element in an array.

• Syntax: You use square brackets [] with the index of the element you want to access.

Slicing

• Purpose: Slicing is used to access a range of elements in an array.

• Syntax: You use the colon : operator within square brackets to specify the start, stop,
and step of the slice.
Key Differences

1. Access Type:

o Indexing: Accesses a single element.

o Slicing: Accesses a range of elements.

2. Syntax:

o Indexing: Uses a single index, e.g., arr[2].

o Slicing: Uses a start, stop, and optional step, e.g., arr[1:4:2].

3. Output:

o Indexing: Returns a single element.

o Slicing: Returns a sub-array.

4. Mutability:

o Indexing: Can be used to modify a single element.

5) Consider the following NumPy array:

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]

Ans5) import numpy as np


data = np.array([[1, 2, 3],[4, 5, 6],[7, 8, 9]])
# Accessing the element at the second row and third column
element = data[1, 2]
print(element) # Output: 6
6) What is a Pandas DataFrame and how does Pandas facilitate data analysis in Python, give
4 basic operations.
Ans6) Pandas DataFrame
A Pandas DataFrame is a two-dimensional, size-mutable, and potentially heterogeneous
tabular data structure with labeled axes (rows and columns). It is similar to a table in a
database or an Excel spreadsheet. DataFrames are one of the most commonly used data
structures in the Pandas library, which is a powerful tool for data manipulation and analysis
in Python.
How Pandas Facilitates Data Analysis
Pandas provides a wide range of functionalities that make data analysis easier and more
efficient:
1. Data Cleaning: Pandas offers tools to handle missing data, remove duplicates, and
perform data transformations, making it easier to clean and prepare data for analysis.
2. Data Manipulation: With Pandas, you can easily filter, sort, and group data. It also
supports merging and joining datasets, which is essential for combining data from
different sources.

7) Create a dataframe to store details of a product like name, product id, company along with
their values.

Ans7)

import pandas as pd

# Creating a dictionary with product details

product_data = {'Name': ['Product A', 'Product B', 'Product C'],'Product ID': [101, 102, 103],
'Company': ['Company X', 'Company Y', 'Company Z']}

# Creating a DataFrame from the dictionary

product_df = pd.DataFrame(product_data)

# Displaying the DataFrame

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.

Ans1) Types of Files


1. Text Files: These files contain plain text and can be opened and read using text
editors. Examples include .txt files.
# Opening a text file in read mode
with open('example.txt', 'r') as file:
content = file.read()
print(content)
# Opening a text file in write mode
with open('example.txt', 'w') as file:
file.write("Hello, World!")
2. Binary Files: These files contain binary data and are not human-readable. Examples
include images, videos, and executable files.
# Opening a binary file in read mode
with open('example.bin', 'rb') as file:
content = file.read()
print(content)
# Opening a binary file in write mode
with open('example.bin', 'wb') as file:
file.write(b'\x00\x01\x02\x03')

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.

Ans2) Exceptions in Python


Exceptions are events that occur during the execution of a program that disrupt the normal
flow of the program's instructions. In Python, exceptions are used to handle errors gracefully
and ensure that the program can continue running or terminate cleanly. When an error occurs,
Python generates an exception that can be caught and handled using specific constructs.
Handling Errors with Exceptions
To handle errors in Python, you use the try and except statements. These statements allow
you to catch and handle exceptions, preventing the program from crashing and providing a
way to manage errors effectively.
Purpose of try and except Statements
• try Block: The code that might raise an exception is placed inside the try block. If an
exception occurs, the rest of the code in the try block is skipped.
• except Block: The code inside the except block is executed if an exception occurs in
the try block. You can specify the type of exception to catch and handle specific
errors.

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)

Writing Data to Files


• Purpose: Writing data to a file allows you to create a new file or overwrite an
existing file with new content.
• Mode: 'w' (write mode)
• Usage: Use this mode when you need to create a new file or replace the contents of
an existing file.
• Example:
python
with open('example.txt', 'w') as file:
file.write("Hello, World!")

Appending Data to Files


• Purpose: Appending data to a file allows you to add new content to the end of an
existing file without modifying the existing content.
• Mode: 'a' (append mode)
• Usage: Use this mode when you need to add new data to an existing file without
overwriting its current contents.
• Example:
python
with open('example.txt', 'a') as file:
file.write("\nThis is an additional line.")

When to Use Each Operation


• Reading: Use reading when you need to access and process the contents of a file
without making any changes to it. For example, reading a configuration file or
processing a text document.
• Writing: Use writing when you need to create a new file or completely replace the
contents of an existing file. For example, generating a report or saving user input to a
file.
• Appending: Use appending when you need to add new data to an existing file
without altering its current contents. For example, logging events to a log file or
adding new entries to a data file.

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):

# Create an empty dictionary to store word counts

word_counts = {}

# Split the text into words

words = text.split()

# Count the occurrences of each word

for word in words:

word = word.lower().strip('.,!?;:"()[]{}') # Normalize the word

if word in word_counts:

word_counts[word] += 1

else:

word_counts[word] = 1

# Print the word counts

for word, count in word_counts.items():

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

1)Write short notes on:

a)Input tag and its types


b)Submit button
c)Action attribute
d)Method attribute
Ans1)
Input Tag and Its Types
The <input> tag in HTML is used to create interactive controls in web forms that allow users
to input data. It is a versatile tag with various types that define the kind of data the user can
enter. Here are some common types of <input> tags:
• Text: <input type="text"> - Creates a single-line text input field.
• Password: <input type="password"> - Creates a password input field where the
characters are masked.
• Email: <input type="email"> - Creates an input field for email addresses, with
validation for proper email format.
• Number: <input type="number"> - Creates an input field for numeric values, with
optional min and max attributes.
• Date: <input type="date"> - Creates an input field for selecting a date.
• Checkbox: <input type="checkbox"> - Creates a checkbox that can be checked or
unchecked.
• Radio: <input type="radio"> - Creates a radio button, allowing the user to select one
option from a group.
• File: <input type="file"> - Creates a file upload control.
b) Submit Button
The <input type="submit"> tag creates a submit button in a web form. When the user clicks
the submit button, the form data is sent to the server for processing. The submit button is
essential for submitting the form data to the specified action URL.
Example:
html
<form action="/submit_form" method="post">
<input type="text" name="username" placeholder="Enter your username">
<input type="submit" value="Submit">
</form>
c) Action Attribute
The action attribute in an HTML form specifies the URL to which the form data should be
sent when the form is submitted. It defines the endpoint on the server that will handle the
form data.
Example:
html
<form action="/submit_form" method="post">
<input type="text" name="username" placeholder="Enter your username">
<input type="submit" value="Submit">
</form>
In this example, the form data will be sent to /submit_form when the user clicks the submit
button.
d) Method Attribute
The method attribute in an HTML form specifies the HTTP method to be used when
submitting the form data. The two most common methods are:
• GET: Sends the form data as URL parameters. It is suitable for retrieving data and
should not be used for sensitive information.
• POST: Sends the form data in the body of the HTTP request. It is suitable for
submitting sensitive information and for actions that modify data on the server.
Example:
html
<form action="/submit_form" method="post">
<input type="text" name="username" placeholder="Enter your username">
<input type="submit" value="Submit">
</form>
In this example, the form data will be sent using the POST method.
These attributes and tags are fundamental for creating and handling web forms, enabling user
interaction and data submission to the server.
2)Create a html form for course registration of students by taking appropriate fields. On
pressing the submit button, the output should display the courses for which students has
registered. Write backend flask script for this.

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">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Course Registration</title>

</head>

<body>

<h1>Course Registration Form</h1>

<form action="/register" method="post">

<label for="name">Name:</label>

<input type="text" id="name" name="name" required><br><br>

<label for="student_id">Student ID:</label>

<input type="text" id="student_id" name="student_id" required><br><br>

<label for="courses">Courses:</label><br>

<input type="checkbox" id="course1" name="courses" value="Mathematics">

<label for="course1">Mathematics</label><br>

<input type="checkbox" id="course2" name="courses" value="Physics">

<label for="course2">Physics</label><br>
<input type="checkbox" id="course3" name="courses" value="Chemistry">

<label for="course3">Chemistry</label><br>

<input type="checkbox" id="course4" name="courses" value="Biology">

<label for="course4">Biology</label><br><br>

<input type="submit" value="Register">

</form>

</body>

</html>

Flask Backend Script

python

from flask import Flask, request, render_template_string

app = Flask(__name__)

@app.route('/')

def index():

return render_template_string('''

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Course Registration</title>

</head>

<body>
<h1>Course Registration Form</h1>

<form action="/register" method="post">

<label for="name">Name:</label>

<input type="text" id="name" name="name" required><br><br>

<label for="student_id">Student ID:</label>

<input type="text" id="student_id" name="student_id" required><br><br>

<label for="courses">Courses:</label><br>

<input type="checkbox" id="course1" name="courses" value="Mathematics">

<label for="course1">Mathematics</label><br>

<input type="checkbox" id="course2" name="courses" value="Physics">

<label for="course2">Physics</label><br>

<input type="checkbox" id="course3" name="courses" value="Chemistry">

<label for="course3">Chemistry</label><br>

<input type="checkbox" id="course4" name="courses" value="Biology">

<label for="course4">Biology</label><br><br>

<input type="submit" value="Register">

</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">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Registration Confirmation</title>

</head>

<body>

<h1>Registration Confirmation</h1>

<p>Name: {{ name }}</p>

<p>Student ID: {{ student_id }}</p>

<p>Registered Courses:</p>

<ul>

{% for course in courses %}

<li>{{ course }}</li>

{% endfor %}

</ul>

</body>

</html>

''', name=name, student_id=student_id, courses=courses)

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.

2. Flask Backend Script:

o The index route renders the HTML form.


o The register route handles the form submission, retrieves the form data, and
displays the registered courses.

o The render_template_string function is used to render HTML templates


directly from strings.

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.

3)WAP to create a histogram for the following data:

Age intervals No. of people having diabetes


20-30 10
30-40 22
40-50 64
50-60 70

Ans3)
import matplotlib.pyplot as plt

# Data
age_intervals = ['20-30', '30-40', '40-50', '50-60']
no_of_people = [10, 22, 64, 70]

# Creating the histogram


plt.bar(age_intervals, no_of_people, color='blue')

# Adding titles and labels


plt.title('Number of People Having Diabetes by Age Interval')
plt.xlabel('Age Intervals')
plt.ylabel('Number of People')

# Displaying the histogram


plt.show()
4)Explain the process of URL routing using Get and Post methods.

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)

Advantages of Matplotlib Library

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.

2. Customization: It offers extensive customization options for plots, including control


over colors, labels, line styles, and more. This allows you to create highly customized
and publication-quality visualizations.

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.

4. Interactivity: It supports interactive plots that can be embedded in Jupyter notebooks


and other interactive environments. This is useful for exploratory data analysis and
presentations.

5. Community and Documentation: Matplotlib has a large and active community,


along with comprehensive documentation and numerous tutorials. This makes it
easier to learn and troubleshoot issues.
6)What is Flask? Why it is used?

Ans6) Flask: A Lightweight Web Framework

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.

Why Flask is Used

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.

5. RESTful Request Dispatching: Flask supports RESTful request dispatching, making


it easy to build APIs and handle different HTTP methods (GET, POST, PUT,
DELETE).

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

Here's a basic example of a Flask application:

python

from flask import Flask

app = Flask(__name__)

@app.route('/')

def home():

return 'Hello, Flask!'

if __name__ == '__main__':

app.run(debug=True)

In this example:

• We import the Flask class and create an instance of it.

• 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.

You might also like