Functions, modules and exception handling — Unit 3 Notes (Python Programming)

BCC302 · Unit 3

Functions, modules and exception handling notes — Unit 3

Free unit-wise study notes on functions, modules and exception handling for Python Programming, Semester 3 of B.Tech — Computer Science & Engineering — key concepts, examples, important questions and a revision checklist for semester exams.

Structuring and securing Python code. Covers Function definitions, argument types (*args, **kwargs), Lambda functions, importing Modules/Packages, and robust Error Handling using try/except blocks.

Notebook — 14 pages

Page 1

Wink Notes

B.Tech CSE — 3rd Semester

Python Programming

Unit - 3

1. Functions in Python

A function is a reusable block of code designed to perform a specific task. Functions prevent code duplication and make programs modular.

1.1 Defining a Function

Functions are defined using the `def` keyword, followed by the function name, parentheses `()`, and a colon `:`.

```python
def greet(name):
"""This is a docstring describing the function."""
print("Hello", name)

greet("Alice") # Calling the function
```

1.2 Return Statement

A function can send data back to the caller using `return`.
If a function does not explicitly have a `return` statement, Python automatically returns `None`.

Unlike C or Java, Python functions can easily return multiple values by packing them into a tuple:
`return sum, difference`

Next — Function Arguments

1 of 14

Page 2

Wink Notes

B.Tech CSE — 3rd Semester

Python Programming

Unit - 3

2. Function Arguments

Python provides highly flexible ways to pass arguments to a function.

2.1 Positional and Keyword Arguments

  • Positional: Arguments are mapped to parameters based on their position/order.
    `def sub(a, b):`
    \to calling `sub(10, 2)` means a=10,b=2a=10, b=2.
  • Keyword: You explicitly state the parameter name in the function call. Order no longer matters!
    `sub(b=2, a=10)` is perfectly valid.

2.2 Default Parameters

You can assign a default value to a parameter. If the caller doesn't provide it, the default is used.

```python
def greet(name, msg="Good morning"):
print(f"Hello {name}, {msg}")

greet("Alice") # Uses default msg
greet("Bob", "Wake up") # Overrides default msg
```

Next — Variable-Length Arguments

2 of 14

Page 3

Wink Notes

B.Tech CSE — 3rd Semester

Python Programming

Unit - 3

3. Variable-Length Arguments (*args, **kwargs)

Sometimes you don't know in advance how many arguments the user will pass. Python uses packing operators to handle this.

3.1 `*args` (Non-Keyword Arguments)

The `` operator packs any number of positional arguments into a Tuple*.

```python
def add_all(*args):
return sum(args) # args is a tuple, e.g., (1, 2, 3, 4)

print(add_all(1, 2, 3, 4)) # Output: 10
```

3.2 `kwargs` (Keyword Arguments)

The `` operator packs any number of keyword arguments into a Dictionary.

```python
def profile(
kwargs):
for key, val in kwargs.items():
print(key, ":", val)

profile(name="Alice", age=20, city="Delhi")
```

Next — Scope of Variables

3 of 14

Page 4

Wink Notes

B.Tech CSE — 3rd Semester

Python Programming

Unit - 3

4. Scope of Variables (LEGB Rule)

Scope refers to the region of the code where a variable is accessible.

  • Local: Variables defined inside a function. They are destroyed when the function exits.
  • Global: Variables defined outside any function. Accessible anywhere in the file.

4.1 Modifying Global Variables

A function can read a global variable easily. However, if you try to modify it inside the function, Python will instead create a new Local variable with the same name, leaving the global untouched.

To actually modify the global variable, you must explicitly declare it using the `global` keyword.

```python
count = 0
def increment():
global count
count += 1
```

Next — Lambda Functions

4 of 14

Page 5

Wink Notes

B.Tech CSE — 3rd Semester

Python Programming

Unit - 3

5. Lambda (Anonymous) Functions

A lambda function is a small, anonymous function that is defined without a name. It can have any number of arguments, but can only have one single expression.

Syntax: `lambda arguments : expression`

```python
# Standard function
def square(x):
return x
2 # Lambda equivalent sq = lambda x : x 2
print(sq(5)) # 25
```

5.1 Use Cases

Lambdas are rarely assigned to variables. Their true power is acting as quick, throwaway "inline" functions passed as arguments to higher-order functions like `map()`, `filter()`, or as the `key` in `sort()`.

Next — Modules

5 of 14

Page 6

Wink Notes

B.Tech CSE — 3rd Semester

Python Programming

Unit - 3

6. Modules

As a program grows, putting all code in one file becomes unmanageable. A Module is simply a file containing Python code (functions, classes, variables) that can be imported into other files.

6.1 Creating and Importing

If you have a file `math_tools.py` containing a function `add()`, you can use it in `main.py`:

  • `import math_tools`: Imports the whole file. Usage: `math_tools.add(2, 3)`
  • `import math_tools as mt`: Imports with an alias. Usage: `mt.add(2, 3)`
  • `from math_tools import add`: Imports only the specific function. Usage: `add(2, 3)`

6.2 Standard Library Modules

Python includes hundreds of pre-written modules. Examples:
`math` (sqrt, sin, pi), `random` (generating random numbers), `os` (operating system interactions), `datetime`.

Next — Packages

6 of 14

Page 7

Wink Notes

B.Tech CSE — 3rd Semester

Python Programming

Unit - 3

7. Packages

A Package is a way of organizing multiple related Modules into a directory hierarchy.

