0% found this document useful (0 votes)
7 views30 pages

Notes On Python

Basics on python programming

Uploaded by

Jasper Haniel
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)
7 views30 pages

Notes On Python

Basics on python programming

Uploaded by

Jasper Haniel
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/ 30

COS 201.

1
Computer Programming I
Course Outline

Table of Contents
Course Outline....................................................................................................... 1
Lecture Note: Introduction to Programming I.........................................................1
Module 1: Essentials of Computer Programming................................................1
Module 2: Structured Programming Principles....................................................5
Module 3: Basic Object-Oriented Programming Concepts..................................8
Module 4: Advanced Object-Oriented Programming Concepts.........................11
Module 5: Algorithms and Data Structures.......................................................15
Module 6: Strings and String Processing...........................................................19
Module 7: Event-Driven Programming and Exception.......................................22
Module 8: Arrays and Simple Recursive Algorithms..........................................25

Lecture Note: Introduction to Programming I


Module 1: Essentials of Computer Programming
Programming is the process of designing and building executable computer
programs to accomplish specific tasks. It involves writing, testing, debugging,
and maintaining the source code.
Key Concepts:
 Algorithm: A step-by-step procedure for solving a problem or performing
a task.
 Programming Language: A set of syntax and rules for writing programs
(e.g., Python, Java, C++).
 Source Code: The set of instructions written in a programming language.
 Compiler/Interpreter: Tools that translate source code into machine-
readable instructions.
 Execution: Running the program to perform the intended task.
Example: Pseudocode for Adding Two Numbers

Start
Input: Number1, Number2
Process: Sum = Number1 + Number2
Output: Sum

1
End
Example Program in Python:

# Program to add two numbers


number1 = float(input("Enter first number: "))
number2 = float(input("Enter second number: "))
sum = number1 + number2
print("The sum is:", sum)
2. Overview of Programming Paradigms
Programming paradigms define the approach and methodology for programming.
The choice of paradigm depends on the problem and the programming
environment.
2.1 Functional Programming
 Emphasizes functions as the primary building blocks.
 Functions are treated as first-class citizens, meaning they can be passed
as arguments, returned from other functions, and assigned to variables.
 Avoids mutable state and side effects.
Example in Python:

# Functional programming example: Finding squares of a list of


numbers
numbers = [1, 2, 3, 4]
squares = list(map(lambda x: x**2, numbers))
print(squares) # Output: [1, 4, 9, 16]
2.2 Declarative Programming
 Focuses on what to achieve rather than how to achieve it.
 Commonly used in database query languages (e.g., SQL) and domain-
specific languages.
Example in SQL:
SELECT name FROM employees WHERE department = 'IT';
Declarative Style in Python (Using List Comprehension):

# Declarative style example: Filtering even numbers


numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [x for x in numbers if x % 2 == 0]
print(even_numbers) # Output: [2, 4, 6]
2.3 Logic Programming
 Based on formal logic.
 Programs consist of facts and rules that describe relationships.
 The system deduces new facts from existing ones.
Example in Prolog:

% Facts
parent(john, mary).

2
parent(mary, tom).

% Rule
grandparent(X, Y) :- parent(X, Z), parent(Z, Y).

% Query
grandparent(john, tom). % Output: true
2.4 Object-Oriented Programming (OOP)
 Models real-world entities using objects.
 Key principles include:
o Abstraction: Hiding complex details and showing only relevant
features.
o Encapsulation: Bundling data and methods together.

o Inheritance: Reusing properties and behaviors from a parent class.

o Polymorphism: Methods behaving differently based on the object.

Example in Python:

# OOP example: Defining a class and creating an object


class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model

def display_info(self):
print(f"Car: {self.brand} {self.model}")

# Creating an object
my_car = Car("Toyota", "Corolla")
my_car.display_info() # Output: Car: Toyota Corolla
3. Introduction to Scripting Languages
Scripting languages are high-level programming languages used to automate
tasks and execute small-scale scripts.
Key Characteristics:
 Interpreted rather than compiled.
 Focus on simplicity and rapid development.
 Commonly used for web development, system automation, and task
