Notes On Python
Notes On Python
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
Start
Input: Number1, Number2
Process: Sum = Number1 + Number2
Output: Sum
1
End
Example Program in Python:
% 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.
Example in Python:
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:
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:
x = 5
y = 10
z = x + y # Expression
print(z) # Output: 15
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
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:
# 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 variance
variance = sum((x - average) ** 2 for x in numbers) /
len(numbers)
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
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 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}")
10
self.__name = name
self.__salary = salary
def get_details(self):
return f"Name: {self.__name}, Salary: {self.__salary}"
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())
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")
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
# Usage
print(factorial(5)) # Output: 120
Example: Fibonacci Sequence
# Usage
print(fibonacci(6)) # Output: 8
# 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:
# 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
# Usage
numbers = [64, 34, 25, 12, 22, 11, 90]
merge_sort(numbers)
print(numbers) # Output: [11, 12, 22, 25, 34, 64, 90]
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:
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:])
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.
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:
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:
# 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())
# Replacing a word
print("Replaced:", sentence.replace("Fun", "Awesome"))
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.
def on_button_click(event):
print("Button clicked!")
23
o Capturing: The event starts from the root element and propagates
down to the target element.
Example in JavaScript (HTML DOM):
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()
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.
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:
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
def factorial(n):
if n == 0: # Base case
return 1
else: # Recursive case
return n * factorial(n - 1)
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)
29