For a folder to be recognized by Python as a Package, it historically needed to contain a special (usually empty) file named `__init__.py`. (This is optional in Python 3.3+, but still standard practice).

Directory Structure:
`game/`
`__init__.py`
`graphics.py`
`audio.py`

Importing from a package:
`from game import audio`
`audio.play_sound()`

7.1 PIP (Python Package Installer)

Third-party packages (like NumPy, Django, Requests) created by the community are hosted on the Python Package Index (PyPI). They are downloaded and installed using the command line tool `pip`:
`pip install numpy`

Next — Errors and Exceptions

7 of 14

Page 8

Wink Notes

B.Tech CSE — 3rd Semester

Python Programming

Unit - 3

8. Errors and Exceptions

Errors in Python fall into two categories.

8.1 Syntax Errors

Mistakes in the structure of the code (e.g., missing a colon, unclosed parenthesis). The parser catches these before execution begins. The program will not even start.

8.2 Exceptions (Runtime Errors)

The syntax is perfect, but an error occurs during execution. The program crashes immediately and prints a Traceback.

  • `ZeroDivisionError`: Trying to divide by zero.
  • `TypeError`: Adding a string to an integer.
  • `IndexError`: Accessing `lst[10]` when the list only has 3 items.
  • `KeyError`: Accessing a dictionary key that doesn't exist.
  • `ValueError`: `int("apple")` (The type is right, but the value is invalid).

Next — Exception Handling: try-except

8 of 14

Page 9

Wink Notes

B.Tech CSE — 3rd Semester

Python Programming

Unit - 3

9. Exception Handling: try-except

Professional programs should never crash abruptly. They should anticipate exceptions, catch them, and handle them gracefully. We use the `try-except` block for this.

9.1 The Mechanism

```python
try:
# Code that might crash
x = 10 / 0
except ZeroDivisionError:
# Code to execute IF the crash happens
print("Cannot divide by zero!")
```

If a ZeroDivisionError occurs inside the `try` block, Python immediately stops executing the `try` block and jumps into the `except` block. The program does not crash; execution continues normally after the block.

If no error occurs, the `except` block is completely ignored.

Next — Handling Multiple Exceptions

9 of 14

Page 10

Wink Notes

B.Tech CSE — 3rd Semester

Python Programming

Unit - 3

10. Handling Multiple Exceptions

A single `try` block might raise different types of errors. You can specify multiple `except` blocks to handle each one differently.

```python
try:
num = int(input("Enter a number: "))
result = 100 / num
except ValueError:
print("You didn't type a number!")
except ZeroDivisionError:
print("You typed zero!")
except Exception as e:
# Catches ANY other unpredicted error
print("An unknown error occurred:", e)
```

The generic `except Exception` acts as a catch-all safety net and should always be placed at the very bottom.

Next — finally and else blocks

10 of 14

Page 11

Wink Notes

B.Tech CSE — 3rd Semester

Python Programming

Unit - 3

11. The `finally` and `else` Clauses

The exception handling structure can be extended with two optional blocks.

11.1 The `else` Block

Executes ONLY if the `try` block succeeds without raising any exceptions.

```python
try:
# calculation
except Error:
# handle error
else:
# print result (only if calculation succeeded)
```

11.2 The `finally` Block

Executes ALWAYS, regardless of whether an exception occurred or not, or even if the `try` block has a `return` or `break` statement.

Crucial for Resource Management: Used to close database connections, close files, or release network sockets, guaranteeing that resources are freed even if the program crashes.

Next — Raising Exceptions

11 of 14

Page 12

Wink Notes

B.Tech CSE — 3rd Semester

Python Programming

Unit - 3

12. Raising Exceptions

Sometimes, you want to trigger an error intentionally. For example, if a user enters an age of -5, it might not break Python's math, but it breaks your program's business logic.

12.1 The `raise` Keyword

You can manually trigger an exception using `raise`.

```python
def set_age(age):
if age < 0:
raise ValueError("Age cannot be negative.")
print("Age set to", age)
```

If `set_age(-5)` is called, the program will crash with a ValueError (unless the caller wrapped it in a try-except block).

Next — Custom Exceptions

12 of 14

Page 13

Wink Notes

B.Tech CSE — 3rd Semester

Python Programming

Unit - 3

13. Custom Exceptions

You are not limited to Python's built-in error types. You can create your own exception classes by inheriting from the base `Exception` class. (Requires basic OOP knowledge).

```python
# Define the custom exception
class InsufficientFundsError(Exception):
pass

# Using it
balance = 100
withdrawal = 200
if withdrawal > balance:
raise InsufficientFundsError("Not enough money in account.")
```

Custom exceptions make large codebases highly readable. When a developer sees `InsufficientFundsError`, they instantly understand exactly what went wrong, much better than a generic `ValueError`.

Next — Summary Checklist

13 of 14

Page 14

Wink Notes

B.Tech CSE — 3rd Semester

Python Programming

Unit - 3

14. Summary Checklist

Functions and Modules keep code organized; Exception Handling keeps it alive.

14.1 University Exam Checklist

  • Explain the difference between local and global scope. When is the `global` keyword necessary?
  • Write a function that accepts `*args` and returns the average of all numbers passed to it.
  • What is a lambda function? Write a lambda function to calculate the cube of a number.
  • Explain the difference between a Module and a Package. What is the role of `__init__.py`?
  • Write a `try-except-else-finally` block to safely divide two numbers taken from user input.
  • What is the `raise` keyword used for?

14 of 14

Continue in this subject