scripting.
Popular Scripting Languages:
 Python: General-purpose scripting with extensive libraries.
 JavaScript: Primarily used for web development.
 Ruby: Known for its developer-friendly syntax.
 Bash: Used for shell scripting in UNIX/Linux environments.

3
Example in Bash:

#!/bin/bash
# Simple script to display the current date
echo "Today's date is: $(date)"
Example in JavaScript:

// JavaScript script to display an alert


alert('Welcome to Scripting!');
Example in Python:

# Python script to count lines in a file


file_path = "example.txt"
with open(file_path, 'r') as file:
lines = file.readlines()
print(f"The file has {len(lines)} lines.")

Programming Paradigms Overview:

OOP Principles:

4
Class Activities
 Discuss the advantages and disadvantages of each programming
paradigm.
 Write programs to solve simple problems using different paradigms.
 Explore scripting languages by automating basic tasks.

5
Module 2: Structured Programming Principles
1. Basic Data Types, Variables, and Expressions
Basic Data Types:
Programming languages provide various data types to store data. Common
examples include:
 Integer (int): Whole numbers (e.g., -3, 0, 42).
 Floating-point (float): Numbers with decimal points (e.g., 3.14, -0.01).
 Character (char): Single characters (e.g., 'A', 'z').
 String (str): Sequence of characters (e.g., "Hello, World!").
 Boolean (bool): True or False values.
Variables:
Variables are named storage locations in memory used to store data.
 Declaration: Specifies the type and name of a variable.
 Initialization: Assigns an initial value to the variable.
Example in Python:

# Variable declaration and initialization


age = 25 # Integer
gpa = 3.75 # Float
name = "Alice" # String
is_student = True # Boolean
Expressions:
Expressions combine variables, constants, and operators to produce a result.
Example:

x = 5
y = 10
z = x + y # Expression
print(z) # Output: 15

2. Assignment Statements and Operators


Assignment Statements:
Used to assign values to variables.
 Syntax: variable_name = value
Operators:
Operators perform operations on variables and values.
1. Arithmetic Operators: +, -, *, /, % (modulus)
2. Relational Operators: ==, !=, <, >, <=, >=

6
3. Logical Operators: and, or, not
4. Assignment Operators: =, +=, -=, *=
Example in Python:

x = 10
y = 5
z = x + y # Arithmetic
print(z) # Output: 15

is_equal = (x == y) # Relational
print(is_equal) # Output: False

is_valid = (x > 0) and (y < 10) # Logical


print(is_valid) # Output: True

3. Control Structures
Control structures dictate the flow of a program. These include conditional
statements and loops.
If Statements:
Used to execute code based on a condition. Example:

x = 10
if x > 5:
print("x is greater than 5")
Switch-Case Statements (Alternative in Python):
Python uses dictionaries or match-case (Python 3.10+). Example:

# Match-case (Python 3.10+)


option = 2
match option:
case 1:
print("Option 1 selected")
case 2:
print("Option 2 selected")
case _:
print("Invalid option")
Loops:
 For Loop: Iterates over a sequence.
 While Loop: Repeats while a condition is true.
Example:

# For Loop
for i in range(5):
print(i) # Output: 0, 1, 2, 3, 4

# While Loop
count = 0
while count < 5:

7
print(count)
count += 1

4. Lab Work
Implementing Control Structures:
1. Write a program to check if a number is even or odd using if. Example:

num = 7
if num % 2 == 0:
print("Even")
else:
print("Odd")
2. Write a menu-driven program using match-case or if-elif.
Calculating Averages and Standard Deviations:
Program to Calculate Average:

# Calculate average of a list of numbers


numbers = [10, 20, 30, 40, 50]
average = sum(numbers) / len(numbers)
print("Average:", average)
Program to Calculate Standard Deviation:

# Importing math module for square root


import math

numbers = [10, 20, 30, 40, 50]


average = sum(numbers) / len(numbers)

