Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

python question and answers

The document provides an overview of Python programming concepts, including list comprehension, dictionary access methods, key-value pairs, parameters in functions, recursive and lambda functions, and examples of function definitions. It explains how to create and manipulate dictionaries, the properties of keys, and the types of parameters in functions. Additionally, it includes code examples for counting uppercase and lowercase letters in a string and removing duplicates from a list.

Uploaded by

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

python question and answers

The document provides an overview of Python programming concepts, including list comprehension, dictionary access methods, key-value pairs, parameters in functions, recursive and lambda functions, and examples of function definitions. It explains how to create and manipulate dictionaries, the properties of keys, and the types of parameters in functions. Additionally, it includes code examples for counting uppercase and lowercase letters in a string and removing duplicates from a list.

Uploaded by

228w1f0045
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

UNIT III QUESTION AND ANSWERS

1. Create a list using list comprehension. Advantage of list comprehension?

List comprehension is a concise way to create lists in Python. It allows you to


generate lists using a single line of code, combining a for loop and an optional if condition.
The basic syntax of list comprehension is:
[expression for item in iterable if condition]
expression is the operation you want to perform on each item.
item is the variable representing each element in the iterable (e.g., a list, tuple, or range).
iterable is the sequence of elements you want to iterate over.
condition (optional) is a filter that allows you to include only certain items that meet a
specified criterion.

Here's an example of list comprehension that creates a list of squares of even numbers from 1
to 10:

# Creating a list of squares of numbers from 1 to 10


squares = [x**2 for x in range(1, 11)]
print(squares)

output
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
The advantage of using list comprehension is that it provides a concise and readable way to
create lists in Python. It allows you to write compact code without sacrificing readability. List
comprehension is often faster than traditional looping techniques (like using for loops)
because it is optimized for the Python interpreter. Additionally, it encourages a functional
programming style, which can lead to more elegant and efficient code.

2. How can you access elements from the dictionary?

Different ways to access elements from a dictionary:


Using Square Brackets: You can access the value associated with a key by using square
brackets [ ] with the key inside.
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
# Accessing value using key
print(my_dict['name']) # Output: John
print(my_dict['age']) # Output: 30

Using the get() Method: You can also use the get() method, which returns the value for the
specified key. If the key is not found, it returns None by default, but you can specify a default
value to return instead.
# Using get() method
print(my_dict.get('city')) # Output: New York
print(my_dict.get('occupation')) # Output: None
print(my_dict.get('occupation', 'Not specified')) # Output: Not specified
Iterating Over Keys: You can iterate over the keys of the dictionary and access the
corresponding values.
# Iterating over keys
for key in my_dict:
print(key, "->", my_dict[key])
Using the keys() Method: You can use the keys() method to get a view object that displays a
list of all the keys in the dictionary.
# Using keys() method
print(my_dict.keys()) # Output: dict_keys(['name', 'age', 'city'])
Using the items() Method: You can use the items() method to get a view object that displays
a list of tuples, where each tuple contains a key-value pair.
# Using items() method
print(my_dict.items()) # Output: dict_items([('name', 'John'), ('age', 30), ('city', 'New
York')])

3. Define properties of key in dictionary. How can you access elements from the
dictionary.

The properties of keys in a dictionary in Python are:

Unique: Keys within a dictionary must be unique. This means that no two keys can have the
same name or value.
Immutable: Keys must be immutable objects. This means that you can use immutable data
types like strings, numbers, or tuples (if they contain only immutable elements) as keys.
However, mutable objects like lists cannot be used as keys.

To access elements from a dictionary, you can use the methods mentioned in the previous
response:

Using Square Brackets: Access elements by specifying the key within square brackets.
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
print(my_dict['name']) # Output: John

