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

Python Data Structures and Exception Handling

The document contains questions and answers related to Python programming, covering topics such as dictionaries, sets, modules, exceptions, and error handling. It includes definitions, comparisons, and example programs for practical understanding. The content is structured in a question-answer format, suitable for educational purposes.

Uploaded by

rehanboiizzz
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)
9 views7 pages

Python Data Structures and Exception Handling

The document contains questions and answers related to Python programming, covering topics such as dictionaries, sets, modules, exceptions, and error handling. It includes definitions, comparisons, and example programs for practical understanding. The content is structured in a question-answer format, suitable for educational purposes.

Uploaded by

rehanboiizzz
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

Que.

[Link] a dictionary in python show how to create a dictionary. 2marks

[Link] tuple/list/set/dictionary in python. 3marks

Or

2. explain mathematical operations on set. 3marks

[Link] a programme to check if a key is exist in a dictionary? 5marks

Or

[Link] use of add( ),update( ),and extend( ),discord( ) method of set. 5marks

Que.2

[Link] module in python, how to create module? 2marks

[Link] how to import a module in python program with example. 3marks

Or

[Link] os module. 3marks

[Link] a program to create package and import package. 6marks

Que.3

[Link] exception, show how it is different from error. 2marks

[Link] the use of “try-except” block with syntax and example. 2marks

[Link] a python program to handle division by zero exception. 5marks

Or

[Link] a python program to implement user-defined exception. 5marks


Que.1

1. Define a dictionary in python show how to create a dictionary. (2 Marks)

A dictionary in Python is an unordered collection of data values used to store data values like
a map. It consists of key-value pairs where each key is unique.

Example:

python
CopyEdit
my_dict = {
"name": "Alice",
"age": 25,
"city": "New York"
}

Here, "name", "age", and "city" are keys, and their corresponding values are "Alice", 25,
and "New York".

2. Compare tuple/list/set/dictionary in python. (3 Marks)

Feature Tuple List Set Dictionary


Syntax () [] {} {key: value}
Ordered Yes Yes No Yes (as of Python 3.7)
Mutable No Yes Yes Yes
Duplicate Allowed Allowed Not allowed Keys not duplicated
Access Index-based Index-based Not indexable Key-based access

Each structure serves a specific use case in data handling.

OR - Explain mathematical operations on set. (3 Marks)

Python sets support various mathematical operations like union, intersection, difference, and
symmetric difference:

python
CopyEdit
A = {1, 2, 3}
B = {3, 4, 5}

print(A | B) # Union: {1, 2, 3, 4, 5}


print(A & B) # Intersection: {3}
print(A - B) # Difference: {1, 2}
print(A ^ B) # Symmetric Difference: {1, 2, 4, 5}

These operations help in solving problems involving group memberships or filtering data
efficiently.
3. Develop a program to check if a key exists in a dictionary? (5 Marks)

python
CopyEdit
# Python program to check if a key exists in a dictionary

my_dict = {
"name": "John",
"age": 30,
"city": "Delhi"
}

key_to_check = "age"