# Calculate variance
variance = sum((x - average) ** 2 for x in numbers) /
len(numbers)

# Calculate standard deviation


std_deviation = math.sqrt(variance)
print("Standard Deviation:", std_deviation)

Class Activities:
1. Implement a program to determine the grade of a student based on their
score.
2. Write a loop-based program to calculate the factorial of a given number.
3. Design a menu-driven application for basic arithmetic operations.
Would you like additional problems or further explanations for any section?

8
Module 3: Basic Object-Oriented Programming Concepts
1. Abstraction, Objects, and Classes
Abstraction:
Abstraction is the process of hiding the implementation details and showing only
the essential features of an object.
 Focuses on what an object does rather than how it does it.
Objects and Classes:
 Class: A blueprint for creating objects. It defines the properties and
behaviors (methods) of the object.
 Object: An instance of a class.
Example in Python:

# Define a class
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model

def display_info(self):
print(f"Car: {self.brand} {self.model}")

# Create objects
car1 = Car("Toyota", "Corolla")
car2 = Car("Honda", "Civic")

# Access methods
car1.display_info() # Output: Car: Toyota Corolla
car2.display_info() # Output: Car: Honda Civic

2. Methods and Parameter Passing


Methods:
Methods are functions defined inside a class that operate on objects of that
class.
 Instance Methods: Operate on an instance of the class.
 Static Methods: Defined using @staticmethod, do not operate on
instance or class variables.
Parameter Passing:
 By Value: A copy of the value is passed.
 By Reference: A reference to the actual variable is passed.
Example in Python:

class Calculator:

9
def add(self, a, b):
return a + b

calc = Calculator()
result = calc.add(5, 3)
print(result) # Output: 8

3. Encapsulation
Encapsulation is the process of bundling data (variables) and methods into a
single unit (class) and restricting access to some of the object's components.
 Private Members: Defined with a leading underscore (e.g., _var).
Example in Python:

class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private variable

def deposit(self, amount):


self.__balance += amount

def get_balance(self):
return self.__balance

account = BankAccount(1000)
account.deposit(500)
print(account.get_balance()) # Output: 1500

4. Lab Work
Creating and Using Classes and Objects:
1. Create a class Student with attributes name and age, and a method
display_details. Example:

class Student:
def __init__(self, name, age):
self.name = name
self.age = age

def display_details(self):
print(f"Name: {self.name}, Age: {self.age}")

student1 = Student("Alice", 20)


student1.display_details() # Output: Name: Alice, Age: 20
Implementing Encapsulation:
1. Create a class Employee with private attributes name and salary.
Example:
class Employee:

def __init__(self, name, salary):

10
self.__name = name
self.__salary = salary

def get_details(self):
return f"Name: {self.__name}, Salary: {self.__salary}"

emp = Employee("John", 50000)


print(emp.get_details()) # Output: Name: John, Salary: 50000
Class Activities:
1. Write a program to create a class Circle with methods to calculate area
and circumference.
2. Create a class Book with private attributes title and author and methods to
set and get these values.

11
Module 4: Advanced Object-Oriented Programming
Concepts
1. Class Hierarchies and Program Organization
Class Hierarchies:
A class hierarchy represents the relationship between classes in object-oriented
programming. It is a structure where:
 A base class (parent) provides general functionality.
 Derived classes (children) inherit and extend the base class's
functionality.
Diagram:

Animal

Bird Mammal

Sparro Parrot
w Cat Dog

Program Organization:
Class hierarchies help organize programs by grouping related classes together,
improving code reusability and readability. Programs are typically structured into:
 Packages/Namespaces: Group related classes together.
 Modules: Contain classes and functions for specific purposes.
Example in Python:

# Base Class
class Animal:
def __init__(self, name):
self.name = name

def speak(self):
pass

# Derived Classes
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"

12
class Cat(Animal):
def speak(self):
return f"{self.name} says Meow!"

# Usage
animals = [Dog("Buddy"), Cat("Whiskers")]
for animal in animals:
print(animal.speak())

2. Inheritance and Polymorphism


