0% found this document useful (0 votes)
6 views7 pages

Python Programming Concepts and Applications

The document outlines various units of study in Python, covering constructs, data structures, file handling, object-oriented programming, and data analysis. It includes both 2-mark and big questions for each unit, along with programming tasks and examples for practical understanding. Key topics include Python operators, data types, exception handling, CRUD operations in MongoDB, and data visualization using libraries like Matplotlib.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views7 pages

Python Programming Concepts and Applications

The document outlines various units of study in Python, covering constructs, data structures, file handling, object-oriented programming, and data analysis. It includes both 2-mark and big questions for each unit, along with programming tasks and examples for practical understanding. Key topics include Python operators, data types, exception handling, CRUD operations in MongoDB, and data visualization using libraries like Matplotlib.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Unit-I: Python Constructs

2-Mark Questions:

1. What is the difference between Python’s interactive mode and script mode?
2. Define identifiers and keywords in Python.
3. What is the purpose of comments in Python?
4. List the primary data types in Python.
5. What is a lambda function? How does it differ from a regular function?
6. Give examples of conditional statements in Python.
7. What is the difference between break and continue in loops?

Big Questions:

1. Explain Python operators with suitable examples.


2. Write a program to calculate the EMI for a loan using Python.
3. Describe the Chocolate Distribution Algorithm with implementation.
4. Discuss Python's control flow with examples of if-else and looping constructs.

Unit-II: Lists, Tuples, Dictionaries, and Sets

2-Mark Questions:

1. What is aliasing in lists?


2. How is a tuple different from a list?
3. Name any four methods of a dictionary and their use.
4. What are the key operations in a set?
5. What is meant by slicing in lists? Provide an example.

Big Questions:

1. Discuss the differences between mutable and immutable data structures in Python.
2. Explain and implement Kadane’s Algorithm in Python.
3. Write a program for the Dutch National Flag Algorithm.
4. Demonstrate dictionary operations with examples.

Unit-III: Files, Modules, and Packages

2-Mark Questions:

1. What is the format operator in Python?


2. Define the purpose of try and except in exception handling.
3. How do you read a text file in Python?
4. What is the difference between a module and a package?
5. List any two command-line arguments used in Python.
Big Questions:

1. Write a Python program to manage bank records using file handling.


2. Explain the steps involved in handling exceptions in Python with examples.
3. How can you locate the path of a Python module? Explain with a program.
4. Describe the process of creating and importing modules in Python.

Unit-IV: OOP and Databases

2-Mark Questions:

1. Define encapsulation and give an example.


2. What is the role of a constructor in Python?
3. Name the CRUD operations in MongoDB.
4. How do you connect Python with MongoDB?
5. Differentiate between abstraction and polymorphism.

Big Questions:

1. Explain the principles of object-oriented programming in Python.


2. Write a Python program for event management using MongoDB.
3. Describe inheritance with an example in Python.
4. Discuss CRUD operations in MongoDB with Python code examples.

Unit-V: Data Analysis and Web Frameworks

2-Mark Questions:

1. What is the purpose of NumPy in Python?


2. List any two methods of handling missing data in Pandas.
3. What is the difference between MVC and MVT architecture in Django?
4. Name three types of plots in Matplotlib.
5. What are universal functions in NumPy?

Big Questions:

1. Explain NumPy arrays and their operations with examples.


2. Write a program to demonstrate data indexing and selection in Pandas.
3. Describe the folder structure of a Django project.
4. Develop a Python application for graph plotting using Matplotlib.
5. Discuss the process of creating forms and templates in Django with an example.
Unit-I: Python Constructs

1. Write a program to calculate EMI for a loan based on user input (principal, interest
rate, tenure).
2. Develop a Python program to detect all vowels in a string that are "sandwiched"
between non-vowel characters.
3. Create a Python program to implement a simple Chocolate Distribution Algorithm to
minimize the difference between the maximum and minimum chocolates given.
4. Write a Python program to demonstrate the use of lambda functions by sorting a list
of tuples based on the second element.
5. Write a Python program to find the factorial of a number using a fruitful function.

Unit-II: Lists, Tuples, Dictionaries, and Sets

6. Write a Python program to implement the Dutch National Flag Algorithm to sort an
array of 0s, 1s, and 2s.
7. Create a program to demonstrate tuple unpacking and tuple as a return value.
8. Write a Python program to perform dictionary operations: adding, updating, deleting,
and searching keys/values.
9. Implement a Python program to find the union, intersection, and difference of two
sets.
10. Develop a program to solve the Count and Say problem.
11. Write a Python program to find the maximum sum of a contiguous subarray using
Kadane’s Algorithm.

Unit-III: Files, Modules, and Packages

12. Create a bank management application where you can:


o Add a new account (store data in a text file).
o View all accounts.
o Deposit money into an account.
13. Write a Python program to demonstrate exception handling for invalid file operations
(e.g., file not found).
14. Create a Python module with a few utility functions (e.g., factorial, prime check). Import
and use this module in another script.
15. Write a program to read command-line arguments and display them as output.

Unit-IV: OOP and Databases


16. Write a Python program demonstrating all principles of OOP (encapsulation, inheritance,
polymorphism, and abstraction).
17. Develop an event management application using MongoDB:
o Add an event (CRUD operation).
o View all events.
o Update an event detail.
o Delete an event.
18. Create a real estate management system using MongoDB and Python where you can
perform CRUD operations on property records.

Unit-V: Data Analysis and Web Frameworks

19. Write a Python program using NumPy to calculate the sum, mean, and standard
deviation of an array.
20. Develop a program in Pandas to:
o Create a DataFrame.
o Perform operations such as data indexing, selection, and handling missing
values.
21. Use Matplotlib to:
o Create a simple line plot.
o Generate a scatter plot to visualize data points.
22. Design a simple webpage in Django that includes a form to collect user data (name
and email).
23. Create a Python program to generate a box plot and a bar plot for given data using
Matplotlib.

Unit-I: Python Constructs

Financial Application: EMI Calculation

python
Copy code
def calculate_emi(principal, rate, time):
rate = rate / (12 * 100) # Monthly interest rate
time = time * 12 # Convert years to months
emi = (principal * rate * ((1 + rate) ** time)) / (((1 + rate) ** time)
- 1)
return round(emi, 2)

principal = float(input("Enter the loan amount: "))


rate = float(input("Enter the annual interest rate (in %): "))
time = int(input("Enter the loan tenure (in years): "))
print("The EMI is:", calculate_emi(principal, rate, time))

Sandwich Vowel Program

python
Copy code
def is_vowel(char):
return [Link]() in 'aeiou'

def sandwich_vowel(s):
result = []
for i in range(1, len(s) - 1):
if is_vowel(s[i]) and not is_vowel(s[i - 1]) and not is_vowel(s[i +
1]):
[Link](s[i])
return result

string = input("Enter a string: ")


print("Sandwiched vowels:", sandwich_vowel(string))

Unit-II: Lists, Tuples, Dictionaries, and Sets

Dutch National Flag Algorithm

python
Copy code
def dutch_national_flag(arr):
low, mid, high = 0, 0, len(arr) - 1
while mid <= high:
if arr[mid] == 0:
arr[low], arr[mid] = arr[mid], arr[low]
low += 1
mid += 1
elif arr[mid] == 1:
mid += 1
else:
arr[mid], arr[high] = arr[high], arr[mid]
high -= 1
return arr

arr = [2, 0, 1, 2, 1, 0]
print("Sorted Array:", dutch_national_flag(arr))

Kadane’s Algorithm

python
Copy code
def max_subarray_sum(arr):
max_sum = float('-inf')
current_sum = 0
for num in arr:
current_sum = max(num, current_sum + num)
max_sum = max(max_sum, current_sum)
return max_sum

arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]


print("Maximum Subarray Sum:", max_subarray_sum(arr))

Unit-III: Files, Modules, and Packages

Bank Management Application Using Files


python
Copy code
def create_account():
with open("bank_accounts.txt", "a") as f:
acc_no = input("Enter account number: ")
name = input("Enter account holder name: ")
balance = input("Enter initial deposit: ")
[Link](f"{acc_no},{name},{balance}\n")
print("Account created successfully!")

def view_accounts():
with open("bank_accounts.txt", "r") as f:
print("Account Details:")
print([Link]())

def deposit(acc_no, amount):


lines = []
with open("bank_accounts.txt", "r") as f:
lines = [Link]()

with open("bank_accounts.txt", "w") as f:


for line in lines:
acc, name, balance = [Link]().split(',')
if acc == acc_no:
balance = str(float(balance) + amount)
[Link](f"{acc},{name},{balance}\n")
print("Amount deposited successfully!")

# Create, view, or deposit example usage


create_account()
view_accounts()
deposit("12345", 500)

Unit-IV: OOP and Databases

CRUD Operations in MongoDB (Python)

python
Copy code
from pymongo import MongoClient

# MongoDB connection
client = MongoClient("mongodb://localhost:27017/")
db = client['mydatabase']
collection = db['mycollection']

# Create
def create_document(data):
collection.insert_one(data)
print("Document inserted successfully.")

# Read
def read_documents():
for doc in [Link]():
print(doc)

# Update
def update_document(filter_query, new_values):
collection.update_one(filter_query, {'$set': new_values})
print("Document updated successfully.")

# Delete
def delete_document(filter_query):
collection.delete_one(filter_query)
print("Document deleted successfully.")

# Example usage
create_document({"name": "John", "age": 30})
read_documents()
update_document({"name": "John"}, {"age": 35})
delete_document({"name": "John"})