Using the get() Method: Access elements using the get() method, which returns the value for
the specified key.
# Using get() method
print(my_dict.get('city')) # Output: New York
print(my_dict.get('occupation')) # Output: None
print(my_dict.get('occupation', 'Not specified')) # Output: Not specified
Iterating Over Keys: You can iterate over the keys of the dictionary and access the
corresponding values.
# Iterating over keys
for key in my_dict:
print(key, "->", my_dict[key])
Using the keys() Method: You can use the keys() method to get a view object that displays a
list of all the keys in the dictionary.
# Using keys() method
print(my_dict.keys()) # Output: dict_keys(['name', 'age', 'city'])
Using the items() Method: You can use the items() method to get a view object that displays
a list of tuples, where each tuple contains a key-value pair.
# Using items() method
print(my_dict.items()) # Output: dict_items([('name', 'John'), ('age', 30), ('city', 'New
York')])

4. Explain key value pair? Mention different data types can be used in key and
value?
A key-value pair is a fundamental concept in dictionaries, which are a data structure used in
Python and many other programming languages. In a key-value pair, a key is associated with
a value. When you need to store and retrieve data based on some identifier (the key),
dictionaries provide an efficient way to do so.

In Python dictionaries, each key is associated with a single value, forming a unique pair.
Here's a basic example:
my_dict = {'name': 'John', 'age': 30}
In this dictionary:

'name' is a key.
'John' is the value associated with the key 'name'.
'age' is another key.
30 is the value associated with the key 'age'.
Keys can be of any immutable data type, such as:

Strings
Numbers (integers, floats)
Tuples (if they contain only immutable elements)
Values can be of any data type, including:

Strings
Numbers
Lists
Tuples
Dictionaries (nested dictionaries)
Here's an example showing different data types used as keys and values:

my_dict = {'name': 'John', 'age': 30, (1, 2): 'tuple_key', 3.14: 'pi', True: 'boolean', 'info': {'city':
'New York', 'country': 'USA'}}

In this dictionary:

'name', 'age', (1, 2), 3.14, True, and 'info' are keys.
'John', 30, 'tuple_key', 'pi', 'boolean', and {'city': 'New York', 'country': 'USA'} are the
corresponding values.

5. What is parameter and types of parameter? How can you insert values in to
dictionary?
a parameter is a variable that is used in a function definition to represent some value that will
be provided when the function is called. Parameters allow functions to accept input and
perform operations on that input.
Types of Parameters:
Positional Parameters: These are parameters that are passed to a function in a specific
order. The function receives the values in the order they are passed.
Example:
def greet(name, age):
print(f"Hello, {name}! You are {age} years old.")

greet("Alice", 25) # Output: Hello, Alice! You are 25 years old.


Keyword Parameters: These are parameters preceded by an identifier (keyword) when
calling a function. This allows you to pass values to a function in any order by specifying the
parameter name.
Example:
def greet(name, age):
print(f"Hello, {name}! You are {age} years old.")

greet(age=30, name="Bob") # Output: Hello, Bob! You are 30 years old.


Default Parameters: These are parameters that have default values specified in the function
definition. If no value is provided when calling the function, the default value is used.
Example:
def greet(name="Guest", age=18):
print(f"Hello, {name}! You are {age} years old.")

greet() # Output: Hello, Guest! You are 18 years old.


Variable-Length Parameters: These parameters allow you to pass a variable number of
arguments to a function. There are two types:
Arbitrary Positional Parameters: They are denoted by an asterisk * before the parameter name
and allow you to pass any number of positional arguments.
Arbitrary Keyword Parameters: They are denoted by two asterisks ** before the parameter
name and allow you to pass any number of keyword arguments.
Example:
def greet(*names):
for name in names:
print(f"Hello, {name}!")

greet("Alice", "Bob", "Charlie") # Output: Hello, Alice! Hello, Bob! Hello, Charlie!

To insert values into a dictionary in Python, you can assign values to specific keys using
square brackets [ ].
my_dict = {} # Create an empty dictionary

# Insert values into the dictionary


my_dict['name'] = 'John'
my_dict['age'] = 30

print(my_dict) # Output: {'name': 'John', 'age': 30}

Also create a dictionary with initial values using curly braces {}:
my_dict = {'name': 'John', 'age': 30}

