0% found this document useful (0 votes)
3 views25 pages

Python Object Types and Programming Concepts

The document provides an overview of various concepts in Python programming, including definitions of objects, lists, exceptions, packages, regular expressions, threading, web surfing, web servers, DB-API, and CGI. It explains the characteristics and types of Python objects, how to create and use packages, and introduces libraries for web scraping and server creation. Additionally, it covers the DB-API for database interaction and the CGI protocol for generating dynamic web content.

Uploaded by

vrohitkumar18
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)
3 views25 pages

Python Object Types and Programming Concepts

The document provides an overview of various concepts in Python programming, including definitions of objects, lists, exceptions, packages, regular expressions, threading, web surfing, web servers, DB-API, and CGI. It explains the characteristics and types of Python objects, how to create and use packages, and introduces libraries for web scraping and server creation. Additionally, it covers the DB-API for database interaction and the CGI protocol for generating dynamic web content.

Uploaded by

vrohitkumar18
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

SECTION-A

1. Define the following used in Python Programming :

a) Python objects

What is an Object?

An object in Python is an instance of a class, which is a blueprint for creating objects. Each
object has:

 Attributes: Variables that store data related to the object.


 Methods: Functions that define the behaviors of the object.

Types of Python Objects

Python supports various built-in object types, which can be broadly categorized into:

1. Numeric Types:
o Integers: Whole numbers, e.g., 5, -10.
o Floats: Decimal numbers, e.g., 3.14, -0.001.
o Complex Numbers: Numbers with a real and imaginary part, e.g., 3 + 4j.
2. Sequence Types:
o Strings: Immutable sequences of characters, e.g., "hello", 'Python'.
o Lists: Mutable ordered collections, e.g., [1, 2, 3].
o Tuples: Immutable ordered collections, e.g., (1, 2, 3).
3. Mapping Type:
o Dictionaries: Unordered collections of key-value pairs, e.g., {'name':
'Alice', 'age': 30}.
4. Set Types:
o Sets: Unordered collections of unique elements, e.g., {1, 2, 3}.
o Frozensets: Immutable versions of sets.
5. Boolean Type:
o Represents True or False.
6. NoneType:
o Represents the absence of a value, indicated by the None keyword.

Creating Custom Objects

In Python, you can create custom objects by defining a class. Here’s a simple example:

class Dog:
def __init__(self, name, age):
[Link] = name # Attribute
[Link] = age # Attribute
def bark(self): # Method
return f"{[Link]} says Woof!"

# Creating an instance (object) of the Dog class


my_dog = Dog("Buddy", 3)

# Accessing attributes and methods


print(my_dog.name) # Output: Buddy
print(my_dog.bark()) # Output: Buddy says Woof!

Characteristics of Python Objects

1. Dynamic Typing:
o Python uses dynamic typing, meaning the type of an object is determined at
runtime, and variables can change types.
2. Mutability:
o Some objects (like lists and dictionaries) are mutable, meaning they can be
changed after creation. Others (like strings and tuples) are immutable.
3. Identity, Type, and Value:
o Every object has a unique identity (memory address), a type (defined by its class),
and a value (the data it holds).
4. Inheritance:
o Python supports inheritance, allowing new classes to inherit attributes and
methods from existing ones, promoting code reuse.
5. Polymorphism:
o Objects of different classes can be treated as objects of a common superclass. This
enables the same method to behave differently depending on the object’s class.

b) Lists

c) Exceptions

d) Packages

packages are a way to organize and distribute modules and related code. A package is essentially
a directory that contains multiple Python modules, and it may also include sub-packages. This
structure helps in maintaining and organizing large codebases, making it easier to manage
dependencies and namespace collisions.

Key Concepts of Python Packages

1. Package Structure:
o A package is a directory that contains an __init__.py file (which can be empty).
This file indicates to Python that the directory should be treated as a package.
o Packages can contain sub-packages and modules, allowing for a hierarchical
organization of code.
Example Structure:

my_package/
__init__.py
[Link]
[Link]
sub_package/
__init__.py
[Link]