Unit-V: Data Analysis and Web Frameworks

Graph Plotting Using Matplotlib

python
Copy code
import [Link] as plt

# Example data
x = [1, 2, 3, 4, 5]
y = [10, 20, 15, 25, 30]

# Line plot
[Link](x, y, label="Performance")
[Link]("Time")
[Link]("Value")
[Link]("Performance Analysis")
[Link]()
[Link]()

Form Design in Django (HTML Template)

html
Copy code
<!-- [Link] -->
<!DOCTYPE html>
<html>
<head>
<title>Simple Form</title>
</head>
<body>
<h2>Simple Form</h2>
<form action="/submit/" method="post">
{% csrf_token %}
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

Common questions

Powered by AI

Object-oriented programming (OOP) in Python is based on four main principles: encapsulation, inheritance, polymorphism, and abstraction. Encapsulation bundles data with methods to ensure that data is protected and managed through defined interfaces. Inheritance allows new classes to utilize methods and attributes of existing ones, promoting code reusability. Polymorphism enables objects to be processed differently based on their data type or class. Abstraction simplifies complexity by hiding the intricate functionalities of objects from the user. An example in Python could involve creating a class "Vehicle" and subclasses like "Car" and "Bike" inheriting properties like "speed" but implementing their own specific behaviors .

Python's interactive mode allows programmers to write code line-by-line and immediately see the results, making it ideal for quick tests, learning, and debugging. In contrast, script mode involves writing code in a file and executing it all at once, which is better suited for developing larger programs due to its ability to run complex scripts that might require multiple executions and refinements. Interactive mode is useful for rapid testing, while script mode supports the development of more structured and scalable applications .

Aliasing occurs when two or more variables reference the same list in memory. This can lead to unintended side-effects when one variable alters the list because the change will be reflected across all aliasing references. It is important to carefully manage list references to prevent bugs in programs relying on complex data manipulations .

Creating a module in Python involves writing Python code in a separate file with a `.py` extension. This file can then be imported into other scripts using the `import` statement, enabling code reuse and modular architecture. For example, placing utility functions in a `utils.py` file allows them to be used across multiple projects by simply importing `utils`. Modules help organize code better, reduce redundancy, and facilitate maintainability and scalability in larger software projects .

CRUD operations in MongoDB using Python involve Create, Read, Update, and Delete functions. Create operation can be done using `insert_one()` to add data into the collection. Read operation utilizes `find()` to retrieve documents, possibly applying filters. Update operation with `update_one()` modifies existing documents based on specified criteria. Delete uses `delete_one()` to remove documents. For example: `insert_one({'name': 'John'})`, `find({'name': 'John'})`, `update_one({'name': 'John'}, {'$set': {'age': 30}})`, and `delete_one({'name': 'John'})` .

Universal functions (ufuncs) in NumPy are essential for performing element-wise operations on arrays, enhancing computational efficiency by leveraging vectorization. Unlike iterative operations in base Python, ufuncs operate on entire arrays, reducing the need for explicit loops. This improves performance, especially with large datasets, by utilizing optimized C and Fortran functions under the hood. Examples include `numpy.add` and `numpy.multiply` for performing additions and multiplications swiftly across array elements .

Python's control flow mechanisms, such as the if-else conditions and looping constructs, allow developers to direct the execution path of a program based on conditions and repetitions. The if-else statement executes conditional logic, where specific blocks of code are run depending on whether a condition evaluates to true or false. Similarly, loops (for and while loops) enable code to execute repeatedly based on a specified condition, facilitating the execution of repetitive tasks efficiently. Control flow constructs are critical for implementing decision-making and iterative procedures in programs .

In Python, mutable data structures like lists and dictionaries can be changed after creation, allowing for dynamic data manipulation such as appending, updating, or deleting elements. Immutable data structures, like tuples and strings, cannot be altered, promoting data integrity and thread safety. The immutability feature is advantageous in scenarios where constant data representation is crucial, as it prevents any unintended modifications. Mutable types offer flexibility but can lead to side-effects if not managed properly .

The Chocolate Distribution Algorithm is used to allocate chocolates among students such that the maximum difference between the highest and lowest allocations is minimized. By sorting the chocolates and optimally distributing them among students, the algorithm ensures the smallest possible disparity in allocation, which is crucial in fairness-driven applications such as resource distribution and load balancing in computing systems .

Django uses the Model-View-Template (MVT) architecture, where the template serves as the user interface, complementing the controller's role in traditional MVC architecture. Rather than explicitly managing HTTP requests, MVT leverages Django's built-in ORM for backend database interactions, simplifying developers' tasks. The core distinction is in how Django abstracts and manages components, offering more automated and less error-prone development paths compared to traditional MVC frameworks which may require manual routing code and logic handling .

You might also like