update an existing dictionary with new key-value pairs:


my_dict.update({'city': 'New York', 'country': 'USA'})

6. Mention different data types can be used in key and value.


In Python dictionaries, keys can be of any immutable data type, while values can be
of any data type, including immutable and mutable types. Here's a list of different
data types that can be used as keys and values in dictionaries:

Keys:

Strings
Integers
Floats
Tuples (if they contain only immutable elements)
Boolean values
Custom objects (if they are hashable)
Values:

Strings
Integers
Floats
Tuples
Lists
Dictionaries (nested dictionaries)
Sets
Boolean values
None (null)
It's important to note that while keys must be of immutable types, values can be of
both immutable and mutable types. Mutable types like lists and dictionaries can be
used as values in a dictionary, allowing for flexible data structures. However, using
mutable types as keys is not allowed because keys need to be hashable for efficient
lookup operations.

Here's an example illustrating different data types used as keys and values in a dictionary:

my_dict = {
'name': 'John', # String key, string value
42: 'answer', # Integer key, string value
3.14: 'pi', # Float key, string value
('apple', 'banana'): 2, # Tuple key, integer value
True: 'boolean', # Boolean key, string value
None: [1, 2, 3], # None key, list value
'info': {'city': 'New York', 'population': 8.4}, # String key, nested dictionary value
}

print(my_dict)
This dictionary demonstrates the variety of data types that can be used as keys and values,
showcasing the flexibility and power of Python dictionaries.
UNIT – IV QUESTION AND ANSWERS

1. Explain Recursive function and lambda function?

Recursive Function: A recursive function is a function that calls itself during its execution.
This technique is used to solve problems that can be broken down into smaller, similar sub-
problems. Recursive functions typically have two parts:
Base Case: This is the termination condition that prevents the function from making further
recursive calls. It defines the simplest possible case and allows the recursion to stop.
Recursive Case: This is where the function calls itself with modified arguments to solve a
smaller sub-problem. This step is repeated until the base case is reached.
Here's an example of a recursive function to calculate the factorial of a non-negative integer:
def factorial(n):
# Base case
if n == 0:
return 1
# Recursive case
else:
return n * factorial(n - 1)

# Test the function


print(factorial(5)) # Output: 120 (5! = 5 * 4 * 3 * 2 * 1 = 120)

Recursive functions can be elegant and concise, but they can also be less efficient and
consume more memory compared to iterative solutions. However, they are often used in
situations where the problem naturally lends itself to recursive thinking.

Lambda Function:
A lambda function, also known as an anonymous function, is a small, unnamed function
defined using the lambda keyword. Lambda functions can have any number of parameters but
can only contain a single expression. They are typically used when you need a simple
function for a short period of time and don't want to define a full-fledged function using the
def keyword.

Here's the syntax of a lambda function:


lambda arguments: expression
Lambda functions are often used in conjunction with functions like map(), filter(), and
reduce() or as arguments to higher-order functions. They are particularly useful in situations
where you need to pass a simple function as an argument.

Here's an example of a lambda function that adds two numbers:


add = lambda x, y: x + y
print(add(3, 5)) # Output: 8
Lambda functions can make your code more concise and readable, especially when used
appropriately in situations where a named function would be overkill. However, they can also
make code harder to understand if overused or if the expressions become too complex.

2. Create a Python function that accepts a string and counts the number of upper
and lower case letters with flow chart.
Python function that accepts a string and counts the number of uppercase and lowercase
letters, along with a flowchart illustrating its logic:
def count_upper_lower(text):
upper_count = 0
lower_count = 0

for char in text:


if char.isupper():
upper_count += 1
elif char.islower():
lower_count += 1

return upper_count, lower_count

# Test the function


text = "Hello World"
upper_count, lower_count = count_upper_lower(text)
print("Number of uppercase letters:", upper_count)
print("Number of lowercase letters:", lower_count)

Flow Chart:

3. Define function? Write its syntax? What are formal and actual arguments?
A function is a block of organized, reusable code that performs a specific task. It groups
together a set of statements so that they can be run more than once in a program without
having to rewrite the code each time. Functions help to modularize code, making it more
organized, readable, and maintainable.

In Python, functions are defined using the def keyword followed by the function name and a
set of parentheses containing zero or more parameters. The function body is then indented
and contains the code to be executed when the function is called.

Here's the syntax for defining a function in Python:

def function_name(parameters):
"""Optional docstring"""
# Function body
# Statements to be executed
return [expression] # Optional return statement

def: Keyword used to define a function.


function_name: Name of the function, which should be descriptive and follow Python's
naming conventions.
parameters: Optional list of parameters (inputs) that the function takes. Parameters are
separated by commas and can be empty if the function doesn't require any inputs.
"""Optional docstring""": Optional documentation string (docstring) that describes what the
function does. It's good practice to include docstrings to document your code.
Function body: Block of statements to be executed when the function is called. It must be
indented.
return [expression]: Optional return statement that specifies the value(s) that the function
returns when it's called. If omitted, the function returns None by default.

Formal and Actual arguments:

Formal Arguments: These are the parameters defined in the function signature. They act as
placeholders for the values that will be passed to the function when it's called. Formal
arguments are used within the function's body to perform operations.
Actual Arguments: Also known as arguments or parameters, these are the actual values
passed to the function when it's called. They correspond to the formal arguments defined in
the function signature. Actual arguments can be literals, variables, expressions, or even other
function calls.

Here's an example illustrating formal and actual arguments:


def greet(name):
"""Function that greets a person"""
print(f"Hello, {name}!")

# 'name' is a formal argument


# 'Alice' is an actual argument
greet('Alice') # Output: Hello, Alice!

In this example, 'Alice' is the actual argument passed to the function greet(), and name is the
formal argument that receives this value within the function's body.
4. Write a Python function that takes a list and returns a new list with distinct
elements from the first list with flow chart also.

Python function that takes a list and returns a new list with distinct elements (i.e., removing
duplicates), along with a flowchart illustrating its logic:
def remove_duplicates(input_list):
distinct_elements = []

for item in input_list:


if item not in distinct_elements:
distinct_elements.append(item)

return distinct_elements

# Test the function


my_list = [1, 2, 3, 3, 4, 4, 5]
result = remove_duplicates(my_list)
print("Original List:", my_list)
print("List with Distinct Elements:", result)

5. Differentiate global and local variables. Illustrate types of inheritance with


python code.

Global and local variables are two types of variables in Python, each with its own scope and
accessibility within a program.

Global Variables:
Scope: Global variables are defined outside of any function or class and can be accessed from
anywhere within the program, including inside functions and classes.
Accessibility: They can be accessed from any part of the program, including inside functions
and classes.
Lifetime: Global variables persist throughout the entire execution of the program.
Example:
global_var = 10

def my_function():
print("Value of global_var inside function:", global_var)

my_function() # Output: Value of global_var inside function: 10


print("Value of global_var outside function:", global_var) # Output: Value of global_var
outside function: 10

Local Variables:
Scope: Local variables are defined within a function or method and can only be accessed
from within that function or method.
Accessibility: They are accessible only within the function or method where they are defined.
Lifetime: Local variables exist only as long as the function or method is executing.
Example:
def my_function():
local_var = 20
print("Value of local_var inside function:", local_var)

my_function() # Output: Value of local_var inside function: 20


# print(local_var) # This would raise a NameError: name 'local_var' is not defined

Types of Inheritance in Python:


Inheritance in Python allows a class (subclass) to inherit attributes and methods from another
class (superclass). There are different types of inheritance:

Single Inheritance: A subclass inherits from only one superclass.


Multiple Inheritances: A subclass inherits from multiple super classes.
Multilevel Inheritance: A subclass inherits from a superclass, and another subclass inherits
from the first subclass, forming a chain of inheritance.
Hierarchical Inheritance: Multiple subclasses inherit from a single superclass.
Hybrid (or Mixin) Inheritance: Combination of multiple inheritance types.