Inheritance:
Inheritance allows a class (child) to acquire properties and behaviors of another
class (parent).
 Enables code reuse.
 Promotes hierarchical classification.
Example:

class Vehicle:
def __init__(self, brand):
self.brand = brand

def move(self):
print("Moving...")

class Car(Vehicle):
def __init__(self, brand, model):
super().__init__(brand)
self.model = model

def move(self):
print(f"{self.brand} {self.model} is driving!")

# Usage
my_car = Car("Toyota", "Corolla")
my_car.move() # Output: Toyota Corolla is driving!
Polymorphism:
Polymorphism allows methods in different classes to have the same name but
behave differently based on the object invoking them.
Example:

class Shape:
def area(self):
pass

class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height

13
def area(self):
return self.width * self.height

class Circle(Shape):
def __init__(self, radius):
self.radius = radius

def area(self):
return 3.14 * self.radius ** 2

# Usage
shapes = [Rectangle(4, 5), Circle(3)]
for shape in shapes:
print("Area:", shape.area())

3. Using Packages/Namespaces
Packages or namespaces are used to organize classes and functions into
modules, avoiding name conflicts and improving modularity.
Example:

# Directory structure:
# mypackage/
# __init__.py
# animal.py

# mypackage/animal.py
class Animal:
def __init__(self, name):
self.name = name

def speak(self):
return "..."

# Main Program
from mypackage.animal import Animal

dog = Animal("Buddy")
print(dog.speak())

Lab Work
1. Designing a Simple Class Hierarchy:
Design a program that models a library system with the following classes:
 Base Class: Item (attributes: title, author, year)
 Derived Classes: Book, Magazine, DVD
Example Skeleton:

class Item:
def __init__(self, title, author, year):

14
self.title = title
self.author = author
self.year = year

def display_info(self):
print(f"{self.title} by {self.author}, {self.year}")

class Book(Item):
def __init__(self, title, author, year, genre):
super().__init__(title, author, year)
self.genre = genre

class DVD(Item):
def __init__(self, title, director, year, duration):
super().__init__(title, director, year)
self.duration = duration
2. Demonstrating Inheritance and Polymorphism:
Write a program that:
1. Implements a Vehicle base class with derived classes Car and Truck.
2. Demonstrates polymorphism by overriding the move method in the
derived classes.
Solution:

class Vehicle:
def move(self):
print("Vehicle is moving")

class Car(Vehicle):
def move(self):
print("Car is driving")

class Truck(Vehicle):
def move(self):
print("Truck is hauling")

vehicles = [Car(), Truck()]


for vehicle in vehicles:
vehicle.move()

Class Activities:
1. Create a class hierarchy for a zoo management system (Animal > Mammal
> Specific Animals).
2. Design a polymorphic program where different employees (Manager,
Engineer, Intern) have a work method that outputs different behaviors.
3. Implement a simple module-based program using packages and
namespaces for an e-commerce system (Products, Customers, Orders).

15
Module 5: Algorithms and Data Structures
1. Introduction to Recursive Algorithms
Recursive Algorithms:
A recursive algorithm solves a problem by breaking it into smaller sub-problems
of the same type. It consists of:
 Base Case: The condition under which recursion stops.
 Recursive Case: The function calls itself with smaller inputs.
Example: Calculating Factorial

# Recursive function for factorial


def factorial(n):
if n == 0: # Base case
return 1
else:
return n * factorial(n - 1) # Recursive case

# Usage
print(factorial(5)) # Output: 120
Example: Fibonacci Sequence

# Recursive function for Fibonacci


def fibonacci(n):
if n <= 1: # Base case
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2) #
Recursive case

# Usage
print(fibonacci(6)) # Output: 8

2. Searching and Sorting Algorithms


Searching Algorithms:
Linear Search:
Iterates through each element in a list to find the target.
Example:

def linear_search(lst, target):


for i in range(len(lst)):
if lst[i] == target:
return i
return -1

# Usage
print(linear_search([1, 2, 3, 4, 5], 3)) # Output: 2
Binary Search:

