ans 10
10. Explain list operations (inserting, replacing, deleting, sorting, searching) with examples.
In Python, a list is a mutable, ordered collection of items. Because lists are mutable, we can
modify them using various built-in operations.
1. Inserting Elements
You can add elements to a list using several methods:
* append(): Adds an element to the end of the list.
* insert(index, value): Adds an element at a specific position.
* Example:
nums = [1, 2, 4]
[Link](5) # [1, 2, 4, 5]
[Link](2, 3) # [1, 2, 3, 4, 5]
2. Replacing Elements
Since lists are mutable, you can change the value of an item by referring to its index number.
* Example:
fruits = ["apple", "banana", "cherry"]
fruits[1] = "mango" # Replaces 'banana' with 'mango'
3. Deleting Elements
There are multiple ways to remove items from a list:
* remove(value): Removes the first occurrence of a specific value.
* pop(index): Removes and returns the element at the given index (defaults to the last item).
* del: A keyword used to delete an item at a specific index or delete the entire list.
* Example:
nums = [10, 20, 30, 40]
[Link](20) # [10, 30, 40]
[Link](1) # Removes 30; list is now [10, 40]
4. Sorting a List
Sorting arranges the elements in a specific order (ascending or descending).
* sort(): Sorts the list in place.
* Example:
letters = ['d', 'a', 'c', 'b']
[Link]() # ['a', 'b', 'c', 'd']
5. Searching a List
Searching involves finding the position or existence of an element.
* index(value): Returns the index of the first matched element.
* in operator: Checks if an element exists in the list.
* Example:
colors = ["red", "blue", "green"]
print([Link]("blue")) # Output: 1
print("red" in colors) # Output: True
Would you like me to move to Question 11: "Explain dictionary operations like adding, updating,
and deleting elements"?
11. Explain dictionary operations like adding, updating, and deleting elements with examples.
A dictionary in Python is an unordered collection of items where data is stored as key-value pairs.
Dictionaries are mutable, meaning we can modify their content after they are created.
1. Adding Elements
You can add a new item to a dictionary by using a new key and assigning a value to it.
* Syntax: dictionary_name[key] = value
* Example:
student = {"name": "Amit", "course": "BCA"}
student["age"] = 20 # Adding a new key-value pair
print(student)
# Output: {'name': 'Amit', 'course': 'BCA', 'age': 20}
2. Updating Elements
Updating is similar to adding; if the key already exists, the old value will be overwritten by the new
one. You can also use the update() method to merge another dictionary or key-value pairs into the
current one.
* Example:
student = {"name": "Amit", "age": 20}
student["age"] = 21 # Updating existing key 'age'
# Using update() method
[Link]({"city": "Bilaspur"})
print(student)
# Output: {'name': 'Amit', 'age': 21, 'city': 'Bilaspur'}
3. Deleting Elements
There are several ways to remove items from a dictionary:
* pop(key): Removes the item with the specified key name and returns the value.
* popitem(): Removes the last inserted item.
* del: This keyword removes the item with the specified key or can delete the entire dictionary.
* clear(): Empties the entire dictionary.
* Example:
data = {"brand": "Ford", "model": "Mustang", "year": 1964}
[Link]("model") # Removes 'model'
del data["year"] # Removes 'year'
print(data) # Output: {'brand': 'Ford'}
[Link]() # Dictionary is now empty: {}
Would you like me to move to Question 12: "Differentiate between lists, tuples, and dictionaries
with examples"?
12. Differentiate between lists, tuples, and dictionaries with examples.
In Python, lists, tuples, and dictionaries are the three most commonly used data structures. While
they all store collections of data, they differ significantly in terms of syntax, mutability, and usage.
Comparison Table
| Feature | List | Tuple | Dictionary |
|---|---|---|---|
| Syntax | Enclosed in square brackets []. | Enclosed in parentheses (). | Enclosed in curly braces
{}. |
| Mutability | Mutable (Can be changed). | Immutable (Cannot be changed). | Mutable (Values can
be changed). |
| Ordering | Ordered collection. | Ordered collection. | Unordered (indexed by keys). |
| Duplicates | Allows duplicate elements. | Allows duplicate elements. | Keys must be unique;
values can duplicate. |
| Access | Accessed via index (e.g., [0]). | Accessed via index (e.g., [0]). | Accessed via keys (e.g.,
['key']). |
1. List Example
Lists are best used when you have a collection of similar items that may need to be modified
(added to or sorted) later.
my_list = ["Apple", "Banana", "Cherry"]
my_list[1] = "Mango" # Modification is allowed
print(my_list) # Output: ['Apple', 'Mango', 'Cherry']
2. Tuple Example
Tuples are used for data that should not change throughout the life of the program, such as
coordinates or fixed configuration settings.
my_tuple = (10, 20, 30)
# my_tuple[0] = 50 # This would raise a TypeError
print(my_tuple[0]) # Output: 10
3. Dictionary Example
Dictionaries are ideal for representing real-world objects where you want to associate a specific
label (key) with a piece of data (value).
my_dict = {"Brand": "Ford", "Model": "Mustang", "Year": 1964}
print(my_dict["Model"]) # Output: Mustang
Would you like me to proceed with Question 13: "Explain exception handling in Python with syntax
and examples"?
13. Explain exception handling in Python with syntax and examples.
Exception handling is a mechanism in Python to handle runtime errors, preventing the program
from crashing. An exception is an event that occurs during the execution of a program that
disrupts the normal flow of instructions.
Syntax of Exception Handling
Python uses a try-except block to handle exceptions:
* try block: Contains the code that might raise an exception.
* except block: Contains the code that executes if an exception occurs in the try block.
* else block (optional): Executes if no exceptions are raised.
* finally block (optional): Executes no matter what, used for cleanup actions (like closing files).
Example 1: Basic Exception Handling
This example handles a division by zero error.
try:
num1 = 10
num2 = 0
result = num1 / num2 # This will raise ZeroDivisionError
print(result)
except ZeroDivisionError:
[span_6](start_span)print("Error: Cannot divide by zero!")[span_6](end_span)
Example 2: Handling Multiple Exceptions
You can specify different except blocks to handle specific types of errors.
try:
value = int(input("Enter a number: "))
result = 100 / value
except ValueError:
[span_7](start_span)print("Error: Please enter a valid integer.")[span_7](end_span)
except ZeroDivisionError:
[span_8](start_span)print("Error: Division by zero is not allowed.")[span_8](end_span)
Example 3: Using finally
The finally block is often used to ensure resources are released.
try:
file = open("[Link]", "r")
# perform file operations
except FileNotFoundError:
[span_9](start_span)print("Error: File not found.")[span_9](end_span)
finally:
[span_10](start_span)print("Execution complete. Cleaning up
resources...")[span_10](end_span)
Would you like me to move to Question 14: "Write short notes on Math module and Random
module with examples"?
14. Write short notes on Math module and Random module with examples.
In Python, modules are files containing Python code (functions, variables, etc.) that can be
imported into your program to perform specific tasks.
1. Math Module
The math module provides access to mathematical functions defined by the C standard. It is used
for performing complex mathematical operations like trigonometry, logarithms, and power
functions.
Common Functions:
* [Link](x): Returns the square root of x.
* [Link](x, y): Returns x raised to the power of y.
* [Link](x): Rounds a number up to the nearest integer.
* [Link](x): Rounds a number down to the nearest integer.
* [Link]: A constant that returns the value of \pi (approx. 3.14159).
Example:
import math
print([Link](16)) # Output: 4.0
print([Link](4.2)) # Output: 5
print([Link]) # Output: 3.141592653589793
2. Random Module
The random module is used to generate pseudo-random numbers for various purposes, such as
games, simulations, or testing.
Common Functions:
* [Link](): Returns a random float between 0.0 and 1.0.
* [Link](a, b): Returns a random integer between a and b (inclusive).
* [Link](sequence): Returns a randomly selected element from a non-empty sequence
like a list or string.
* [Link](list): Reorders the elements of a list in place randomly.
Example:
import random
print([Link](1, 100)) # Output: (Any integer between 1 and 100)
fruits = ["Apple", "Banana", "Cherry"]
print([Link](fruits)) # Output: (A random fruit from the list)
Would you like me to complete the final task, Question 15: "What are user-defined exceptions and
how to demonstrate custom exception handling"?
15. What are user-defined exceptions? Write a program to demonstrate custom exception
handling.
In Python, user-defined exceptions (also known as custom exceptions) are exceptions created by
the programmer to handle specific error scenarios that are not covered by standard built-in
exceptions like ValueError or TypeError.
Concept of User-Defined Exceptions
* Custom exceptions are created by defining a new class that inherits from the built-in Exception
class or one of its subclasses.
* They allow developers to provide more meaningful error messages and specific handling logic
tailored to their application's needs.
* They are triggered using the raise keyword when a specific condition in the program is met.
Program to Demonstrate Custom Exception Handling
The following program defines an exception called InvalidAgeException which is raised if a user
attempts to register with an age less than 18.
# Step 1: Define the custom exception class
class InvalidAgeException(Exception):
"""Exception raised for errors in the input age."""
def __init__(self, age, message="Age must be 18 or older to register"):
[Link] = age
[Link] = message
super().__init__([Link])
# Step 2: Function that raises the custom exception
def register_user(age):
if age < 18:
# Step 3: Use the 'raise' keyword to trigger the exception
raise InvalidAgeException(age)
else:
print("Registration successful!")
# Step 4: Demonstrate handling the custom exception
try:
user_age = int(input("Enter your age: "))
register_user(user_age)
except InvalidAgeException as e:
print(f"Error occurred: {[Link]} (Provided age: {[Link]})")
except ValueError:
print("Please enter a valid numeric value for age.")
How it works:
* Inheritance: The InvalidAgeException class inherits from Exception, making it a valid exception
type.
* Raising: Inside the register_user function, we check a condition. If the age is invalid, the raise
statement stops the normal execution and sends the error to the except block.
* Handling: The try-except block catches the specific InvalidAgeException and prints a user-
friendly message instead of the program crashing.
This completes all 15 questions for your Python assignment. Is there anything else you would like
me to help you with?