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

Python UNIT 3

The document outlines a syllabus for a Python course covering exceptions, functions, functional programming, and modules, with a focus on applications in civil engineering. It includes descriptive and objective questions, assignment prompts, and project ideas that emphasize practical use of Python in real-time scenarios. Additionally, it lists MOOC resources and provides examples of programming problems related to traffic data analysis and GIS operations.
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)
3 views14 pages

Python UNIT 3

The document outlines a syllabus for a Python course covering exceptions, functions, functional programming, and modules, with a focus on applications in civil engineering. It includes descriptive and objective questions, assignment prompts, and project ideas that emphasize practical use of Python in real-time scenarios. Additionally, it lists MOOC resources and provides examples of programming problems related to traffic data analysis and GIS operations.
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
You are on page 1/ 14

PYTHON

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

2. What will happen if an exception is not handled in Python?


a) The program will terminate abruptly
b) The program will continue execution
c) The error will be ignored
d) Python will automatically handle it
Answer: a) The program will terminate abruptly

3. Which of the following is not a built-in exception in Python?


a) ValueError
b) FileNotFoundError
c) NullPointerException
d) ZeroDivisionError
Answer: c) NullPointerException

4. What is the correct way to raise an exception in Python?


a) throw Exception("Error")
b) raise Exception("Error")
c) exception.raise("Error")
d) Error.raise("Exception")
Answer: b) raise Exception("Error")

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

6. What does the "with" statement help with in Python?


a) Handling exceptions
b) Managing resources efficiently
c) Declaring functions
d) Creating classes
Answer: b) Managing resources efficiently

7. What will be the output of the following code snippet?

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

8. What does the assert statement do in Python?


a) Raises an exception if the condition is False
b) Ignores the condition
c) Returns True always
d) Used for debugging only
Answer: a) Raises an exception if the condition is False

9. Which module provides access to exception-related functions in Python?


a) os
b) sys
c) exceptions
d) traceback
Answer: b) sys

10. Which of the following is an example of handling multiple exceptions?


a) Using multiple except blocks
b) Using multiple try blocks
c) Using a nested function
d) Using assert
Answer: a) Using multiple except blocks
11. What is a lambda function in Python?
a) A function with no name
b) A function that returns multiple values
c) A function that modifies global variables
d) A function with a loop
Answer: a) A function with no name

12. What will be the output of the following code?

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

13. Which function is used to apply a function to all items in an iterable?


a) map()
b) filter()
c) reduce()
d) apply()
Answer: a) map()

14. What is the purpose of the filter() function in Python?


a) Filters elements based on a condition
b) Modifies each element in a list
c) Merges two lists
d) Sorts a list
Answer: a) Filters elements based on a condition

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

17. What will be the output of the following code?

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

18. Which statement correctly imports the math module?


a) import math
b) include math
c) using math
d) load math
Answer: a) import math

19. How do you create a package in Python?


a) Create a directory with an init.py file
b) Define all functions in one file
c) Install all required modules
d) Use the package keyword
Answer: a) Create a directory with an init.py file

20. What will be the output of the following code?


python
Copy
Edit
import math
print(math.sqrt(25))
a) 5.0
b) 25
c) Error
d) None
Answer: a) 5.0

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.

MOOCS course or NPTEL courses

1. Programming, Data Structures and Algorithms Using Python

https://onlinecourses.nptel.ac.in/noc24_cs45/preview

2. Python for Data Science

https://onlinecourses.nptel.ac.in/noc22_cs32/preview

3. The Joy of Computing using Python

https://onlinecourses.nptel.ac.in/noc24_cs57/preview

4. Programming in Python

https://onlinecourses.swayam2.ac.in/cec22_cs20/preview

5. NOC: Programming, Data Structures and Algorithms in Python


https://archive.nptel.ac.in/courses/106/106/106106145

REAL TIME APPLICATION

The image illustrates real-time applications of Python in civil engineering. It features a


construction site where engineers use Python-based calculations for structural stability, a
GIS-based road network analysis on a computer, and a bridge with real-time sensors that use
Python functions for maintenance predictions. Additionally, a traffic analysis program on a
laptop demonstrates exception handling, while a dashboard visualizes data processing using
functional programming techniques for air quality assessment. This highlights how Python
supports infrastructure planning and engineering decision-making.

Minor Project Ideas:

 Automated Traffic Data Analysis Using Python

 Objective: Develop a Python-based system to analyze real-time traffic data and


identify congestion patterns.
 Scope:
o Use exception handling to manage missing or incorrect data.
o Apply functional programming (map, filter, reduce) to process traffic sensor
data.
o Use Python modules like Pandas and Matplotlib for data visualization.
 Expected Outcome: A program that can process live or historical traffic data, detect
peak congestion times, and generate reports for better traffic management.

 Road Network Connectivity Analysis Using Python and GIS

 Objective: Develop a Python-based tool to evaluate the connectivity of urban road


networks using GIS data.
 Scope:
o Use Python modules like geopandas and networkx to analyze road networks.
o Implement exception handling to manage missing geospatial data.
o Develop functions to calculate connectivity indices (e.g., Alpha Index, Beta
Index, Gamma Index).
 Expected Outcome: A tool that visualizes and quantifies road network efficiency,
helping urban planners improve transportation infrastructure.

UNIT TEST

SET 1

Answer any two questions

All questions carry equal marks MAX MARKS: 10

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

Answer any two questions

All questions carry equal marks MAX MARKS: 10

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.

Solved tutorial questions

Exceptions in Python

Question: Write a Python program to demonstrate exception handling using try, except, and
else blocks.

Answer:

python

Copy
Edit

try:

num1 = int(input("Enter a number: "))

num2 = int(input("Enter another number: "))

result = num1 / num2

except ZeroDivisionError:

print("Error: Cannot divide by zero.")

except ValueError:

print("Error: Invalid input. Please enter an integer.")

else:

print("Result:", result)

Detecting and Handling Exceptions

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:

file = open("non_existent_file.txt", "r")

content = file.read()

except FileNotFoundError:

print("Error: The file does not exist.")

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

with open("sample.txt", "w") as file:

file.write("This is a sample text.")

# No need to explicitly close the file, it will be done automatically.

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:

raise CustomError("This is a custom error message")

except CustomError as e:

print(f"Exception caught: {str(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:

raise ValueError("Input must be a positive integer.")

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):

assert num > 0, "Number must be positive"

return num

try:

print(check_positive(-5))

except AssertionError as e:
print(f"AssertionError: {e}")

Modules and Importing

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

def add_numbers(a, b):

return a + b

Main Program:

python

Copy

Edit

import math_operations

result = math_operations.add_numbers(10, 20)

print("Sum:", result)

Packages and Related Modules

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):

return math.pi * radius ** 2

rectangle.py:

python

Copy

Edit

def area(length, width):

return length * width

Main Program:

python

Copy

Edit

from geometry import circle, rectangle

circle_area = circle.area(5)

rectangle_area = rectangle.area(10, 20)

print(f"Area of circle: {circle_area}")

print(f"Area of rectangle: {rectangle_area}")

You might also like