16
Works on sorted lists by repeatedly dividing the search interval in half.
Example:

def binary_search(lst, target):


low, high = 0, len(lst) - 1
while low <= high:
mid = (low + high) // 2
if lst[mid] == target:
return mid
elif lst[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1

# Usage
print(binary_search([1, 2, 3, 4, 5], 4)) # Output: 3
Sorting Algorithms:
Bubble Sort:
Repeatedly swaps adjacent elements if they are in the wrong order.
Example:

def bubble_sort(lst):
n = len(lst)
for i in range(n):
for j in range(0, n - i - 1):
if lst[j] > lst[j + 1]:
lst[j], lst[j + 1] = lst[j + 1], lst[j]

# Usage
numbers = [64, 34, 25, 12, 22, 11, 90]
bubble_sort(numbers)
print(numbers) # Output: [11, 12, 22, 25, 34, 64, 90]
Merge Sort:
Divides the list into halves, sorts them recursively, and merges them.
Example:

def merge_sort(lst):
if len(lst) > 1:
mid = len(lst) // 2
left_half = lst[:mid]
right_half = lst[mid:]

merge_sort(left_half)
merge_sort(right_half)

i = j = k = 0
while i < len(left_half) and j < len(right_half):
if left_half[i] < right_half[j]:
lst[k] = left_half[i]
i += 1

17
else:
lst[k] = right_half[j]
j += 1
k += 1

while i < len(left_half):


lst[k] = left_half[i]
i += 1
k += 1

while j < len(right_half):


lst[k] = right_half[j]
j += 1
k += 1

# Usage
numbers = [64, 34, 25, 12, 22, 11, 90]
merge_sort(numbers)
print(numbers) # Output: [11, 12, 22, 25, 34, 64, 90]

3. Use of List, Stack, Queue from APIs


List:
Lists are dynamic arrays that can store heterogeneous elements. Example:

lst = [1, 2, 3, 4, 5]
lst.append(6) # Add an element
lst.remove(3) # Remove an element
print(lst) # Output: [1, 2, 4, 5, 6]
Stack:
A stack follows the LIFO (Last In, First Out) principle. Python uses lists to
implement stacks. Example:

stack = []
stack.append(1) # Push
stack.append(2)
stack.pop() # Pop
print(stack) # Output: [1]
Queue:
A queue follows the FIFO (First In, First Out) principle. Use the queue module in
Python. Example:

from collections import deque


queue = deque()
queue.append(1) # Enqueue
queue.append(2)
queue.popleft() # Dequeue
print(queue) # Output: deque([2])

Lab Work
1. Implementing and Comparing Sorting Algorithms:

18
Write programs for Bubble Sort and Merge Sort. Compare their performance
using a large dataset.
Example:

import time

# Test dataset
import random
numbers = [random.randint(0, 1000) for _ in range(1000)]

# Bubble Sort
start = time.time()
bubble_sort(numbers.copy())
end = time.time()
print("Bubble Sort Time:", end - start)

# Merge Sort
start = time.time()
merge_sort(numbers.copy())
end = time.time()
print("Merge Sort Time:", end - start)
2. Developing and Tracing Simple Recursive Algorithms:
1. Write a program to calculate the sum of a list using recursion. Example:

def recursive_sum(lst):
if not lst:
return 0
return lst[0] + recursive_sum(lst[1:])

print(recursive_sum([1, 2, 3, 4, 5])) # Output: 15


2. Trace the execution of a recursive Fibonacci function using print
statements to track calls and returns.

Class Activities:
1. Implement and compare Linear Search and Binary Search.
2. Design a program to evaluate postfix expressions using a stack.
3. Create a queue-based system for managing a simple ticketing service.

19
Module 6: Strings and String Processing
1. Introduction to Strings
Strings are sequences of characters used to represent text in programming. They
are immutable in many programming languages, meaning their values cannot be
changed after creation.
Key Characteristics of Strings:
 Sequence of Characters: Strings are made up of characters, which can
include letters, numbers, and symbols.
 Immutable (in most languages): Operations on strings create new
strings rather than modifying the original.
 Stored in Memory: Strings are stored in contiguous memory locations,
making them accessible via indexing.
Examples in Python:

# Creating strings
name = "Alice"
greeting = 'Hello'

# Multi-line string
message = """This is a
multi-line string."""

# Printing strings
print(name) # Output: Alice
print(message) # Output: This is a multi-line string.

2. String Manipulation and Processing Techniques


String manipulation involves performing operations like concatenation, slicing,
searching, and modification.
a. Concatenation:
Combining two or more strings.

first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name) # Output: John Doe
b. Slicing Strings:
Extracting parts of a string using indices.