Here's an example illustrating single and multiple inheritances in Python:


# Single Inheritance
class Animal:
def sound(self):
print("Animal makes a sound")

class Dog(Animal):
def sound(self):
print("Dog barks")

# Multiple Inheritance
class Parent1:
def method1(self):
print("Method from Parent1")

class Parent2:
def method2(self):
print("Method from Parent2")

class Child(Parent1, Parent2):


pass

# Test the classes


dog = Dog()
dog.sound() # Output: Dog barks

child = Child()
child.method1() # Output: Method from Parent1
child.method2() # Output: Method from Parent2
In the single inheritance example, the class Dog inherits from the class Animal, while in the
multiple inheritance example, the class Child inherits from both Parent1 and Parent2.

6. Write about different filter functions in Python?

In Python, the filter() function is used to filter elements from an iterable (such as a list, tuple,
or set) based on a given condition. It takes two arguments: a function and an iterable. The
function passed to filter() must return a boolean value (True or False), indicating whether the
element should be included in the filtered result.

There are different ways to use the filter() function in Python:

Using a Function: You can define a separate function and pass it to filter().
def is_even(num):
return num % 2 == 0

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


even_numbers = list(filter(is_even, numbers))
print(even_numbers) # Output: [2, 4, 6, 8, 10]

Using Lambda Function: You can use a lambda function directly as the first argument to
filter().
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4, 6, 8, 10]

Filtering None Values: You can use filter() to remove None values from a list.
items = [1, None, 3, None, 5, None, 7]
filtered_items = list(filter(None, items))
print(filtered_items) # Output: [1, 3, 5, 7]

Filtering Based on Length: You can filter elements based on their length, for example,
filtering out empty strings.
strings = ["", "hello", "", "world", "", "python"]
non_empty_strings = list(filter(lambda x: len(x) > 0, strings))
print(non_empty_strings) # Output: ['hello', 'world', 'python']

Filtering Based on Custom Conditions: You can filter elements based on any custom
condition.
ages = [25, 17, 30, 16, 21, 18, 35]
adults = list(filter(lambda age: age >= 18, ages))
print(adults) # Output: [25, 30, 21, 18, 35]

The filter() function returns an iterator, so you need to convert it to a list (or tuple, set, etc.) to
view the filtered elements. It's a powerful tool for selectively extracting elements from
iterables based on specific criteria.
UNIT – V QUESTION AND ANSWERS

1. List some few common Exception types and explain when they occur. How to
create user defined exception in python with an example.
Common exception types in Python:
SyntaxError: This occurs when the Python parser encounters a syntax error, such as a
missing colon at the end of a statement or an invalid indentation.
Example:
# Missing colon
if True
print("Hello")

Indentation Error: This occurs when there is an incorrect indentation in the code, such as
mixing tabs and spaces or inconsistent indentation levels.
Example:
def my_function():
print("Indented incorrectly")

NameError: This occurs when a name (variable, function, etc.) is not found in the local or
global scope.
Example:
print(unknown_variable)

TypeError: This occurs when an operation or function is applied to an object of


inappropriate type.
Example:
x = 5 + "hello"

ValueError: This occurs when a built-in operation or function receives an argument with the
right type but an inappropriate value.
Example:
x = int("hello")

IndexError: This occurs when trying to access an index that does not exist in a sequence
(e.g., list, tuple, string).
Example:
my_list = [1, 2, 3]
print(my_list[3])

User-defined Exception in Python:


You can create your own custom exceptions in Python by sub classing the built-in Exception
class. This allows you to define custom exception types tailored to your specific application
or use case.
An example of how to create a custom exception called InvalidAgeError, which is raised
when an invalid age is provided:
class InvalidAgeError(Exception):
"""Exception raised for invalid age."""
def __init__(self, age):
self.age = age
super().__init__(f"Invalid age: {age}")