2. Creating a Package: To create a package, follow these steps:


o Create a directory for your package.
o Add an __init__.py file to that directory.
o Add your Python modules (i.e., .py files) to the package directory.

Example:

my_package/
__init__.py
math_operations.py
string_operations.py

3. Using Packages: You can import modules from a package using the import statement.

Example:

from my_package import math_operations


result = math_operations.add(5, 3) # Assuming add() is defined in
math_operations.py

You can also import specific functions or classes:

from my_package.math_operations import add

4. Sub-packages: A package can contain other packages (sub-packages), allowing for


further organization.

Example:

my_package/
__init__.py
utilities/
__init__.py
file_utils.py
network_utils.py

Importing from Sub-packages:

from my_package.utilities import file_utils


5. Installing Packages: Python packages can be distributed and installed using package
managers like pip. Many packages are available on the Python Package Index (PyPI),
which can be installed with a simple command:

pip install package_name

Advantages of Using Packages

 Organization: Packages help organize related modules into a coherent structure, making
it easier to navigate and maintain the codebase.
 Namespace Management: Packages prevent name conflicts by encapsulating modules
in their own namespaces.
 Reusability: Modules within packages can be reused across different projects, promoting
code reuse.
 Dependency Management: When distributing packages, dependencies can be managed
more effectively, ensuring that all required modules are available.

e) Regular expressions

Regular expressions (regex) in Python are powerful tools for searching, matching, and
manipulating strings based on specific patterns. The re module in Python provides functions to
work with regex. Here’s a quick overview of how to use them:

Basic Functions

1. Import the Module

import re

2. Searching for Patterns


o [Link](): Searches the string for a match and returns a match object if found.

match = [Link](r'\d+', 'There are 123 apples')


if match:
print([Link]()) # Output: 123

3. Finding All Matches


o [Link](): Returns a list of all matches in the string.

matches = [Link](r'\d+', 'There are 123 apples and 456 oranges')


print(matches) # Output: ['123', '456']

4. Replacing Patterns
o [Link](): Replaces occurrences of a pattern with a specified string.
result = [Link](r'apples', 'bananas', 'There are 123 apples')
print(result) # Output: There are 123 bananas

5. Splitting Strings
o [Link](): Splits a string by the occurrences of a pattern.

parts = [Link](r'\s+', 'Split this string by spaces')


print(parts) # Output: ['Split', 'this', 'string', 'by', 'spaces']

Common Patterns

 \d: Matches any digit (equivalent to [0-9])


 \D: Matches any non-digit character
 \w: Matches any alphanumeric character (equivalent to [a-zA-Z0-9_])
 \W: Matches any non-word character
 \s: Matches any whitespace character (space, tab, newline)
 .: Matches any character except a newline
 ^: Matches the start of a string
 $: Matches the end of a string
 *: Matches 0 or more repetitions
 +: Matches 1 or more repetitions
 ?: Matches 0 or 1 repetition
 {n}: Matches exactly n repetitions
 {n, m}: Matches between n and m repetitions

Example Usage

Here’s a complete example that demonstrates several functionalities:

import re

text = "Contact us at support@[Link] or visit our website at


[Link]

# Find email addresses


emails = [Link](r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}', text)
print("Emails found:", emails)

# Replace website URL with a placeholder


updated_text = [Link](r'http[s]?://[^\s]+', '[LINK]', text)
print("Updated text:", updated_text)

f) Thread module

The thread module in Python provides low-level primitives for working with threads. However,
it has been largely superseded by the threading module, which offers a higher-level interface
and more features.
Key Features of the threading Module

1. Thread Creation: You can create new threads by subclassing Thread or by using the
Thread class directly.
2. Thread Synchronization: It includes locks, conditions, and semaphores to help manage
thread interactions and prevent race conditions.
3. Daemon Threads: You can create threads that run in the background and terminate when
the main program exits.
4. Thread Communication: You can use queues to facilitate communication between
threads.

Example of Using threading

Here’s a simple example to demonstrate creating and starting a thread:

import threading
import time

