0% found this document useful (0 votes)
8 views

CP Assignment (1)

The document contains sample questions and answers related to computer programming, specifically focusing on Python. It covers topics such as data types, comments, object-oriented programming, NumPy arrays, and file handling. Each section includes explanations, code examples, and best practices for effective programming in Python.

Uploaded by

sureshchou7048
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

CP Assignment (1)

The document contains sample questions and answers related to computer programming, specifically focusing on Python. It covers topics such as data types, comments, object-oriented programming, NumPy arrays, and file handling. Each section includes explanations, code examples, and best practices for effective programming in Python.

Uploaded by

sureshchou7048
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

COMPUTER PROGRAMMING

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?

In Python, some important data types include:

1. Integer (`int`) - whole numbers without a decimal point.


2. Float (`float`) - numbers with a decimal point.
3. String (`str`) - sequence of characters enclosed in single or double quotes.
4. Boolean (`bool`) - represents True or False.

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.

marks = int(input("Enter your 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.

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.

In Python dictionaries, keys and values play important roles:


Keys: Keys are unique identifiers within a dictionary. They are used to retrieve the
corresponding value. Keys must be immutable objects like strings, numbers, or tuples.
Values: Values are the data associated with a particular key. Each key in a dictionary is
associated with a single value.
students = {
1001: {"name": "Ankit", "grade": 9, "subjects": ["Math", "Science", "History"]},
1002: {"name": "Tammana", "grade": 10, "subjects": ["English", "Physics",
"Geography"]},
1003: {"name": "Bharat", "grade": 9, "subjects": ["Chemistry", "Biology", "Art"]}
}

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.

Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a new


class (derived class or subclass) to inherit attributes and methods from an existing class (base
class or superclass). This promotes code reuse and extensibility by allowing the derived class
to reuse the functionality of the base class and also add new functionality or override existing
functionality.
Types of inheritance:
Single inheritance: A derived class inherits from only one base class.
Multiple inheritance: A derived class inherits from multiple base classes.
Multilevel inheritance: One derived class is used as a base class for another derived class.
Hierarchical inheritance: Multiple derived classes inherit from a single base class.

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.

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 display the
values.

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


classes to design and create reusable, modular, and scalable software applications. In Python,
everything is an object, and you can define your own classes to create objects with specific
attributes (data) and methods (functions).

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

# Creating an instance of the Person class


person1 = Person("Alice", 30)

# Accessing attributes and calling methods


person1.display()

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

print(add(2, 3)) # Output: 5

# Equivalent lambda function


add_lambda = lambda a, b: a + b

print(add_lambda(2, 3)) # Output: 5

4) Explain 4 pillars of OOPs in Python .


The four pillars of Object-Oriented Programming (OOP) in Python are:

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.

4. Polymorphism: Polymorphism means the ability to take multiple forms. In OOP,


polymorphism allows objects of different classes to be treated as objects of a common
superclass. It allows a single interface to be used for different data types or objects, providing a
way to perform a single action in different ways.

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


In Python, the super() function is used to call a method from a parent class (or superclass) in a
subclass. It is particularly useful in inheritance when you want to extend the functionality of a
method defined in the parent class without completely overriding it.
The super() function returns a proxy object that represents the parent class, allowing you to call
methods on the parent class directly. This is important because it ensures that the method
resolution order (MRO) is followed correctly, especially in multiple inheritance scenarios.

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

# Create a NumPy array


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

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

# Create 3 arrays of 1-dimension


array1 = np.array([1, 2, 3, 4, 5])
array2 = np.array([6, 7, 8])
array3 = np.array([9, 10, 11, 12, 13, 14])
# Find sum of the 3rd and 4th elements of all arrays
sum_3rd_4th = array1[2] + array1[3] + array2[2] + array3[2] + array3[3]

print("Sum of 3rd and 4th elements of all arrays:", sum_3rd_4th)


3) How does indexing work in NumPy arrays? How do you extract the third element
from a NumPy array named arr?
We can use integers and slices to index NumPy arrays.
Negative indices are supported, with -1 referring to the last element, -2 referring to the
second-to-last element, and so on.
import numpy as np

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

# Extract the third element (index 2)


third_element = arr[2]

print("Third element:", third_element)


4) Explain the difference between indexing and slicing in the context of NumPy arrays.
Indexing:
Indexing refers to accessing a single element or a subset of elements at specific positions in the
array.
When using indexing, you specify the position (index) of the element(s) you want to access.
You can use integers or arrays of integers as indices to access elements.
Indexing returns a single element when using a single integer index or a subset of elements
when using an array of indices.

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.

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?

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 at second row and third column:", element)

