Loading...

My Learning Pad Login

Welcome

PCEP-30-02 Module 4: Functions and Exceptions


Table of Contents

  1. Overview & Syllabus
  2. User-Defined Functions
    • Defining Functions
    • Function Arguments (Positional, Keyword, Default, Arbitrary)
    • Return Values & The None Keyword
    • Variable Scope & global
    • Recursion
    • Best Practices & Common Pitfalls
    • Exercises
  3. Exception Handling
    • Introduction: Errors vs Exceptions
    • Built-in Exceptions Hierarchy
    • Catching Exceptions (try, except)
    • Multiple, Specific, and Generic Exceptions
    • else and finally
    • Raising and Creating Exceptions
    • Example Scenarios for Common Exceptions
    • Best Practices
    • Exercises
  4. Practice Problems
  5. Summary Table

1. Overview & Syllabus

Module 4 focuses on:


2. User-Defined Functions

2.1 Defining and Invoking Functions

def say_hello():
            print("Hello!")
        say_hello()  # Output: Hello!
        

2.2 Return Values & None

def get_greeting(name):
            return f"Hello, {name}!"
        result = get_greeting('Alice')
        print(result)  # Output: Hello, Alice!

        def does_nothing():
            pass
        print(does_nothing())  # Output: None
        

2.3 Parameters and Arguments

def power(base, exponent=2):
            return base ** exponent
        print(power(4))        # 16
        print(power(2, 8))     # 256
        
def many(*args):
            return sum(args)
        print(many(1,2,3))     # 6
        

2.4 Variable Scope & global

x = 10
        def set_x():
            global x
            x = 99
        set_x()
        print(x)  # Output: 99
        

2.5 Recursion

def factorial(n):
            if n==0: return 1
            return n * factorial(n-1)
        print(factorial(5))  # Output: 120
        

Recursion Exercise

Write a recursive function to compute the nth Fibonacci number.

2.6 Best Practices

2.7 Function Exercises

  1. Write a function to count vowels in a string.
  2. Write a function that returns both min and max from a list as a tuple.
  3. Write a function that prints all keyword arguments passed to it.

3. Exception Handling

3.1 What are Errors and Exceptions?

3.2 Built-in Exceptions Hierarchy (selected)

Exception Typical Use
BaseException Base for all exceptions
Exception Most user exceptions
SystemExit Raised by sys.exit()
KeyboardInterrupt Interrupts program
ArithmeticError Numeric errors
ZeroDivisionError Divide by zero
IndexError Sequence index out of range
KeyError Dict key not found
TypeError Invalid type
ValueError Invalid value
FileNotFoundError File I/O fails
ImportError Import fails

3.3 Catching Exceptions

try:
            print(10/0)
        except ZeroDivisionError:
            print('Division by zero!')
        

3.4 Multiple, Specific, and Generic Excepts

try:
            f = open("test.txt")
            data = int(f.read())
        except FileNotFoundError:
            print("File not found!")
        except ValueError:
            print("Non-integer in file!")
        except Exception as e:
            print(f"Other error: {e}")
        

3.5 Else and Finally blocks

try:
            x = int(input())
        except ValueError:
            print('Not an integer!')
        else:
            print('You entered:', x)
        finally:
            print('This always runs.')
        

3.6 Raising and Creating Exceptions

def check_positive(x):
            if x < 0:
                raise ValueError("Negative value!")
        check_positive(-5)  # Raises ValueError
        

Custom Exception Example

class CustomError(Exception):
            pass
        try:
            raise CustomError("This is a custom error!")
        except CustomError as e:
            print(e)
        

3.7 Best Exception Practice

3.8 Exception Exercises

  1. Write a function that safely divides two numbers and catches division and type errors.
  2. Write code that attempts to read a file and print the number of lines, handling missing file exception.
  3. Write a function to parse user input as an integer, handling ValueError gracefully.
  4. Practice: Handle both KeyError and IndexError in a function that receives a dictionary and list.

4. Practice Problems

  1. Write a recursive function for the nth triangular number (sum 1 to n).
  2. Write a function that returns True if a string is palindrome.
  3. Build a function get_element(seq, idx) that safely gets the element at index, handling both IndexError and TypeError (e.g., for dicts and lists).
  4. Demonstrate the difference between handling exceptions at function level vs. caller level.
  5. Write a function that multiplies all numeric values in an iterable but safely skips non-numeric values.

5. Summary Table

Concept Syntax Example Purpose
Function Definition def fun(...): ... Define reusable code block
Function Call fun(args) Invoke function
Return Value return x Function outputs a value
Default Args def foo(x=5): ... Optional parameter
Keyword Args def bar(a, b=1): ... Explicit param assignment
*args/**kwargs def f(*a, **kw): ... Pass arbitrary args and keyword args
Recursion def rec(n): return rec(n-1) Self-calling function
try/except/finally try: ... except: ... finally: ... Exception handling and code cleanup
Raising Exception raise ValueError("msg") Manually raise an error
Custom Exception class X(Exception): ... User-defined exception
Exception Hierarchy ZeroDivisionError, KeyError, etc Built-in error types
global global var Access/modify global variable inside function