def worker():
print("Worker thread is running")
[Link](2)
print("Worker thread is done")

# Create a thread
thread = [Link](target=worker)

# Start the thread


[Link]()

# Wait for the thread to finish


[Link]()

print("Main thread is done")

When to Use Threads

Threads can be useful for:

 I/O-bound tasks (e.g., web scraping, file operations)


 Running multiple tasks concurrently
 Keeping the UI responsive in applications

g) Web surfing

Web surfing in Python typically involves using libraries to interact with web pages, scrape
content, or automate browsing tasks. Here are some popular libraries and methods for web
surfing in Python:
1. Requests

The requests library is great for making HTTP requests to retrieve web content.

import requests

response = [Link]('[Link]
print([Link])

2. Beautiful Soup

For parsing HTML and extracting data, Beautiful Soup works well in conjunction with
requests.

from bs4 import BeautifulSoup

response = [Link]('[Link]
soup = BeautifulSoup([Link], '[Link]')

# Extracting specific data


titles = soup.find_all('h1')
for title in titles:
print([Link])

3. Selenium

If you need to interact with web pages (like clicking buttons or filling out forms), Selenium can
control a web browser.

from selenium import webdriver

# Set up the web driver (make sure you have the appropriate driver installed)
driver = [Link]()

[Link]('[Link]

# Interact with the page


button = driver.find_element_by_id('submit-button')
[Link]()

# Close the browser


[Link]()

4. Scrapy

For more complex web scraping tasks, Scrapy is a powerful framework that allows you to define
spiders to crawl websites and extract structured data.

# Install Scrapy
pip install scrapy
You would create a new Scrapy project and define your spiders to crawl and scrape data.

5. Pyppeteer

For headless browsing (running a browser without a GUI), Pyppeteer is a good choice. It's a
Python port of Puppeteer, which is a [Link] library.

import asyncio
from pyppeteer import launch

async def main():


browser = await launch()
page = await [Link]()
await [Link]('[Link]
content = await [Link]()
print(content)
await [Link]()

asyncio.get_event_loop().run_until_complete(main())

Considerations

 Respect [Link]: Always check a website's [Link] file to ensure that your
scraping activities are allowed.
 Rate Limiting: Be mindful of how frequently you make requests to avoid overwhelming
the server.
 Legal Compliance: Ensure that your activities comply with the website's terms of
service.

If you have specific needs or examples in mind, feel free to ask!

h) Web servers

Creating web servers in Python can be done using various frameworks and libraries, each suited
for different use cases. Here are some popular options:

1. Flask

Flask is a lightweight and easy-to-use micro web framework for building web applications.

from flask import Flask

app = Flask(__name__)

@[Link]('/')
def hello():
return "Hello, World!"
if __name__ == '__main__':
[Link](debug=True)

2. Django

Django is a full-featured web framework that follows the "batteries-included" philosophy,


providing many built-in features for building complex applications.

# Install Django
pip install django

Then create a project:

django-admin startproject myproject


cd myproject
python [Link] runserver

3. FastAPI

FastAPI is a modern framework for building APIs with Python 3.6+ based on standard Python
type hints, which makes it fast and easy to use.

from fastapi import FastAPI

app = FastAPI()

@[Link]("/")
def read_root():
return {"Hello": "World"}

# Run with: uvicorn filename:app --reload

4. Tornado

Tornado is an asynchronous networking library and web framework, great for handling long-
lived connections and WebSockets.

from tornado import web, ioloop

class MainHandler([Link]):
def get(self):
[Link]("Hello, World!")

app = [Link]([
(r"/", MainHandler),
])

if __name__ == "__main__":
[Link](8888)
[Link]().start()
5. [Link]

For simple use cases or development purposes, Python's built-in [Link] module can be
used to create a basic HTTP server.

from [Link] import SimpleHTTPRequestHandler, HTTPServer

PORT = 8000

class MyHandler(SimpleHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.end_headers()
[Link](b"Hello, World!")

httpd = HTTPServer(('localhost', PORT), MyHandler)


print(f"Serving on port {PORT}")
httpd.serve_forever()

Choosing the Right Framework

 Flask: Great for small to medium applications and APIs.


 Django: Best for large, complex applications that need an all-in-one solution.
 FastAPI: Ideal for modern, fast APIs, especially if you want automatic validation and
documentation.
 Tornado: Useful for real-time applications that require non-blocking I/O.
 [Link]: Perfect for quick tests and development.

If you have a specific use case or need help with a particular framework, let me know!

i) DB-API

The Python Database API (DB-API) is a specification for a standard interface that Python
programs can use to interact with databases. It is defined in PEP 249 and provides a consistent
way to connect to different database systems, execute SQL queries, and manage results.

Key Features of DB-API:

1. Connection Objects: Establish a connection to a database.


o Methods: connect(), commit(), rollback(), and close().
2. Cursor Objects: Used to execute SQL commands and fetch data.
o Methods: execute(), fetchone(), fetchall(), and fetchmany(size).
3. Parameterization: Supports safe execution of queries with parameters to prevent SQL
injection.
o Syntax: Use placeholders like ? or %s in SQL statements.
4. Error Handling: Provides a standardized way to handle exceptions using specific error
classes (e.g., DatabaseError, IntegrityError).
5. Transaction Management: Supports transactions with methods for committing and
rolling back changes.

Basic Example:

Here's a simple example of using DB-API with SQLite:

import sqlite3

# Connect to the database


connection = [Link]('[Link]')

# Create a cursor object


cursor = [Link]()

# Create a table
[Link]('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY,
name TEXT)')

# Insert a new user


[Link]('INSERT INTO users (name) VALUES (?)', ('Alice',))

# Commit the transaction


[Link]()

# Fetch all users


[Link]('SELECT * FROM users')
users = [Link]()

# Print users
print(users)

# Close the cursor and connection


[Link]()
[Link]()

Key Points to Remember:

 Always close connections and cursors to free resources.


 Use parameterized queries for security.
 Handle exceptions properly to avoid crashes.

This specification allows for greater flexibility and portability of database code across different
database systems in Python.

j) CGI.
Common Gateway Interface (CGI) is a standard protocol used to enable web servers to interact
with executable programs, typically scripts, to generate dynamic web content. In Python, CGI
allows you to create web applications that can respond to user requests by generating HTML or
other content dynamically.

Key Concepts of CGI in Python:

1. Execution Environment: When a web server receives a request for a CGI script, it
executes the script in a specific environment and sends the output back to the client.
2. HTTP Request and Response: CGI scripts process input from the user (like form data)
and return a response to the web browser.
3. Standard Input and Output: CGI scripts read from standard input (usually the request
data) and write to standard output (the HTTP response).
4. Content-Type Header: The first line of the output must specify the content type (e.g.,
Content-Type: text/html), followed by a blank line.

Basic Example of a CGI Script in Python:

Here's a simple example of a CGI script that generates an HTML page:

#!/usr/bin/env python3

import cgi

# Set the content type


print("Content-Type: text/html\n")

# Output HTML
print("<html>")
print("<head><title>CGI Example</title></head>")
print("<body>")
print("<h1>Hello, CGI!</h1>")
print("<p>This is a simple CGI script written in Python.</p>")

# Process form data if available


form = [Link]()
if "name" in form:
name = [Link]("name")
print(f"<p>Hello, {name}!</p>")
else:
print("<p>What's your name?</p>")
print('<form method="post">')
print('<input type="text" name="name">')
print('<input type="submit" value="Submit">')
print('</form>')

print("</body>")
print("</html>")

Steps to Use a CGI Script:


1. File Permissions: Ensure the script has execute permissions. You can set this with chmod
+x [Link].
2. Place in CGI Directory: Save the script in the server's CGI directory (often /cgi-bin).
3. Access via URL: Access the script through a web browser by navigating to the
appropriate URL (e.g., [Link]

Key Points to Remember:

 CGI scripts are executed for each request, which may lead to performance issues for
high-traffic sites.
 Alternatives like WSGI or web frameworks (Flask, Django) are often preferred for more
complex applications.
 Always sanitize user input to prevent security vulnerabilities.

CGI provides a straightforward way to create dynamic web content in Python, although it is less
common in modern web development.

SECTION-B
2. List any five built-in functions used in Python. Give suitable examples.

en()

Description: Returns the length (number of items) of an object (e.g., string, list, tuple).

Example:

my_list = [1, 2, 3, 4, 5]
print(len(my_list)) # Output: 5

my_string = "Hello, World!"


print(len(my_string)) # Output: 13

2. type()

Description: Returns the type of an object.

Example:

num = 10
print(type(num)) # Output: <class 'int'>

text = "Hello"
print(type(text)) # Output: <class 'str'>
3. max()

Description: Returns the largest item in an iterable or the largest of two or more arguments.

Example:

numbers = [10, 20, 30, 40]


print(max(numbers)) # Output: 40

print(max(5, 10, 15)) # Output: 15

4. sum()

Description: Sums up all the items in an iterable, typically a list or tuple.

Example:

numbers = [1, 2, 3, 4, 5]
print(sum(numbers)) # Output: 15

# With a start value


print(sum(numbers, 10)) # Output: 25

5. sorted()

Description: Returns a new sorted list from the elements of any iterable.

Example:

numbers = [5, 2, 9, 1, 5, 6]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 2, 5, 5, 6, 9]

# Sorting in reverse order


print(sorted(numbers, reverse=True)) # Output: [9, 6, 5, 5, 2, 1]

These built-in functions are fundamental to Python programming and provide essential
functionality for manipulating data and objects.

4. What is the significance of Namespaces in Python programming.

Namespaces in Python are crucial for managing the scope and visibility of variables, functions,
and objects within a program. They serve several significant purposes:

1. Organizing Code
Namespaces help organize and structure code, allowing for better management of variables and
functions. This organization helps avoid naming conflicts, especially in larger projects or when
using multiple modules.

2. Avoiding Name Collisions

By providing a unique context for variable names, namespaces prevent name collisions. For
example, you can have a function and a variable with the same name in different namespaces
without conflict.

3. Scope Management

Namespaces define the scope in which variables and functions are accessible. This scope can be
global (accessible throughout the program), local (accessible only within a function), or built-in
(names provided by Python).

4. Modularity

Namespaces enhance modularity by allowing you to encapsulate functionality within modules or


classes. This encapsulation keeps code organized and makes it easier to maintain and reuse.

5. Dynamic Binding

Python uses namespaces to support dynamic binding. This means that names can be assigned to
different objects at runtime, enabling more flexible programming.

Types of Namespaces

1. Built-in Namespace: Contains names built into Python (e.g., print, len).
2. Global Namespace: Contains names defined at the top level of a module or script.
3. Local Namespace: Contains names defined within a function. Each function call creates
a new local namespace.
4. Enclosing Namespace: Exists in nested functions, containing names from the outer
function's scope.

Example

Here’s a simple example to illustrate namespaces:

x = "global"

def outer_function():
x = "outer"

def inner_function():
x = "inner"
print("Inner:", x) # Refers to the inner function's x
inner_function()
print("Outer:", x) # Refers to the outer function's x

outer_function()
print("Global:", x) # Refers to the global x

Output:
sql
Copy code
Inner: inner
Outer: outer
Global: global

In this example:

 The inner_function has access to its local x, the outer_function's x, and the global x,
demonstrating how namespaces control variable access.

5. Write a python program to calculate the length of a string without using library
functions.

Python program to calculate the length of a string without using any library functions:

def string_length(input_string):
count = 0 # Initialize a counter
for char in input_string: # Iterate over each character in the string
count += 1 # Increment the counter for each character
return count # Return the final count

# Example usage
user_input = input("Enter a string: ")
length = string_length(user_input)
print("The length of the string is:", length)

Explanation:

1. Function Definition: The string_length function takes a string as an argument.


2. Counter Initialization: A counter variable count is initialized to zero.
3. Iteration: A for loop iterates over each character in the string, incrementing the counter
by one for each character.
4. Return Length: Finally, the function returns the total count, which represents the length
of the string.

You can run this program, enter a string, and it will display the length of that string.
5. Write the steps to create simple web clients in Python.

6. Creating a simple web client in Python can be accomplished using various libraries, with
the most common being requests. Below are the steps to create a simple web client that
can make HTTP requests and handle responses.
7. Steps to Create a Simple Web Client in Python
8. Step 1: Install the Requests Library
9. If you haven't installed the requests library yet, you can do so using pip. Open your
terminal or command prompt and run:
10. pip install requests

11. Step 2: Import the Requests Library


12. In your Python script, import the requests library:
13. import requests

14. Step 3: Make an HTTP GET Request


15. You can use the get() method to retrieve data from a specific URL. Here’s a basic
example:
16. response =
[Link]('[Link]

17. Step 4: Check the Response


18. Check if the request was successful by examining the status code:
19. if response.status_code == 200:
20. print("Success!")
21. else:
22. print("Failed to retrieve data. Status code:",
response.status_code)

23. Step 5: Access the Response Content


24. You can access the content of the response, typically in JSON format for APIs, using the
json() method:
25. data = [Link]()
26. print(data)

27. Step 6: Making a POST Request


28. To send data to a server, use the post() method:
29. payload = {
30. 'title': 'foo',
31. 'body': 'bar',
32. 'userId': 1
33. }
34. post_response =
[Link]('[Link]
json=payload)
35.
36. if post_response.status_code == 201:
37. print("Data successfully posted!")
38. print(post_response.json())
39. else:
40. print("Failed to post data. Status code:",
post_response.status_code)

41. Step 7: Handle Exceptions


42. To make your web client robust, handle potential exceptions:
43. try:
44. response =
[Link]('[Link]
45. response.raise_for_status() # Raises an HTTPError for bad
responses
46. data = [Link]()
47. print(data)
48. except [Link] as e:
49. print("An error occurred:", e)
50. Full Example
51. Here’s a complete example that incorporates all the above steps:
52. import requests
53.
54. # GET request
55. try:
56. response =
[Link]('[Link]
57. response.raise_for_status() # Check for HTTP errors
58. data = [Link]()
59. print("GET Response:", data)
60. except [Link] as e:
61. print("An error occurred during GET:", e)
62.
63. # POST request
64. payload = {
65. 'title': 'foo',
66. 'body': 'bar',
67. 'userId': 1
68. }
69.
70. try:
71. post_response =
[Link]('[Link]
json=payload)
72. post_response.raise_for_status() # Check for HTTP errors
73. print("POST Response:", post_response.json())
74. except [Link] as e:
75. print("An error occurred during POST:", e)

6. How are object relational mappers useful?

7. Object-Relational Mappers (ORMs) are powerful tools in Python (and other


programming languages) that facilitate the interaction between object-oriented
programming and relational databases. Here are several ways in which ORMs are useful:
8. 1. Simplified Database Interaction
9. ORMs abstract away the complexity of raw SQL queries. Instead of writing SQL
statements, you can interact with the database using Python objects and methods. This
leads to cleaner, more readable code.
10. 2. Automatic SQL Generation
11. ORMs automatically generate SQL queries based on your Python class definitions and
method calls. This reduces the risk of syntax errors and ensures that the SQL is optimized
for the database you’re using.
12. 3. Data Abstraction
13. By using ORMs, you can focus on the business logic and data models without worrying
about the underlying database schema. This abstraction allows developers to think in
terms of objects rather than tables and rows.
14. 4. Cross-Database Compatibility
15. Many ORMs support multiple database backends (like PostgreSQL, MySQL, SQLite,
etc.). This means that you can switch databases with minimal changes to your code,
enhancing portability.
16. 5. Easier Data Manipulation
17. With ORMs, you can perform CRUD (Create, Read, Update, Delete) operations on your
objects directly. For example, to create a new record, you can instantiate a class and save
it, rather than writing an insert statement.
18. 6. Relationship Management
19. ORMs provide built-in mechanisms to handle relationships between tables (e.g., one-to-
many, many-to-many). You can easily navigate and manipulate related data using object
references.
20. 7. Built-in Validation and Constraints
21. ORMs often include features for data validation and enforcing constraints (like unique
fields or foreign keys). This can help maintain data integrity within your application.
22. 8. Migration Support
23. Many ORMs come with tools to manage database schema changes (migrations). This
makes it easier to evolve your database schema over time as your application
requirements change.
24. 9. Session Management
25. ORMs handle database connections and sessions, allowing you to easily manage
transactions and context, which simplifies the coding process.
26. Example: Using SQLAlchemy
27. Here's a brief example using SQLAlchemy, a popular ORM for Python:
28. from sqlalchemy import create_engine, Column, Integer, String
29. from [Link] import declarative_base
30. from [Link] import sessionmaker
31.
32. # Define the database engine
33. engine = create_engine('sqlite:///[Link]', echo=True)
34.
35. # Create a base class for declarative models
36. Base = declarative_base()
37.
38. # Define a User class
39. class User(Base):
40. __tablename__ = 'users'
41.
42. id = Column(Integer, primary_key=True)
43. name = Column(String)
44.
45. def __repr__(self):
46. return f"<User(name='{[Link]}')>"
47.
48. # Create the table
49. [Link].create_all(engine)
50.
51. # Create a new session
52. Session = sessionmaker(bind=engine)
53. session = Session()
54.
55. # Create a new user
56. new_user = User(name='Alice')
57. [Link](new_user)
58. [Link]()
59.
60. # Query the user
61. user = [Link](User).filter_by(name='Alice').first()
62. print(user) # Output: <User(name='Alice')>

SECTION-C
6. How multi-threaded programming is done in Python? Give an illustration.

Multi-threaded programming in Python can be accomplished using the threading module,


which provides a way to create and manage threads in your application. Threads allow you to run
multiple operations concurrently, which can be useful for I/O-bound tasks, such as network
requests or file operations.

Steps to Create a Multi-threaded Program

1. Import the threading Module: This module provides the necessary classes and
functions for creating threads.
2. Define a Function for the Thread: Create a function that you want the thread to
execute.
3. Create Thread Objects: Instantiate Thread objects, passing the target function and any
arguments it requires.
4. Start the Threads: Use the start() method to begin the execution of each thread.
5. Wait for Threads to Complete: Optionally, use the join() method to ensure the main
program waits for the threads to finish.

Example

Here’s a simple example that demonstrates how to use threads in Python:

import threading
import time

# Function to simulate a time-consuming task


def print_numbers():
for i in range(1, 6):
print(f"Number: {i}")
[Link](1) # Simulating a delay

def print_letters():
for letter in 'abcde':
print(f"Letter: {letter}")
[Link](1) # Simulating a delay

# Creating thread objects


thread1 = [Link](target=print_numbers)
thread2 = [Link](target=print_letters)

# Starting the threads


[Link]()
[Link]()

# Waiting for both threads to complete


[Link]()
[Link]()

print("Both threads have finished execution.")

Explanation of the Example

1. Function Definitions: Two functions, print_numbers() and print_letters(), are


defined to print numbers and letters with a one-second delay between prints.
2. Thread Creation: Two Thread objects are created, each assigned to one of the
functions.
3. Thread Start: The start() method is called on both thread objects, which begins their
execution.
4. Joining Threads: The join() method ensures that the main thread waits for both
thread1 and thread2 to complete before printing the final message.

Output

When you run the program, the output will interleave the numbers and letters, demonstrating that
both functions are running concurrently:

Number: 1
Letter: a
Number: 2
Letter: b
Number: 3
Letter: c
Number: 4
Letter: d
Number: 5
Letter: e
Both threads have finished execution.

Important Notes

 Global Interpreter Lock (GIL): Python's GIL means that only one thread can execute
Python bytecode at a time. This can limit the effectiveness of threading for CPU-bound
tasks. However, it works well for I/O-bound tasks.
 Thread Safety: Be cautious with shared data between threads. Use synchronization
mechanisms like Lock if necessary to avoid race conditions.

7. Define lists in Python. Write a python program to find the intersection of two lists.

Lists in Python

Lists in Python are ordered, mutable collections of items that can hold a variety of data types,
including numbers, strings, and other objects. Lists are defined using square brackets [], and
items are separated by commas. They allow duplicate elements and can be modified after
creation.

Key Features of Lists:

 Ordered: The items have a defined order, and that order will not change unless explicitly
modified.
 Mutable: You can change, add, or remove items after the list has been created.
 Dynamic: Lists can grow and shrink in size as needed.

Example of Finding the Intersection of Two Lists

The intersection of two lists is a new list that contains only the elements that are present in both
lists. Here's a Python program to find the intersection of two lists:

def list_intersection(list1, list2):


# Using set to find intersection
intersection = list(set(list1) & set(list2))
return intersection

# Example usage
list_a = [1, 2, 3, 4, 5]
list_b = [4, 5, 6, 7, 8]

result = list_intersection(list_a, list_b)


print("The intersection of the two lists is:", result)

Explanation of the Program:


1. Function Definition: The function list_intersection takes two lists as input.
2. Set Intersection: It converts both lists to sets and uses the & operator to find common elements.
The result is then converted back to a list.
3. Example Lists: Two example lists, list_a and list_b, are defined with some overlapping
elements.
4. Output: The program calls the list_intersection function and prints the result.

Output

When you run the program, the output will be:

The intersection of the two lists is: [4, 5]

8. Discuss the commonly used Tkinter widgets used with python programming.

Tkinter is the standard GUI (Graphical User Interface) toolkit for Python, providing a range of
widgets to create interactive applications. Here are some commonly used Tkinter widgets:

1. Label

 Description: Displays text or images that users cannot edit.


 Usage: Often used for titles, instructions, or to show static information.

label = [Link](root, text="Hello, Tkinter!")


[Link]()

2. Button

 Description: A clickable button that can trigger actions.


 Usage: Used for submitting forms, starting processes, or executing commands.

button = [Link](root, text="Click Me", command=my_function)


[Link]()

3. Entry

 Description: A single-line text input field.


 Usage: Used for user input, such as names, passwords, or search queries.

entry = [Link](root)
[Link]()

4. Text

 Description: A multi-line text input field.


 Usage: Used for larger amounts of text input, such as comments or messages.
text_area = [Link](root, height=5, width=40)
text_area.pack()

5. Checkbutton

 Description: A checkbox that allows users to select or deselect options.


 Usage: Used for settings or preferences where multiple selections are allowed.

var = [Link]()
checkbutton = [Link](root, text="Option 1", variable=var)
[Link]()

6. Radiobutton

 Description: A button that allows users to select one option from a set.
 Usage: Used when only one choice is allowed from multiple options.

var = [Link]()
radiobutton1 = [Link](root, text="Option A", variable=var, value="A")
radiobutton2 = [Link](root, text="Option B", variable=var, value="B")
[Link]()
[Link]()

7. Listbox

 Description: Displays a list of items from which users can select one or more.
 Usage: Used for selections from a predefined list.

listbox = [Link](root)
[Link](1, "Item 1")
[Link](2, "Item 2")
[Link]()

8. Menu

 Description: A menu bar with dropdown options.


 Usage: Used to create application menus, such as File, Edit, Help, etc.

menu = [Link](root)
[Link](menu=menu)
file_menu = [Link](menu)
menu.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="Open", command=open_file)

9. Frame

 Description: A container widget used to organize other widgets.


 Usage: Useful for grouping widgets and creating layouts.
frame = [Link](root)
[Link]()

10. Canvas

 Description: A widget for drawing shapes, images, or other complex layouts.


 Usage: Used for creating graphics or custom layouts.

canvas = [Link](root, width=200, height=200)


[Link]()
canvas.create_rectangle(50, 50, 150, 150, fill="blue")

You might also like