Answer: data[1, 2]
6) What is a Pandas DataFrame and how does Pandas facilitate data analysis in
Python, give 4 basic operations.

A Pandas DataFrame is a two-dimensional, size-mutable, and heterogeneous tabular data


structure with labeled axes (rows and columns). It is similar to a spreadsheet or SQL table,
where each column can have a different data type. DataFrames are widely used for data
manipulation, cleaning, analysis, and visualization in Python.
import pandas as pd
# Creating a DataFrame from a dictionary
data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'Los Angeles', 'Chicago']}
df = pd.DataFrame(data)

# Displaying the first few rows of the DataFrame


print(df.head())

# Selecting a single column


print(df['Name'])
# Selecting multiple columns
print(df[['Name', 'City']])
# Selecting rows based on a condition
print(df[df['Age'] > 30])

# Calculating the mean age


print(df['Age'].mean())

# Grouping data by a column and calculating statistics


grouped_data = df.groupby('City').mean()
print(grouped_data)
7) Create a dataframe to store details of a product like name, product id, company
along with their values.
import pandas as pd
# Creating a dictionary with product details
data = {
'Name': ['Product1', 'Product2', 'Product3'],
'Product ID': [101, 102, 103],
'Company': ['CompanyA', 'CompanyB', 'CompanyC']
}

# Creating a DataFrame from the dictionary


df = pd.DataFrame(data)

# Displaying the DataFrame


print(df)

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'

Modified Text: 'All hail King Louis.

def replace_word(original_text, search_word, replace_word):


modified_text = original_text.replace(search_word, replace_word)
return modified_text
original_text = 'All hail King George.'
search_word = 'George'
replace_word = 'Louis'

modified_text = replace_word(original_text, search_word, replace_word)


print("Modified Text:", modified_text)

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

# Reading a CSV file


with open('data.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
print(row)

# Writing to a CSV file


with open('data.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['Name', 'Age', 'City'])
writer.writerow(['Alice', 25, 'New York'])
writer.writerow(['Bob', 30, 'Los Angeles'])

# Reading a binary file


with open('file.bin', 'rb') as f:
data = f.read()

# Writing to a binary file


with open('file.bin', 'wb') as f:
f.write(b'Hello, world!')

import json

# Reading a JSON file


with open('data.json', 'r') as f:
data = json.load(f)
print(data)

# Writing to a JSON file


with open('data.json', 'w') as f:
data = {'name': 'Alice', 'age': 25, 'city': 'New York'}
json.dump(data, f)
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.

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.

Writing data to files:


Writing allows you to write data to a file, overwriting its previous contents if the file
already exists.
You would use writing when you need to create a new file or completely replace the
existing content of a file.
Writing is done using the 'w' mode in the open() function.

Appending data to files:


Appending allows you to add data to the end of a file without deleting its existing
contents.
You would use appending when you want to add new information to an existing file, such
as logging new events or adding entries to a log file.
Appending is done using the 'a' mode in the open() function.
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.

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

# Create an empty dictionary to store word counts


word_counts = {}

# Iterate over each word


for word in words:
# Convert the word to lowercase
word = word.lower()

# Remove punctuation
word = word.strip('.,!?')

# Update the word count in the dictionary


if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1

return word_counts

# Given text
sample_text = 'The quick brown fox jumps over the quick red fox.'

# Count the occurrences of each word


word_counts = count_words(sample_text)

# Print the word counts


for word, count in word_counts.items():
print(f"{word.capitalize()}: {count}")

UNIT 5
1) Write short notes on:

a) Input tag and its types


b) Submit button
c) Action attribute
d) Method attribute

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.

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

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


<select id="courses" name="courses[]" multiple required>
<option value="Math">Math</option>
<option value="Science">Science</option>
<option value="English">English</option>
<option value="History">History</option>
</select><br><br>

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


</form>
</body>
</html>

from flask import Flask, render_template, request

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

return f"Name: {name}<br>Email: {email}<br>Courses: {', '.join(courses)}"

if __name__ == '__main__':
app.run(debug=True)

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


Age No. of people having
intervals diabetes
20-30 10
30-40 22
40-50 64
50-60 70

import matplotlib.pyplot as plt

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

Line Plot: plt.plot()


Bar Chart: plt.bar()
Histogram: plt.hist()
Scatter Plot: plt.scatter()
Pie Chart: plt.pie()
Box Plot: plt.boxplot()
Violin Plot: plt.violinplot()
Heatmap: plt.imshow()
3D Plot: plt.plot3D()

6) What is Flask? Why it is used?

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.

You might also like