def validate_age(age):
if age < 0 or age > 120:
raise InvalidAgeError(age)
else:
print("Valid age")

# Test the custom exception


try:
validate_age(150)
except InvalidAgeError as e:
print(e)

In this example:
A custom exception class InvalidAgeError that inherits from the built-in Exception class is
defined.
Override the __init__ method to customize the exception message.
A function validate_age() that raises InvalidAgeError if the age is not within the valid range
is defined.
Tested the custom exception by calling validate_age() with an invalid age and catching the
InvalidAgeError exception. If the age is invalid, the exception is raised, and its message is
printed.

2. Write a Python program to construct a seeded random number generator, also


generate a float between 0 and 1, excluding 1. Use random. Random () with flowchart.

To create a seeded random number generator and generate a float between 0 and 1 (excluding
1) in Python using the random. random() function,
import random

def seeded_random(seed):
random.seed(seed)

def generate_random_float():
return random.random()

# Set the seed for reproducibility


seeded_random(123)

# Generate a random float between 0 and 1 (excluding 1)


random_float = generate_random_float()

print("Random float between 0 and 1 (excluding 1):", random_float)


Start of Program

Import random module

Define seeded_random () function

Construct seeded random number


generator with given seed value

Generate random float between 0 and 1


(excluding 1)

Print random float between 0 and 1

End of Program

3. Explain from import statement in modules?

In Python, the from ... import ... statement is used to import specific attributes (functions,
variables, classes, etc.) from a module into the current namespace. It provides a way to
selectively import only the desired components from a module, rather than importing the
entire module.

The syntax for the from ... import ... statement is as follows:
from module_name import name1, name2, ...

module_name: The name of the module from which you want to import attributes.
name1, name2, ...: The names of the specific attributes (functions, variables, classes, etc.) that
you want to import from the module.
Here's an example to illustrate how the from ... import ... statement works:

A module named math_operations.py, which contains some mathematical functions:


# math_operations.py
def add(x, y):
return x + y

def subtract(x, y):


return x - y

def multiply(x, y):


return x * y
def divide(x, y):
return x / y

The from ... import ... statement to import specific functions from the math_operations
module into another Python script:
# main.py
from math_operations import add, subtract

result_add = add(5, 3)
result_subtract = subtract(10, 4)

print("Result of addition:", result_add)


print("Result of subtraction:", result_subtract)

In this example:

From math_operations import add, subtract to import only the add and subtract functions
from the math_operations module are used. Then directly use these imported functions (add
and subtract) without prefixing them with the module name. Other functions (multiply and
divide) defined in the math_operations module are not imported and cannot be used directly
in the main.py script.
Using from ... import ... statement allows for more concise and selective imports, which can
improve code readability and reduce potential naming conflicts. However, be cautious not to
import too many attributes from modules, as it can clutter the namespace and make code
harder to understand.

4. What are packages? Give an example of package creation in Python.

In Python, a package is a way of organizing and structuring modules into a hierarchical


directory structure. A package can contain multiple modules and subpackages, allowing for
better organization and management of code in large projects. Packages are an essential
concept in Python for building scalable and maintainable software.

To create a package in Python, you need to follow these steps:

Create a directory to serve as the root directory of your package.


Inside the root directory, create a Python file named __init__.py. This file can be empty or
contain initialization code for the package.
Optionally, create additional Python modules and subpackages inside the root directory.
Here's an example of how to create a simple package named my_package:
my_package/ # Root directory of the package

├── __init__.py # Initialization file

├── module1.py # Module 1

├── module2.py # Module 2

└── subpackage/ # Subpackage

├── __init__.py # Initialization file for the subpackage

└── submodule.py # Submodule inside the subpackage

# Import module1 from my_package


from my_package import module1

# Import submodule from subpackage inside my_package


from my_package.subpackage import submodule

Packages are commonly used in Python for structuring large projects and libraries.

5. Write a Python program to check if a given value is a method of a user-defined


class. Use types.
The types module in Python to check if a given value is a method of a user-defined class.
Here's a Python program that demonstrates how to do this:
import types