text = "Programming"
print(text[0:4]) # Output: Prog
print(text[4:]) # Output: ramming
print(text[-1]) # Output: g
c. String Methods:
Common methods for string processing.

20
 len(): Returns the length of the string.
 lower() and upper(): Converts the string to lowercase or uppercase.
 strip(): Removes leading and trailing whitespace.
 replace(): Replaces a substring with another.
 find(): Finds the index of the first occurrence of a substring.
 split() and join(): Splits a string into a list or joins a list into a string.
Example:

text = " Hello, World! "


print(len(text)) # Output: 17
print(text.lower()) # Output: hello, world!
print(text.strip()) # Output: Hello, World!
print(text.replace("World", "Python")) # Output: Hello,
Python!
words = text.split(", ")
print(words) # Output: [' Hello', 'World! ']
d. Iterating Through Strings:
Using loops to process each character.

for char in "Hello":


print(char)
e. Checking Substring Presence:
Using the in keyword.

sentence = "The quick brown fox jumps over the lazy dog."
print("fox" in sentence) # Output: True
print("cat" in sentence) # Output: False

3. Lab Work
a. Writing Programs for String Operations:
1. Concatenation and Substring Extraction:

# Program for string concatenation and slicing


first_name = "Jane"
last_name = "Smith"
full_name = first_name + " " + last_name
print("Full Name:", full_name)

# Extracting a substring
substring = full_name[0:4]
print("Substring:", substring) # Output: Jane
String Processing Techniques:
# Program to demonstrate string methods
sentence = " Python Programming is Fun! "

# String length
print("Length:", len(sentence))

21
# Converting to uppercase
print("Uppercase:", sentence.upper())

# Removing extra spaces


print("Trimmed:", sentence.strip())

# Replacing a word
print("Replaced:", sentence.replace("Fun", "Awesome"))

# Splitting and joining


words = sentence.strip().split(" ")
print("Words:", words)
joined_sentence = "-".join(words)
print("Joined:", joined_sentence)
3. Palindrome Checker: Write a program to check if a string is a
palindrome (reads the same forward and backward).

def is_palindrome(string):
string = string.lower().replace(" ", "")
return string == string[::-1]

# Example
word = "Racecar"
print(f"Is '{word}' a palindrome?", is_palindrome(word)) #
Output: True

Class Activities:
1. Write a program to count the number of vowels in a given string.
2. Create a program to reverse a string without using slicing.
3. Develop a program to find the most frequent character in a string.

22
Module 7: Event-Driven Programming and Exception
Overview
This module covers the fundamentals of event-driven programming and
exception handling in Python. Students will learn how to write programs that
respond to user events and handle errors gracefully. By the end of the module,
students will be able to:
 Understand the concepts of event-driven programming.
 Implement event-handling mechanisms in Python.
 Propagate and manage events effectively.
 Utilize Python’s exception handling features to build robust programs.

1. Event-Driven Programming Concepts


Event-driven programming is a programming paradigm where the flow of the
program is determined by events (such as user actions, sensor outputs, or
message passing) rather than a pre-defined sequence of instructions. This is
commonly used in GUI (Graphical User Interface) applications, web development,
and other interactive systems.
 Events: These are actions or occurrences detected by the program, such
as button clicks, mouse movements, or keyboard inputs.
 Event Handlers: Functions or methods that are invoked in response to
