CP Assignment (1)
CP Assignment (1)
SAMPLE QUESTIONS
UNIT 1
1) Give names of important data types in Python. What is the correct way to
declare and initialize a variable in Python?
To declare and initialize a variable in Python, we simply use the assignment operator
`=`. Here's an example:
# Integer variable
my_int = 10
# Float variable
my_float = 3.14
# String variable
my_string = "Hello, World!"
# Boolean variable
my_bool = True
```
Python is dynamically typed, so you don't need to explicitly declare the type of a
variable. Python infers the type based on the value assigned to it.
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?
Comments in Python are used to add explanations or notes within the code. They are ignored by the
Python interpreter and are only for the benefit of developers reading the code. Comments are
essential for improving code readability, explaining complex logic, and documenting code for future
reference.
In Python, you can create multiline comments using triple quotes (''' or """)
3) Write a Python expression to calculate the remainder when dividing 10 by 3.
remainder = 10 % 3
print(remainder)
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.
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.
The main difference between lists and tuples in Python is that lists are mutable, meaning
you can change their elements after creation, while tuples are immutable, meaning once
they are created, their elements cannot be changed.
Lists:
Mutable: Elements can be added, removed, or modified.
Defined using square brackets [].
Used when you need a collection that can be modified, such as maintaining a list of items
that might change.
Tuples:
Immutable: Elements cannot be changed after creation.
Defined using parentheses ().
Used when you want to ensure that the elements in the collection remain constant, such as
coordinates or settings that should not be modified.
Sets: A set in Python is an unordered collection of unique elements. It is defined using curly
braces {} or the set() constructor. Sets do not allow duplicate elements, so each element in a
set must be unique.
6) Discuss the significance of keys and values in Python dictionaries and provide an
example scenario where dictionaries are useful.
UNIT 2
Consider a scenario where you are developing a software application for a zoo. You have
different types of animals, each with common attributes (e.g., name, age, species) and
behaviors (e.g., eat, sleep, make sound). You can use inheritance to create a base class Animal
with these common attributes and methods. Then, you can create derived classes for specific
types of animals (e.g., Lion, Elephant, Giraffe) that inherit from the Animal class and add
their own unique attributes and behaviors.
Here's an example of defining a `Person` class in Python, where each `Person` object has a
`name` and an `age`:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display(self):
print(f"Name: {self.name}, Age: {self.age}")
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. Lambda functions can have any number of arguments but can only have one
expression. They are often used when you need a simple, short-lived function without the need
to define a full-fledged function using the def keyword.
# Regular function
def add(a, b):
return a + b
1. Encapsulation: Encapsulation is the practice of bundling the data (attributes) and the
methods (functions) that operate on the data into a single unit or class. This concept helps in
data hiding, where the internal state of an object is hidden from the outside world and can only
be accessed through the object's methods.
2. Abstraction: Abstraction is the process of hiding the complex implementation details and
showing only the necessary features of an object. It helps in reducing complexity and
increasing efficiency. In Python, abstraction is achieved by using abstract classes and
interfaces. Abstract classes are classes that cannot be instantiated and are meant to be used as
base classes for other classes.
3. Inheritance: Inheritance is the mechanism where a new class (derived class or subclass) is
created based on an existing class (base class or superclass). The derived class inherits the
attributes and methods of the base class, allowing for code reuse and extensibility. In Python, a
class can inherit from one or more base classes, supporting single, multiple, multilevel, and
hierarchical inheritance.
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?
NumPy arrays are preferred over Python lists for numerical computations due to several
reasons:
Efficient storage and operations: NumPy arrays are stored in contiguous blocks of memory,
which allows for efficient storage and fast element-wise operations. In contrast, Python
lists are stored as individual objects with references, which can be less efficient for
numerical computations.
Vectorized operations: NumPy provides a wide range of mathematical functions that
operate on entire arrays without the need for explicit loops (vectorized operations). This
can lead to significant performance improvements over using loops with Python lists.
Broadcasting: NumPy allows arrays with different shapes to be combined in arithmetic
operations through broadcasting. This makes it easier to perform operations on arrays of
different shapes without having to manually align them.
Memory efficiency: NumPy arrays consume less memory compared to Python lists,
especially for large datasets, due to their efficient storage mechanism.
import numpy as np
print(arr)
2) Create 3 arrays of 1-dimension of different sizes. Find sum of the 3rd and 4th
elements of all the 3 arrays together.
import numpy as np
Slicing:
Slicing refers to extracting a contiguous subsequence (slice) of elements from the array.
When using slicing, you specify a range of indices to extract a subset of elements.
Slicing is done using the colon : operator, with the syntax start:stop:step, where start is the
starting index, stop is the stopping index (exclusive), and step is the step size (default is 1).
Slicing returns a new array containing the specified slice of elements.
import numpy as np
How would you access the element at the second row and third column of the array
data using indexing?
import numpy as np
Answer: data[1, 2]
6) What is a Pandas DataFrame and how does Pandas facilitate data analysis in
Python, give 4 basic operations.
8) Write a Python program to find all words starting with 'a' or 'e' in the given string.
import re
# Given string
text = "apple banana elephant cat dog eagle ant"
# Find all words starting with 'a' or 'e'
words_with_a_or_e = re.findall(r'\b[a|e]\w+', text)
# Print the words
print("Words starting with 'a' or 'e':", words_with_a_or_e)
9) Write a Python program that searches for a word within a string and replaces it
with another word if found. The program should take the original text, the word to
search for, and the word to replace it with as input.
Input:
original_text = 'All hail King George.'
search_word = 'George'
replace_word = 'Louis'
UNIT 4
1) What are the different types of files and how they can be opened in python.
# Reading a text file
with open('file.txt', 'r') as f:
content = f.read()
# Writing to a text file
with open('file.txt', 'w') as f:
f.write('Hello, world!')
# Appending to a text file
with open('file.txt', 'a') as f:
f.write('\nThis is a new line.')
import csv
import json
In Python, exceptions are errors that occur during the execution of a program. They can be
caused by various factors, such as invalid input, missing files, or unexpected conditions.
Exception handling is the process of responding to these exceptions and taking appropriate
actions to handle them gracefully, preventing the program from crashing.
try:
# Code that may raise an exception
x = 10 / 0
except ZeroDivisionError:
# Handle the ZeroDivisionError exception
print("Division by zero!")
except Exception as e:
# Handle other exceptions
print("An error occurred:", e)
3) Explain the difference between reading, writing, and appending data to files in
Python. When would you use each operation?
Reading data from files:
Reading allows you to retrieve data from a file without modifying its contents.
You would use reading when you need to extract information from a file, such as reading
a configuration file, parsing a log file, or processing a dataset.
Reading is done using the 'r' mode in the open() function.
In Python, the finally clause is used in exception handling to define a block of code that will
always be executed, regardless of whether an exception is raised or not. The finally block is
typically used to clean up resources or perform cleanup operations that should be done
regardless of whether an exception occurs.
try:
f = open('file.txt', 'r')
# Perform operations on the file
except FileNotFoundError:
print("File not found.")
finally:
# Close the file, regardless of whether an exception occurred
f.close()
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
def count_words(text):
# Split the text into words
words = text.split()
# Remove punctuation
word = word.strip('.,!?')
return word_counts
# Given text
sample_text = 'The quick brown fox jumps over the quick red fox.'
UNIT 5
1) Write short notes on:
<!DOCTYPE html>
<html>
<head>
<title>Course Registration Form</title>
</head>
<body>
<h2>Course Registration Form</h2>
<form action="/register" method="post">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name" required><br><br>
<label for="email">Email:</label><br>
<input type="email" id="email" name="email" required><br><br>
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/register', methods=['POST'])
def register():
name = request.form.get('name')
email = request.form.get('email')
courses = request.form.getlist('courses')
if __name__ == '__main__':
app.run(debug=True)
# Data
age_intervals = ['20-30', '30-40', '40-50', '50-60']
no_of_people = [10, 22, 64, 70]
# Create histogram
plt.bar(age_intervals, no_of_people, color='skyblue')
plt.xlabel('Age Intervals')
plt.ylabel('Number of People')
plt.title('Histogram of Number of People having Diabetes by Age Intervals')
plt.show()
4) Explain the process of URL routing using Get and Post methods.
URL routing is the process of mapping URLs to specific functionality or resources in a web
application. In web development, URL routing is used to determine which code should handle
a particular request based on the URL path and HTTP method (GET, POST, etc.).
The GET method is used for requests where the client is requesting data from the server.
In URL routing, the path specified in the URL is used to determine the resource or functionality
that the client is requesting.
he POST method is used for requests where the client is submitting data to the server, typically
through a form submission.
In URL routing, the path specified in the URL is still used to determine the resource or
functionality that the client is requesting, but the data submitted by the client is sent separately
as the request body.
5) What is the advantage of matplotlib library? Write the inbuilt functions of drawing
various diagrams.
The matplotlib library is a powerful tool for creating static, animated, and interactive
visualizations in Python. Some of the key advantages of matplotlib include:
Ease of Use: matplotlib is relatively easy to use, especially for creating basic plots and charts.
It has a simple and intuitive API that allows users to quickly generate visualizations with
minimal code.
Customization: matplotlib offers a high level of customization, allowing users to tailor their
plots and charts to suit their specific needs. Users can customize the appearance of plots by
modifying colors, line styles, markers, labels, and more.
Wide Range of Plots: matplotlib supports a wide range of plots and charts, including line
plots, bar charts, histograms, scatter plots, and more. This makes it suitable for a variety of
data visualization tasks.
Flask is a lightweight web application framework for Python. It is designed to be simple and
easy to use, allowing developers to quickly create web applications with minimal boilerplate
code. Flask is often referred to as a "micro" framework because it does not require any specific
tools or libraries, and it does not impose a specific way of structuring the application.
Flask is used for developing web applications and APIs. It provides tools and libraries for
handling routing, request and response handling, template rendering, and more. Flask is
commonly used for building small to medium-sized web applications, prototypes, and APIs due
to its simplicity and flexibility.