class MyClass:
def method1(self):
pass

def method2(self):
pass

# Create an instance of MyClass


obj = MyClass()

# Check if the value is a method of the class using the types.MethodType


print(isinstance(obj.method1, types.MethodType)) # Output: True
print(isinstance(obj.method2, types.MethodType)) # Output: True

# Check if a regular function is a method of the class


def my_function():
pass

print(isinstance(my_function, types.MethodType)) # Output: False

In this example:

Define a user-defined class MyClass with two methods: method1 and method2. Create an
instance obj of the MyClass. Use the isinstance() function along with types.MethodType to
check if obj.method1 and obj.method2 are methods of the class MyClass. The isinstance()
function returns True if the value is an instance of the specified type (types.MethodType in
this case), otherwise False. A regular function (my_function) is not considered a method of
the class.
6. Write syntax for Handling Exceptions with example.
The syntax for handling exceptions in Python along with an example:
try:
# Code that may raise an exception
# ...
# ...
except ExceptionType1 as e:
# Handle exception of type ExceptionType1
# Optionally, you can access the exception object using 'e'
# ...
except ExceptionType2 as e:
# Handle exception of type ExceptionType2
# Optionally, you can access the exception object using 'e'
# ...
except (ExceptionType3, ExceptionType4) as e:
# Handle exceptions of type ExceptionType3 or ExceptionType4
# Optionally, you can access the exception object using 'e'
# ...
except Exception as e:
# Handle any other exceptions not caught by previous except blocks
# Optionally, you can access the exception object using 'e'
# ...
else:
# Optional else block executed if no exception occurs in the try block
# ...
finally:
# Optional finally block always executed regardless of whether an exception occurs
or not
# This block is used for cleanup activities, such as closing files or releasing resources
# It is executed even if a "return", "break", or "continue" statement is encountered in
the "try" or "except" blocks pass # Placeholder for cleanup code

Example demonstrating the usage of the try, except, else, and finally blocks:
try:
x = int(input("Enter a number: "))
result = 10 / x
print("Result:", result)

except ValueError:
print("Please enter a valid integer.")

except ZeroDivisionError:
print("Cannot divide by zero.")

else:
print("No exceptions occurred.")

finally:
print("Execution completed.")
In this example:

Divide 10 by a user-provided integer x.


If the user enters a non-integer value, a ValueError exception is raised, and we handle it by
printing a message.
If the user enters 0, a ZeroDivisionError exception is raised, and we handle it by printing a
message.
If no exceptions occur, the result is printed along with a message indicating that no
exceptions occurred.
The finally block is always executed, regardless of whether an exception occurs or not. It
prints a message indicating that the execution is completed.

7. Write a Python program to configure the rounding to round to the floor, ceiling
Configure the rounding behavior in Python using the math.floor() and math.ceil() functions
from the math module. Here's a Python program that demonstrates how to round to the floor
and ceiling:
import math

def round_to_floor(number):
"""Round to the nearest integer less than or equal to the given number."""
return math.floor(number)

def round_to_ceiling(number):
"""Round to the nearest integer greater than or equal to the given number."""
return math.ceil(number)

# Test the functions


number = 5.7
rounded_floor = round_to_floor(number)
rounded_ceiling = round_to_ceiling(number)

print(f"Original number: {number}")


print(f"Rounded to the floor: {rounded_floor}")
print(f"Rounded to the ceiling: {rounded_ceiling}")

Original number: 5.7


Rounded to the floor: 5
Rounded to the ceiling: 6

In this program:
Import the math module to access the math.floor() and math.ceil() functions. Define two
functions round_to_floor() and round_to_ceiling() that round a given number to the floor and
ceiling, respectively, using math.floor() and math.ceil() functions. Test the functions with a
sample number (5.7). The round_to_floor() function rounds 5.7 to the nearest integer less
than or equal to 5.
The round_to_ceiling() function rounds 5.7 to the nearest integer greater than or equal to 6.

You might also like