if key_to_check in my_dict:
print(f"Key '{key_to_check}' exists with value:
{my_dict[key_to_check]}")
else:
print(f"Key '{key_to_check}' does not exist.")

Output:

sql
CopyEdit
Key 'age' exists with value: 30

The in operator checks if the key is part of the dictionary.

OR - Make use of add( ), update( ), and extend( ), discard( ) method of set. (5 Marks)

Note: extend() is not used with sets, only add(), update(), and discard() apply.

python
CopyEdit
# Set operations
A = {1, 2, 3}
[Link](4) # Adds a single element
[Link]([5, 6]) # Adds multiple elements from a list
[Link](2) # Removes element if present

print("Updated Set:", A)

Output:

css
CopyEdit
Updated Set: {1, 3, 4, 5, 6}

Here, add() inserts an element, update() merges iterable elements, and discard() removes
an element safely.
Que.2

1. Define module in python, how to create module? (2 Marks)

A module in Python is a file containing Python code such as functions, classes, or variables
which can be reused in other programs.

Creating a module: Create a Python file, e.g., my_module.py:

python
CopyEdit
def greet(name):
return f"Hello, {name}"

This file can be imported in other Python files to use the greet() function.

2. Explain how to import a module in python program with example. (3 Marks)

Modules can be imported using the import keyword in Python.

Example:

python
CopyEdit
import math

print([Link](16)) # Output: 4.0

You can also import specific functions:

python
CopyEdit
from math import pow
print(pow(2, 3)) # Output: 8.0

Modules help reuse code and maintain program structure.

OR - Explain os module. (3 Marks)

The os module in Python provides functions to interact with the operating system.

Common functions:

python
CopyEdit
import os

print([Link]) # Returns OS name


print([Link]()) # Gets current directory
[Link]("new_folder") # Creates new directory

It’s useful for file handling, directory navigation, and process management.

3. Develop a program to create package and import package. (6 Marks)

Step 1: Create a Package Folder Structure

markdown
CopyEdit
my_package/
__init__.py
[Link]

[Link]

python
CopyEdit
def add(a, b):
return a + b

Main Program ([Link]):

python
CopyEdit
from my_package import module1

result = [Link](10, 5)
print("Addition:", result)

Output:

makefile
CopyEdit
Addition: 15

Que.3

1. Define exception, show how it is different from error. (2 Marks)

An exception in Python is an event that occurs during program execution and disrupts the normal
flow of instructions. It is usually caused by logical errors.

Difference from error:

 Errors are serious problems that a program cannot handle (e.g., syntax errors).
 Exceptions can be handled using try-except blocks.

Example: ZeroDivisionError is an exception, while IndentationError is an error.


2. Explain the use of “try-except” block with syntax and example. (2 Marks)

The try-except block is used to catch and handle exceptions in Python.

Syntax:

python
CopyEdit
try:
# Code that may raise an exception
except ExceptionType:
# Code to handle the exception

Example:

python
CopyEdit
try:
x = 5 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")

3. Develop a Python program to handle division by zero exception. (5 Marks)

python
CopyEdit
# Division by zero exception handling

try:
a = int(input("Enter numerator: "))
b = int(input("Enter denominator: "))
result = a / b
print("Result:", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except ValueError:
print("Error: Invalid input.")

Output Example:

yaml
CopyEdit
Enter numerator: 10
Enter denominator: 0
Error: Cannot divide by zero.

This prevents the program from crashing when a zero denominator is entered.

OR - Develop a Python program to implement user-defined exception. (5 Marks)

python
CopyEdit
# User-defined exception example

class AgeTooSmallError(Exception):
pass

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

try:
if age < 18:
raise AgeTooSmallError
else:
print("You are eligible to vote.")
except AgeTooSmallError:
print("Error: Age is too small to vote.")

Output Example:

vbnet
CopyEdit
Enter your age: 16
Error: Age is too small to vote.

User-defined exceptions are created by extending the Exception class and used to handle custom
error conditions.

Common questions

Powered by AI

To safely execute division with exception handling in Python, you can use: `try: a = int(input("Enter numerator: ")) b = int(input("Enter denominator: ")) result = a / b print("Result:", result) except ZeroDivisionError: print("Error: Cannot divide by zero.") except ValueError: print("Error: Invalid input.")`. This program prevents crashes from invalid input types or zero division by handling exceptions explicitly .

A Python dictionary is defined as an unordered collection of data values used to store data values like a map. It consists of key-value pairs where each key is unique. A dictionary can be created using curly braces `{}` with keys and values. For example, `my_dict = { "name": "Alice", "age": 25, "city": "New York" }`. Here, "name", "age", and "city" are keys with corresponding values "Alice", 25, and "New York" .

To create a package in Python, organize files into a directory with an `__init__.py` file. For example, `my_package/` containing `__init__.py` and `module1.py` with content `def add(a, b): return a + b`. A main program (`main.py`) imports this package using `from my_package import module1` and can then utilize `module1.add(10, 5)`, resulting in `Addition: 15`. This structure allows for modular, maintainable, and reusable code .

The `os` module in Python provides various functions that allow interaction with the operating system. It is used for file handling, directory management, and process management. Functions include `os.name` to return the name of the operating system, `os.getcwd()` to get the current working directory, and `os.mkdir("new_folder")` to create a new directory. These functionalities are critical for applications needing to manage system resources and environments efficiently .

A Python program to check if a key exists in a dictionary uses the `in` operator. For example: `my_dict = { "name": "John", "age": 30, "city": "Delhi" }`. Using `key_to_check = "age"`, you can check its existence with `if key_to_check in my_dict`. If it exists, the program could output: `Key 'age' exists with value: 30` .

In Python, exceptions are events that occur during program execution that disrupt the normal flow of instructions, typically caused by logical errors. Errors, on the other hand, are serious problems that a program cannot handle such as syntax errors. Exceptions can be managed using try-except blocks which handle exceptions gracefully without crashing the program. For instance, `try: x = 5 / 0 except ZeroDivisionError: print("Cannot divide by zero.")` prevents termination upon encountering a division by zero exception .

Python sets support mathematical operations like union, intersection, difference, and symmetric difference. Union (`|`) combines elements from both sets, intersection (`&`) finds common elements, difference (`-`) identifies elements in one set but not the other, and symmetric difference (`^`) identifies elements that are in either of the sets but not in both. These operations are helpful for tasks involving group memberships or filtering data efficiently .

Tuples, lists, sets, and dictionaries in Python differ primarily in their syntax, order preservation, mutability, and whether duplicates are allowed. Tuples use `()` and are ordered and immutable, allowing duplicates. Lists use `[]`, are ordered, and mutable, also allowing duplicates. Sets use `{}` and are unordered, mutable, and do not allow duplicates. Dictionaries use `{key: value}` format, are ordered as of Python 3.7, mutable, and do not allow duplicated keys, with access based on key-value pairs .

Modules in Python enhance code reusability and maintenance by encapsulating functionalities such as functions, classes, and variables into a single file that can be imported and used in other programs. To create a module, write Python code in a file, such as `my_module.py` containing `def greet(name): return f"Hello, {name}"`. This module can be imported using `import my_module` in other scripts to call `my_module.greet("World")`, thus reusing the `greet` function efficiently .

User-defined exceptions in Python are custom exceptions created by extending the base Exception class, allowing for handling specific conditions unique to a program's logic. For example, `class AgeTooSmallError(Exception): pass` defines a new exception. A program can raise this exception with: `age = int(input("Enter your age: ")) if age < 18: raise AgeTooSmallError else: print("You are eligible to vote.") except AgeTooSmallError: print("Error: Age is too small to vote.")`, allowing controlled responses to invalid ages .

You might also like