events. For example, when a user clicks a button, an event handler is
triggered to execute a set of instructions.
 Event Loop: A loop that waits for events and dispatches them to the
appropriate handler. This is central to event-driven programs.
2. Event-Handling Methods and Propagation
 Event Handlers: These are specific functions or methods that execute in
response to an event. In most GUI frameworks (like JavaScript for web, or
Java for desktop apps), event handlers are assigned to specific events.
Example:

def on_button_click(event):
print("Button clicked!")

# Button click simulation


button = Button(on_click=on_button_click)
button.click()
 Event Propagation: This refers to the way events are passed through the
hierarchy of components in an application. There are two primary types of
event propagation:
o Bubbling: The event starts from the target element and propagates
up the DOM tree.

23
o Capturing: The event starts from the root element and propagates
down to the target element.
Example in JavaScript (HTML DOM):

// Example of Event Bubbling


document.getElementById("parent").addEventListener("click",
function() {
alert("Parent clicked");
});

document.getElementById("child").addEventListener("click",
function(event) {
alert("Child clicked");
event.stopPropagation(); // Stops further bubbling
});
3. Exception Handling
Exception handling is a mechanism to handle runtime errors in a program. When
an error occurs, an exception is raised, and the program can respond by
executing predefined exception-handling code, rather than crashing.
 Try Block: The code that might throw an exception is placed inside a try
block.
 Catch Block: If an exception occurs, the catch block handles it.
 Finally Block: This block runs after the try-catch, regardless of whether
an exception occurred or not.
Example in Python:

try:
x = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError as e:
print(f"Error: {e}")
finally:
print("This block always executes.")
Types of Exceptions: Common exceptions include
ZeroDivisionError, ValueError, FileNotFoundError, etc.
Custom Exceptions: You can define your own exceptions by
inheriting from the built-in Exception class.
Example of Custom Exception:

class NegativeNumberError(Exception):
pass

def check_positive_number(num):
if num < 0:
raise NegativeNumberError("Number must be positive.")
return num

try:
check_positive_number(-1)
except NegativeNumberError as e:
print(f"Error: {e}")

24
4. Lab Work
Lab 1: Writing Event-Driven Programs
 Objective: Students will create a simple event-driven program, such as a
GUI calculator or a click-counter application.
 Steps:
1. Set up a simple GUI application (using libraries like Tkinter in Python
or Java Swing).
2. Define events (button clicks, text field interactions).
3. Write event handlers to respond to the actions (e.g., calculate the
sum when the user clicks "Add").
Example (Python with Tkinter):

import tkinter as tk

def on_button_click():
label.config(text="Button Clicked!")

root = tk.Tk()
button = tk.Button(root, text="Click Me",
command=on_button_click)
button.pack()

label = tk.Label(root, text="")


label.pack()

root.mainloop()
Lab 2: Handling Exceptions in Real-World Scenarios
 Objective: Students will write programs that handle real-world exceptions
like invalid file input, network issues, or user errors.
 Steps:
1. Simulate a scenario where an exception can occur, such as reading
from a file that may not exist.
2. Handle the exception gracefully by providing error messages or
fallback options.
Example (Handling File Not Found Exception):

try:
with open("non_existent_file.txt", "r") as file:
content = file.read()
except FileNotFoundError as e:
print(f"Error: {e}. File not found.")

25
Module 8: Arrays and Simple Recursive Algorithms
1. Arrays: Definition, Initialization, and Operations
An array is a collection of elements that are stored in contiguous memory
locations. All elements in an array are of the same data type, and each element
can be accessed using an index.
 Definition: An array can store multiple values of the same type. The
index of the first element is 0, and the index of the last element is the
length of the array minus one.
 Array in Python: Although Python does not have a built-in array data
structure like C/C++, lists are commonly used to simulate arrays.
Defining and Initializing Arrays in Python
In Python, arrays are implemented as lists. Lists are dynamic, meaning their size
can change during program execution.

# Defining an array in Python


numbers = [10, 20, 30, 40, 50]

