Python UNIT 3
Python UNIT 3
UNIT 3
SYLLABUS
Exceptions: Exceptions in Python, Detecting and Handling Exceptions, Context
Management, Exceptions as Strings, Raising Exceptions, Assertions, Standard Exceptions,
Creating Exceptions, Exceptions and the sys Module.
Functions and Functional Programming –Calling Functions , Creating Functions, Passing
Functions , Formal Arguments, Variable-Length Arguments, Functional Programming.
Modules–Modules and Files, Namespaces, Importing Modules, Module
Built-in Functions, Packages, Related modules.
10 DESCRIPTIVE QUESTIONS
S.No Question BL CO
1 Explain the concept of exceptions in Python. How do exceptions differ from 2 CO-3
syntax errors? Provide examples relevant to civil engineering applications,
such as handling division by zero in structural analysis.
2 Describe the process of detecting and handling exceptions in Python using 3 CO-3
try-except blocks. Illustrate with an example where you handle input errors
in a program that calculates the load-bearing capacity of a beam.
3 What is the purpose of raising exceptions in Python? How can custom 3 CO-3
exceptions be created? Provide an example where you define a custom
exception for handling invalid soil test data.
4 Explain the role of assertions in Python. How can assertions be used to 2 CO-3
enforce constraints in civil engineering calculations, such as verifying the
stability of a retaining wall?
5 Discuss the significance of context management in Python. How does the 2 CO-3
"with" statement help in handling file operations efficiently in applications
such as reading structural analysis reports?
6 Explain the concept of functional programming in Python. How can lambda 2 CO-3
functions, map, filter, and reduce be used to simplify civil engineering
computations, such as analyzing multiple stress values in concrete
structures?
7 What are variable-length arguments in Python functions? How can they be 5 CO-3
useful in writing flexible programs for civil engineering applications such as
computing varying load distributions?
8 Describe the concept of modules in Python. How do modules help in 4 CO-3
organizing code effectively? Illustrate with an example of a module that
includes functions for calculating different transportation planning
parameters.
9 Explain the difference between importing a module using "import" and 3 CO-3
"from ... import ...". How does this impact namespace management in large-
scale projects like traffic simulation models?
10 What are Python packages? How can related modules be grouped into a 5 CO-3
package for better code reusability? Provide an example where you create a
package for handling various GIS operations in urban planning.
20 objective questions along with answers
1. Which keyword is used to handle exceptions in Python?
a) error
b) try
c) except
d) raise
Answer: b) try
5. Which statement is used to ensure that a block of code runs regardless of whether an
exception occurs?
a) finally
b) catch
c) assert
d) ensure
Answer: a) finally
python
Copy
Edit
try:
print(10 / 0)
except ZeroDivisionError:
print("Cannot divide by zero")
a) Error
b) Cannot divide by zero
c) 0
d) None
Answer: b) Cannot divide by zero
python
Copy
Edit
add = lambda x, y: x + y
print(add(3, 5))
a) 8
b) (3, 5)
c) lambda function
d) Error
Answer: a) 8
15. What is the difference between *args and **kwargs in function definitions?
a) *args passes multiple arguments as a list, **kwargs passes key-value pairs
b) *args is used for loops, **kwargs is used for lists
c) *args stores only integers, **kwargs stores only strings
d) No difference
Answer: a) *args passes multiple arguments as a list, **kwargs passes key-value pairs
16. Which statement is used to define a function in Python?
a) function
b) define
c) def
d) create
Answer: c) def
python
Copy
Edit
def test(a, b=5):
return a * b
print(test(3))
a) 3
b) 15
c) Error
d) None
Answer: b) 15
ASSIGNMENT QUESTIONS
S.No Question BL CO
1 Write a Python program that reads two numbers from the user and 2 CO-3
divides the first number by the second. Use exception handling to
manage division by zero errors and invalid inputs.
2 Create a Python function that calculates the area of a rectangle. Use 3 CO-3
function arguments to pass the length and width, and return the
calculated area.
3 Write a Python script that demonstrates the use of a lambda function to 6 CO-3
find the maximum of two given numbers.
4 Create a Python module named math_operations.py that contains 4 CO-3
functions for addition, subtraction, multiplication, and division. Write
another script to import and use this module.
5 Write a Python program that reads a list of numbers from the user and 6 CO-3
uses the map() function to square each number in the list.
https://onlinecourses.nptel.ac.in/noc24_cs45/preview
https://onlinecourses.nptel.ac.in/noc22_cs32/preview
https://onlinecourses.nptel.ac.in/noc24_cs57/preview
4. Programming in Python
https://onlinecourses.swayam2.ac.in/cec22_cs20/preview
UNIT TEST
SET 1
S.No Question BL CO
1 What is the difference between handling exceptions using try-except 2 CO-3
and using assertions in Python? Provide examples for both.
2 Write a Python function that takes a list of numbers as input and 3 CO-3
returns a new list with only even numbers using the filter() function.
3 Explain the significance of Python modules in large-scale applications. 2 CO-3
How do namespaces help in avoiding conflicts when importing multiple
modules?
4 Given the following code, what will be the output? Explain why. 2 CO-3
def func(a, b=10, c=20):
return a + b + c
print(func(5, c=15))
UNIT TEST
SET 2
S.No Question BL CO
1 What happens when an exception occurs in a try block but there is no 2 CO-3
corresponding except block to handle it? Provide an example to support
your answer.
2 Write a Python lambda function that takes two arguments and 3 CO-3
returns their product. Use this function with the map() function on two
lists of numbers.
3 What is the difference between absolute and relative imports in 2 CO-3
Python modules? Provide an example of each.
4 What will be the output of the following code? Explain the role of 2 CO-3
*args in function definitions.
def add_numbers(*args):
return sum(args)
print(add_numbers(5, 10, 15))
10 analytical/programming problems
1. Write a Python program that reads a file containing traffic data (vehicle count per
hour) and calculates the average traffic flow. Handle possible exceptions like file not
found or incorrect data format.
2. Implement a Python function using the reduce() function to find the highest load-
bearing capacity from a list of bridge load values.
3. Create a Python script that calculates the air quality index (AQI) based on given
pollutant concentration levels. Use map() and lambda functions to process a list of
values.
4. Write a program that defines a custom exception InvalidSoilDataError and raises it
when a soil bearing capacity value is negative or zero.
5. Develop a Python module civil_engineering.py that contains functions for beam
deflection, stress analysis, and load distribution. Import this module in another script
and demonstrate its use.
6. Write a Python program that takes a list of road lengths and lane widths and uses list
comprehensions along with zip() to calculate the total road surface area for each road
segment.
7. Implement a Python function that takes an elevation dataset and removes outliers
using the filter() function. Handle exceptions for invalid inputs.
8. Create a Python package gis_analysis containing modules for distance calculation,
nearest facility detection, and network connectivity analysis. Demonstrate how to
import and use these modules.
9. Given a dictionary containing traffic counts at different intersections, write a Python
function to find the intersection with the highest and lowest traffic using max() and
min() with custom key functions.
10. Write a Python script that uses context management to safely read and process a CSV
file containing urban infrastructure project data, ensuring proper file handling without
memory leaks.
Exceptions in Python
Question: Write a Python program to demonstrate exception handling using try, except, and
else blocks.
Answer:
python
Copy
Edit
try:
except ZeroDivisionError:
except ValueError:
else:
print("Result:", result)
Question: Write a Python program that handles a FileNotFoundError and prints a custom
error message when the file does not exist.
Answer:
python
Copy
Edit
try:
content = file.read()
except FileNotFoundError:
else:
print(content)
Context Management
Question: Demonstrate the use of context manager with the with statement to open and close
a file in Python.
Answer:
python
Copy
Edit
Exceptions as Strings
Question: Write a Python program that raises a custom exception and handles it by printing
the exception as a string.
Answer:
python
Copy
Edit
class CustomError(Exception):
pass
try:
except CustomError as e:
Raising Exceptions
Question: Write a Python function that raises an exception if the input is not a positive
integer.
Answer:
python
Copy
Edit
def check_positive_integer(num):
if num <= 0:
return num
try:
print(check_positive_integer(-5))
except ValueError as e:
print(f"Error: {e}")
Assertions
Question: Write a Python program that uses assertions to check if a number is greater than
zero.
Answer:
python
Copy
Edit
def check_positive(num):
return num
try:
print(check_positive(-5))
except AssertionError as e:
print(f"AssertionError: {e}")
Question: Demonstrate how to import and use a module in Python. Create a custom module
math_operations.py with a function add_numbers(a, b) that returns the sum of two numbers.
math_operations.py:
python
Copy
Edit
return a + b
Main Program:
python
Copy
Edit
import math_operations
print("Sum:", result)
Question: Create a Python package named geometry with two modules: circle.py and
rectangle.py. Each module should contain a function that calculates the area of the respective
shape. Import and use these functions in a main program.
circle.py:
python
Copy
Edit
import math
def area(radius):
rectangle.py:
python
Copy
Edit
Main Program:
python
Copy
Edit
circle_area = circle.area(5)