# Initializing an empty array and adding elements dynamically


numbers = []
numbers.append(10)
numbers.append(20)
numbers.append(30)
Array Operations in Python
 Accessing Array Elements: You can access elements of an array using
indices.

# Accessing the first element (index 0)


print(numbers[0]) # Output: 10
 Updating Array Elements: Arrays allow you to modify elements by using
their index.

# Updating the second element (index 1)


numbers[1] = 100
print(numbers) # Output: [10, 100, 30]
 Iterating Over an Array: You can loop through the array using a for loop.

for num in numbers:


print(num)
 Finding the Length of an Array: You can find the number of elements in
an array using the len() function.

print(len(numbers)) # Output: 3
2. Designing Simple Recursive Solutions
A recursive function is a function that calls itself in order to solve a problem.
Recursive functions are typically used for problems that can be broken down into
smaller subproblems of the same type.

26
 Base Case: Every recursive function needs a base case to stop the
recursion and prevent infinite recursion.
 Recursive Case: The function calls itself with modified parameters to
move toward the base case.
Example: Factorial of a Number
The factorial of a number nn is defined as:

n!=n×(n−1)×(n−2)×⋯×1n! = n \times (n-1) \times (n-2) \times \dots \


times 1
And the base case is 0!=10! = 1.
Recursive Approach to Factorial
The recursive formula for factorial is:

n!=n×(n−1)!n! = n \times (n-1)!


def factorial(n):
if n == 0: # Base case
return 1
else: # Recursive case
return n * factorial(n - 1)

# Test the function


print(factorial(5)) # Output: 120
Example: Fibonacci Sequence
The Fibonacci sequence is defined as:
F(0)=0,F(1)=1,F(n)=F(n−1)+F(n−2)F(0) = 0, F(1) = 1, F(n) = F(n-1) + F(n-
2)
Recursive Approach to Fibonacci
The recursive formula for Fibonacci is:

F(n)=F(n−1)+F(n−2)F(n) = F(n-1) + F(n-2)


def fibonacci(n):
if n == 0: # Base case
return 0
elif n == 1: # Base case
return 1
else: # Recursive case
return fibonacci(n - 1) + fibonacci(n - 2)

# Test the function


print(fibonacci(5)) # Output: 5
3. Lab Work
Lab 1: Solving Problems Using Arrays
 Objective: Write Python programs to solve problems using arrays (lists).
For example:
1. Find the sum of all elements in an array.

27
2. Implement a linear search to find an element in an array.
3. Reverse the array.
Example: Sum of Array Elements

def sum_array(arr):
total = 0
for num in arr:
total += num
return total

# Test the function


numbers = [10, 20, 30, 40, 50]
print(sum_array(numbers)) # Output: 150
Example: Linear Search

def linear_search(arr, target):


for i in range(len(arr)):
if arr[i] == target:
return i # Return the index of the found element
return -1 # Return -1 if not found

# Test the function


numbers = [10, 20, 30, 40, 50]
print(linear_search(numbers, 30)) # Output: 2
print(linear_search(numbers, 60)) # Output: -1
Example: Reversing an Array
def reverse_array(arr):
return arr[::-1]

# Test the function


numbers = [10, 20, 30, 40, 50]
print(reverse_array(numbers)) # Output: [50, 40, 30, 20, 10]

Lab 2: Developing Recursive Solutions for Mathematical Problems


 Objective: Write Python programs to solve mathematical problems
recursively. For example:
1. Calculate the factorial of a number.
2. Calculate the nth Fibonacci number.
Example: Factorial

def factorial(n):
if n == 0: # Base case
return 1
else: # Recursive case
return n * factorial(n - 1)

# Test the function


print(factorial(5)) # Output: 120
Example: Fibonacci Sequence

28
def fibonacci(n):
if n == 0: # Base case
return 0
elif n == 1: # Base case
return 1
else: # Recursive case
return fibonacci(n - 1) + fibonacci(n - 2)

# Test the function


print(fibonacci(5)) # Output: 5

29

You might also like