Python Notes by MR Saem
Python Notes by MR Saem
Python Notes by MR Saem
Strings
In computer science, sequences of characters are referred to as strings. Strings
can be any length and can include any character such as letters, numbers,
symbols, and whitespace (spaces, tabs, new lines).
Escaping Characters
Backslashes (\) are used to escape characters in a Python string.
For instance, to print a string with quotation marks, the given code snippet
can be used.
txt = "She said \"Never let go\"."
print(txt) # She said "Never let go".
The in Syntax
The in syntax is used to determine if a letter or a substring exists in a string. It
returns True if a match is found, otherwise False is returned.
game = "Popular Nintendo Game: Mario Kart"
Indexing with negative numbers counts from the end of the string.
str = 'yellow'
str[1] # => 'e'
str[-1] # => 'w'
str[4:6] # => 'ow'
str[:4] # => 'yell'
str[-3:] # => 'low'
1-dimensional (1D) or 2-dimensional (2D)
In Python, arrays can be either 1-dimensional (1D) or 2-dimensional (2D). Let's look at both in
detail with examples.
1D Arrays
A 1-dimensional array is essentially a list of items that can be accessed by a single index. In
Python, a 1D array can be created using a list or by using the numpy library for more functionality.
Using a List
Using NumPy
import numpy as np
2D Arrays
A 2-dimensional array is essentially a list of lists, where each sublist represents a row. In Python,
this can be created using a list of lists or with numpy for more functionality.
Using NumPy
# [7 8 9]]
print(array_2d_np[1, 2]) # Access element in row 1, column 2, Output: 6
• Efficiency: NumPy arrays are more memory-efficient and perform better for large
datasets.
• Mathematical Operations: NumPy provides built-in operations for mathematical
calculations on arrays, making it suitable for scientific computing.
Key Differences
These examples demonstrate basic usage of 1D and 2D arrays in Python with both lists and
NumPy.
A-LEVEL CS 9618 FOR LOOP PRACTICE
A-LEVEL CS 9618 FOR LOOP PRACTICE
SOLUTIONS
#3 print 5,6,7,8,9,...,89,90
for i in range(5,91):
print(i, end=' ')
print()
#4 print 2,6,10,14,18,...,98,102
for i in range(2,103,4):
print(i, end=' ')
print()
#5 print 29,28,27,26,25,...5,4
for i in range(29,3,-1):
print(i, end=' ')
print()
A-LEVEL CS 9618 FOR LOOP PRACTICE
#6 print 1. A 2. A ... 5. A
for i in range(1,6):
print(i, '. A', sep='')
#7 perfect squares
for i in range(1,21):
print(i*i, end=' ')
print()
#10 AAAAAAAAAABCDBCDBCDBCDBCDEFFFFFFFFFFFFFFF
for i in range(10):
print('A', end='')
for i in range(5):
print('BCD', end='')
print('E')
for i in range(15):
print('F', end='')
print()
A-LEVEL CS 9618 FOR LOOP PRACTICE
• Equals: a == b
• Not Equals: a != b
• Less than: a < b
• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b
Example
If statement:
a = 33
b = 200
if b > a:
print("b is greater than a")
Elif
The elif keyword is pythons way of saying "if the previous conditions were not
true, then try this condition".
Example
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
In this example a is greater than b, so the first condition is not true, also
the elif condition is not true, so we go to the else condition and print to
screen that "a is greater than b".
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Short Hand If
If you have only one statement to execute, you can put it on the same line as
the if statement.
Example
One line if statement:
Example
One line if else statement:
a = 2
b = 330
print("A") if a > b else print("B")
And
The and keyword is a logical operator, and is used to combine conditional
statements:
Example
Test if a is greater than b, AND if c is greater than a:
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
Or
The or keyword is a logical operator, and is used to combine conditional
statements:
Example
Test if a is greater than b, OR if a is greater than c:
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
Try it Yourself »
Nested If
You can have if statements inside if statements, this is
called nested if statements.
Example
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
Python Loops
Python has two primitive loop commands:
• while loops
• for loops
Example
Print i as long as i is less than 6:
i = 1
while i < 6:
print(i)
i += 1
The while loop requires relevant variables to be ready, in this example we need
to define an indexing variable, i, which we set to 1.
Example
Exit the loop when i is 3:
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
This is less like the for keyword in other programming languages, and works
more like an iterator method as found in other object-orientated programming
languages.
With the for loop we can execute a set of statements, once for each item in a
list, tuple, set etc.
Example
Print each fruit in a fruit list:
Example
Loop through the letters in the word "banana":
for x in "banana":
print(x)
Example
Exit the loop when x is "banana":
Example
Exit the loop when x is "banana", but this time the break comes before the
print:
Example
Using the range() function:
for x in range(6):
print(x)
Example
Using the start parameter:
Python Functions
A function is a block of code which only runs when it is called.
Creating a Function
In Python a function is defined using the def keyword:
Example
def my_function():
print("Hello from a function")
Calling a Function
To call a function, use the function name followed by parenthesis:
Example
def my_function():
print("Hello from a function")
my_function()
Try it Yourself »
Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When the
function is called, we pass along a first name, which is used inside the function
to print the full name:
Example
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Try it Yourself »
Programming with Python for Paper 04 Computer Science 9618 A - LEVEL
CLASSES EXAMPLE 01
class Employee:
def __init__(self,first,last,email):
self.first=first
self.last=last
self.email=first + '.'+ last +'@mrsaem.com'
emp1=Employee('SAEM','TARIQ','mrsaem@yahoo.com')
emp2=Employee('ALI','MURTAZA','murtaza@yahoo.com')
print(emp1.email)
print(emp2.email)
________________________________________________________________
CLASSES EXAMPLE 02
class Human:
def __init__(self,n,o):
self.name=n
self.occupancy=o
def do_work(self):
if self.occupancy=="teacher":
print(self.name, " teaches Computer Science")
elif self.occupancy=="student":
print(self.name, "studies all the time")
def speaks(self):
print(self.name," says how are you")
Searching in Python
def search(list,n):
for i in range(len(list)):
if list[i]==n:
return True
return False
list=[3,5,6,7]
n=int(input("Enter the number"))
if search(list,n):
print("Found")
else:
print("Not Found")
__________________________________________________
Bubble Sort
# Bubble sort in python
# Sorts numbers in ascending order
str_input = input("Please enter numbers separated by spaces: ")
count = len(numbers)
print(numbers)
Learning Python with Mr Saem
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist
Example
Create a file called "myfile.txt":
f = open("myfile.txt", "x")
Example
Create a new file if it does not exist:
f = open("myfile.txt", "w")
Example
Open the file "demofile2.txt" and append content to the file:
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
#open and read the file after the appending:
f = open("demofile2.txt", "r")
print(f.read())
Delete a File
To delete a file, you must import the OS module, and run
its os.remove() function:
Example
Remove the file "demofile.txt":
import os
os.remove("demofile.txt")
Python Dates
A date in Python is not a data type of its own, but we can import a module
named datetime to work with dates as date objects.
Example
Import the datetime module and display the current date:
import datetime
x = datetime.datetime.now()
print(x)
Example
x = min(5, 10, 25)
y = max(5, 10, 25)
print(x)
print(y)
The abs() function returns the absolute (positive) value of the specified
number:
Example
x = abs(-7.25)
print(x)
Example
Return the value of 4 to the power of 3 (same as 4 * 4 * 4):
x = pow(4, 3)
print(x)
When you have imported the math module, you can start using methods and
constants of the module.
The math.sqrt() method for example, returns the square root of a number:
Example
import math
x = math.sqrt(64)
print(x)
The math.ceil() method rounds a number upwards to its nearest integer, and
the math.floor() method rounds a number downwards to its nearest integer,
and returns the result:
Example
import math
x = math.ceil(1.4)
y = math.floor(1.4)
print(x) # returns 2
print(y) # returns 1
The math.pi constant, returns the value of PI (3.14...):
Example
import math
x = math.pi
print(x)
Python abs()
The abs() method returns the absolute value of the given number. If the number is
a complex number, abs() returns its magnitude.
# random integer
integer = -20
print('Absolute value of -20 is:', abs(integer))
Output
Python any()
The any() function returns True if any element of an iterable is True. If not, any()
returns False.
Python chr()
The chr() method returns a character (a string) from an integer (represents unicode
code point of the character).
print(chr(97))
print(chr(65))
print(chr(1200))
Python len()
The len() function returns the number of items (length) in an object.
testList = []
print(testList, 'length is', len(testList))
testList = [1, 2, 3]
print(testList, 'length is', len(testList))
testTuple = (1, 2, 3)
print(testTuple, 'length is', len(testTuple))
[] length is 0
[1, 2, 3] length is 3
(1, 2, 3) length is 3
Length of range(1, 10) is 9
Python reversed()
The reversed() function returns the reversed iterator of the given sequence.
# for string
seq_string = 'Python'
print(list(reversed(seq_string)))
# for tuple
seq_tuple = ('P', 'y', 't', 'h', 'o', 'n')
print(list(reversed(seq_tuple)))
# for range
seq_range = range(5, 9)
print(list(reversed(seq_range)))
# for list
seq_list = [1, 2, 4, 3, 5]
print(list(reversed(seq_list)))
Output
# for integers
print(round(10))
# even choice
print(round(5.5))
Output
10
11
6
Python sorted()
The sorted() function returns a sorted list from the items in an iterable.
# vowels list
py_list = ['e', 'a', 'u', 'o', 'i']
print(sorted(py_list))
# string
py_string = 'Python'
print(sorted(py_string))
# vowels tuple
py_tuple = ('e', 'a', 'u', 'o', 'i')
print(sorted(py_tuple))
Output
Python sum()
The sum() function adds the items of an iterable and returns the sum.
# start = 10
numbers_sum = sum(numbers, 10)
print(numbers_sum)
Output
4.5
14.5
A-LEVEL CS 9618 LINKED LIST/QUEUES/STACKS/BINARY TREE
Write algorithms to insert an item into each of the following: stack, queue, linked list, binary tree
Explanation
1. is_empty Function:
• The is_empty function checks whether the stack is empty by
verifying if its length is zero.
2. push Function:
• The push function takes an item as an argument and appends it
to the end of the stack (list).
• It also prints a message indicating the item that has been
pushed into the stack.
3. Example Usage:
• Items (5, "Hello", and 3.14) are pushed onto the stack using
the push function.
This implementation mimics the basic functionality of a stack without the
use of a class. Keep in mind that a class-based approach provides
encapsulation and a more structured way to handle multiple stacks if
needed.
A-LEVEL CS 9618 LINKED LIST/QUEUES/STACKS/BINARY TREE
Code in Python
def create_stack_with_limit(limit):
return [], limit
def is_empty(stack):
return len(stack) == 0
def display_stack(stack):
print("Stack:", stack)
Pseudocode
Code in Python
def is_empty():
return len(stack) == 0
def push(item):
stack.append(item)
print(f"Pushed {item} into the stack")
def pop():
if not is_empty():
item = stack.pop()
print(f"Popped {item} from the stack")
return item
else:
print("Stack is empty. Cannot pop.")
# Example Usage:
# Insert items into the stack
push(5)
push("Hello")
push(3.14)
Explanation:
1. pop Function:
• The pop function checks if the stack is not empty before
attempting to pop an item.
• If the stack is not empty, it uses the pop() method to remove
and return the last item from the stack.
• It also prints a message indicating the item that has been
popped from the stack.
• If the stack is empty, it prints a message indicating that the
stack is empty, and popping is not possible.
2. Example Usage:
• The push function is called three times to insert items (5,
"Hello", and 3.14) into the stack.
• The pop function is called four times to delete (pop) items
from the stack. The last call attempts to pop from an empty
stack.
This algorithm demonstrates how to delete (pop) items from a stack using a
simple list-based implementation in Python.
A-LEVEL CS 9618 LINKED LIST/QUEUES/STACKS/BINARY TREE
PseudoCode in Python
def is_empty():
return len(queue) == 0
def enqueue(item):
queue.append(item)
print(f"Enqueued {item} into the queue")
# Example Usage:
# Insert items into the queue
enqueue(5)
enqueue("Hello")
enqueue(3.14)
Pseudocode in Python
# Example Usage:
# Insert items into the queue
enqueue(5)
enqueue("Hello")
enqueue(3.14)
A-LEVEL CS 9618 LINKED LIST/QUEUES/STACKS/BINARY TREE
def is_empty():
return len(queue) == 0
def enqueue(item):
queue.append(item)
print(f"Enqueued {item} into the queue")
def dequeue():
if not is_empty():
item = queue.pop(0)
print(f"Dequeued {item} from the queue")
return item
else:
print("Queue is empty. Cannot dequeue.")
# Example Usage:
# Insert items into the queue
enqueue(5)
enqueue("Hello")
enqueue(3.14)
Explanation:
1. dequeue Function:
• The dequeue function checks if the queue is not
empty before attempting to dequeue an item.
• If the queue is not empty, it uses the pop(0) method
to remove and return the first item from the queue.
• It also prints a message indicating the item that
has been dequeued from the queue.
• If the queue is empty, it prints a message
indicating that the queue is empty, and dequeuing is
not possible.
2. Example Usage:
A-LEVEL CS 9618 LINKED LIST/QUEUES/STACKS/BINARY TREE
•
The enqueue function is called three times to insert
items (5, "Hello", and 3.14) into the queue.
• The dequeue function is called four times to delete
(dequeue) items from the queue. The last call
attempts to dequeue from an empty queue.
Keep in mind that using pop(0) on a list can be inefficient
for large queues because it requires shifting all remaining
elements. For better performance, consider using collections.
Deque for a more efficient implementation of a queue.
Pseudocode in Python
Code in Python
def create_node(data):
return {"data": data, "next": None}
if head is None:
head = new_node
else:
current = head
while current["next"] is not None:
current = current["next"]
current["next"] = new_node
return head
def print_linked_list(head):
current = head
while current is not None:
print(current["data"], end=" -> ")
current = current["next"]
print("None")
# Example Usage:
# Create a linked list
head = None
Code in Python
class Node:
def __init__(self, data):
self.data = data
self.next = None
return head
def print_linked_list(head):
current = head
while current is not None:
print(current.data, end=" -> ")
current = current.next
print("None")
# Example Usage:
# Create a linked list
head = Node(1)
head.next = Node(2)
head.next.next = Node(3)
head.next.next.next = Node(4)
In this example:
• The Node class is used to represent a node in the linked list.
• The delete_node function takes the head of the linked list and the
key to be deleted.
• It traverses the linked list to find the node with the specified key.
• If found, it deletes the node:
• If the node is the first node, it updates the head.
• If the node is in the middle, it updates the next pointer of
the previous node.
• If the key is not found, it prints a message.
• The print_linked_list function is used to print the elements of the
linked list.
This code demonstrates how to delete a node with a specific value from a
singly linked list.
A-LEVEL CS 9618 LINKED LIST/QUEUES/STACKS/BINARY TREE
PseudoCode in Python
return head
# Example Usage:
# Create a linked list
head <- null
if head is None:
head = new_node
else:
current = head
while current.next is not None:
current = current.next
current.next = new_node
return head
def print_linked_list(head):
current = head
while current is not None:
print(current.data, end=" -> ")
current = current.next
print("None")
# Example Usage:
# Create a linked list
head = None
Explanation:
1. Node Class:
• Represents a node in the linked list with a data field and a
next pointer.
2. insert_at_end Function:
• Inserts a new node at the end of the linked list.
3. print_linked_list Function:
• Prints the elements of the linked list.
4. Example Usage:
• The linked list is managed using the head variable.
• Nodes with data 5, 10, and 15 are inserted at the end of the
linked list using the insert_at_end function.
• The linked list is printed to verify the insertion.
This version uses functions to encapsulate the linked list operations
without the use of a class.
A-LEVEL CS 9618 LINKED LIST/QUEUES/STACKS/BINARY TREE
class TreeNode:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
return root
def inorder_traversal(root):
if root:
inorder_traversal(root.left)
print(root.key, end=" ")
inorder_traversal(root.right)
# Example Usage:
# Create a simple binary search tree
root = None
keys = [5, 3, 7, 2, 4, 6, 8]
1. Node Class:
• Represents a node in the binary search tree (BST).
2. insert Function:
• Inserts a new key into the BST.
• If the tree is empty, it creates a new node as the root.
• Otherwise, it recursively traverses the tree based on the key
value to find the appropriate position to insert the new node.
3. inorder_traversal Function:
• Performs an inorder traversal of the BST.
• Used here to print the elements of the tree in sorted order to
verify the insertion.
4. Example Usage:
• An instance of the Node class is created for the root of the
BST.
• Keys (5, 3, 7, 2, 4, 6, 8) are inserted into the BST using the
insert function.
• The inorder traversal is printed to verify the insertion.
This algorithm assumes that the keys to be inserted are unique and follows
the properties of a binary search tree where nodes in the left subtree are
A-LEVEL CS 9618 LINKED LIST/QUEUES/STACKS/BINARY TREE
less than the root, and nodes in the right subtree are greater than the
root.
Deleting a node from a binary tree involves handling various cases based on
the position of the node to be deleted. Below is an algorithm in Python
that demonstrates how to delete a node from a binary search tree (BST). The
algorithm covers three cases:
1. Deleting a node with no children (leaf node).
2. Deleting a node with one child.
3. Deleting a node with two children.
Explanation:
• The TreeNode class represents a node in the binary search tree (BST).
• The find_min function finds the node with the minimum key in a given
BST.
• The delete_node function handles the deletion of a node from the BST
based on the three cases mentioned above.
• The inorder_traversal function is used to print the elements of the
BST.
This algorithm can be adapted for other types of binary trees as well,
depending on the specific deletion requirements.
INSERTION SORT VS. BUBBLE SORT
Insertion Sort and Bubble Sort are both simple sorting algorithms, but they differ in how they operate
and their efficiency in various scenarios.
1. Algorithm Type
• Insertion Sort: Builds the sorted array by taking one element at a time and inserting it into the
correct position among the already sorted elements.
• Bubble Sort: Repeatedly compares adjacent elements and swaps them if they are in the wrong
order, gradually "bubbling" the largest elements to the end of the array.
2. Time Complexity
• Insertion Sort:
o Worst-case/Average: O(n²).
• Bubble Sort:
o Worst-case/Average: O(n²).
Both algorithms have a worst-case time complexity of O(n²), but Insertion Sort tends to perform better
than Bubble Sort in practice, especially on nearly sorted arrays.
• Insertion Sort: Fewer swaps are performed since elements are shifted and not swapped until the
correct position is found. Comparisons continue until the correct insertion point is identified.
• Bubble Sort: Swaps adjacent elements during each pass. In the worst case, each pass requires
numerous comparisons and swaps, even if the array is mostly sorted.
4. Stability
• Both Insertion Sort and Bubble Sort are stable algorithms, meaning they maintain the relative
order of equal elements.
5. Efficiency
• Insertion Sort: More efficient on smaller datasets or nearly sorted arrays due to its best-case
time complexity of O(n). It can be used for online sorting, where elements are inserted into a
sorted list as they are received.
• Bubble Sort: Very inefficient compared to most sorting algorithms. It performs many
unnecessary swaps, even when only a small part of the array is unsorted.
6. Use Case
INSERTION SORT VS. BUBBLE SORT
• Insertion Sort: Useful for small arrays or lists that are already close to sorted. It’s also often used
as a subroutine in more complex algorithms like hybrid sorting techniques (e.g., Timsort).
• Bubble Sort: Rarely used in practice due to its inefficiency, except as a teaching tool or for small
datasets when simplicity is the priority.
7. Example Walkthrough
• Insertion Sort:
o Start with the second element (1), compare and insert before 5 → [1, 5, 4, 2, 8]
• Bubble Sort:
o Continue swapping adjacent elements until no more swaps are needed → [1, 2, 4, 5, 8]
Summary of Differences:
Type Insert elements in the correct position Swap adjacent elements if out of order
Swaps Fewer swaps, more shifts More swaps, even for partially sorted
arrays
Use Case Small or nearly sorted datasets Simple sorting, often for teaching
INSERTION SORT VS. BUBBLE SORT
BUBBLE SORT
arr = [64, 34, 25, 12, 22, 11, 90] arr = [64, 34, 25, 12, 22, 11, 90]
bubble_sort(arr) bubble_sort(arr)
print("Sorted array:", arr) print("Sorted array:", arr)
INSERTION SORT VS. BUBBLE SORT
INSERTION SORT
1. Algorithm Type
3. Precondition
4. Implementation Simplicity
5. Use Case
• Linear Search: Best case is O(1), when the target is at the first position.
• Binary Search: Best case is O(1), when the target is the middle element.
Example:
LINEAR SEARCH
BINARY SEARCH
# Accessing methods
account.deposit(50) # Output: Deposited $50. New balance is $150.
Python Classes
account.withdraw(30) # Output: Withdrew $30. New balance is $120.
print(account.get_balance()) # Output: 120
Explanation
• __balance is a private attribute, so it cannot be accessed directly from
outside the class.
• deposit, withdraw, and get_balance methods allow controlled interaction
with the __balance attribute.
Example 3: Inheritance
Inheritance allows a class to inherit attributes and methods from another class.
# Base class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass # Abstract method, to be defined in subclasses
-----------------------------------------------------------------------------------
Exercise 2: Create a Vehicle class without any variables and
methods
-----------------------------------------------------------------------------------
Exercise 3: Inside the class called ‘Phone create two user-defined
functions:
-----------------------------------------------------------------------------------
Exercise 4:
Create a class vehicle that will consist of a constructor to hold
parameters Milage and cost of the vehicle.
class Bus(Vehicle):
pass
class Car(Vehicle):
pass
Expected Output:
Color: White, Vehicle name: School Volvo, Speed: 180, Mileage: 12
Color: White, Vehicle name: Audi Q5, Speed: 240, Mileage: 18
Hint-
Variables created in .__init__() are called instance variables. An instance
variable’s value is specific to a particular instance of the class. For example, in the
solution, All Vehicle objects have a name and a max_speed, but the name and
max_speed variables’ values will vary depending on the Vehicle instance.
On the other hand, the class variable is shared between all class instances. You
can define a class attribute by assigning a value to a variable name outside
of .__init__().
-----------------------------------------------------------------------------------
Python Classes and Inheritance Activities
Note: The bus seating capacity is 50. so the final fare amount should
be 5500. You need to override the fare() method of a Vehicle class in Bus class.
Use the following code for your parent Vehicle class. We need to access the
parent class from inside a method of a child class.
Expected Output:
Total Bus fare is: 5500.0
Python Classes and Inheritance Activities
Exercise Question 1: Create a Vehicle class with max_speed and mileage
instance attributes
class Vehicle:
def __init__(self, max_speed, mileage):
self.max_speed = max_speed
self.mileage = mileage
Exercise Question 2: Create a Vehicle class without any variables and methods
class Vehicle:
pass
Exercise Question 3: Create child class Bus that will inherit all
of the variables and methods of the Vehicle class
class Vehicle:
class Bus(Vehicle):
pass
Python Inheritance
Inheritance allows us to define a class that inherits all the methods and
properties from another class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived
class.
mrsaem@yahoo.com
Inheritance – Types of Inheritance in Python
Parent Class
Child Class 01
Example
Create a class named Person, with firstname and lastname properties, and
a printname method:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
mrsaem@yahoo.com
Inheritance – Types of Inheritance in Python
x = Person("John", "Doe")
x.printname()
Example
Create a class named Student, which will inherit the properties and
methods from the Person class:
class Student(Person):
pass
Note: Use the pass keyword when you do not want to add any other properties
or methods to the class.
Now the Student class has the same properties and methods as the Person
class.
Example
Use the Student class to create an object, and then execute
the printname method:
x = Student("Mike", "Olsen")
x.printname()
mrsaem@yahoo.com
Inheritance – Types of Inheritance in Python
We want to add the __init__() function to the child class (instead of
the pass keyword).
Note: The __init__() function is called automatically every time the class is
being used to create a new object.
Example
Add the __init__() function to the Student class:
class Student(Person):
def __init__(self, fname, lname):
#add properties etc.
When you add the __init__() function, the child class will no longer inherit the
parent's __init__() function.
To keep the inheritance of the parent's __init__() function, add a call to the
parent's __init__() function:
Example
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
mrsaem@yahoo.com
Inheritance – Types of Inheritance in Python
What Is Inheritance?
The method of inheriting the properties of parent class into a child class
is known as inheritance. It is an OOP concept. Following are the benefits
of inheritance.
class Parent():
def first(self):
print('first function')
class Child(Parent):
def second(self):
print('second function')
ob = Child()
ob.first()
ob.second()
Output:
first function
second function
mrsaem@yahoo.com
Inheritance – Types of Inheritance in Python
__init__( ) Function
The __init__() function is called every time a class is being used to make an object. When
we add the __init__() function in a parent class, the child class will no longer be able to
inherit the parent class’s __init__() function. The child’s class __init__() function overrides
the parent class’s __init__() function.
class Parent:
def __init__(self , fname, fage):
self.firstname = fname
self.age = fage
def view(self):
print(self.firstname , self.age)
class Child(Parent):
def __init__(self , fname , fage):
Parent.__init__(self, fname, fage)
self.lastname = "edureka"
def view(self):
print("course name" , self.firstname ,"first came", self.age , "
years ago." , self.lastname, " has courses to master python")
ob = Child("Python" , '28')
ob.view()
mrsaem@yahoo.com
Inheritance – Types of Inheritance in Python
Types Of Inheritance
Depending upon the number of child and parent classes involved, there are four
types of inheritance in python.
Single Inheritance
When child class is derived from only one parent class. This is called
single inheritance. The example we did above is the best example for
single inheritance in python programming.
Parent Class
Child Class 01
mrsaem@yahoo.com
Inheritance – Types of Inheritance in Python
class Parent:
def func1(self):
print("this is function one")
class Child(Parent):
def func2(self):
print(" this is function 2 ")
ob = Child()
ob.func1()
ob.func2()
mrsaem@yahoo.com
Inheritance – Types of Inheritance in Python
mrsaem@yahoo.com
Inheritance – Types of Inheritance in Python
Multiple Inheritance
When child class is derived or inherited from the more than one parent
classes. This is called multiple inheritance. In multiple inheritance, we
have two parent classes/base classes and one child class that inherits
both parent classes’ properties.
Child Class
When a child class inherits from more than one parent class.
class Parent:
def func1(self):
print("this is function 1")
class Parent2:
def func2(self):
print("this is function 2")
class Child(Parent , Parent2):
def func3(self):
print("this is function 3")
ob = Child()
ob.func1()
ob.func2()
ob.func3()
mrsaem@yahoo.com
Inheritance – Types of Inheritance in Python
mrsaem@yahoo.com
Inheritance – Types of Inheritance in Python
Multilevel Inheritance
In multilevel inheritance, we have one parent class and child class that is
derived or inherited from that parent class. We have a grand-child class
that is derived from the child class. See the below-given flow diagram to
understand more clearly.
When a child class becomes a parent class for another child class.
A Parent Class
B Child Class
mrsaem@yahoo.com
Inheritance – Types of Inheritance in Python
class Parent:
def func1(self):
print("this is function 1")
class Child(Parent):
def func2(self):
print("this is function 2")
class Child2(Child):
def func3("this is function 3")
ob = Child2()
ob.func1()
ob.func2()
ob.func3()
mrsaem@yahoo.com
Inheritance – Types of Inheritance in Python
mrsaem@yahoo.com
Inheritance – Types of Inheritance in Python
Hierarchical Inheritance
When we derive or inherit more than one child class from one(same)
parent class. Then this type of inheritance is called hierarchical
inheritance.
Hierarchical inheritance involves multiple inheritance from the same base or parent
class.
A
[Parent Class]
B C D
[Child Class] [Child Class] [Child Class]
class Parent:
def func1(self):
print("this is function 1")
class Child(Parent):
def func2(self):
print("this is function 2")
class Child2(Parent):
def func3(self):
print("this is function 3")
ob = Child()
ob1 = Child2()
ob.func1()
ob.func2()
mrsaem@yahoo.com
Inheritance – Types of Inheritance in Python
mrsaem@yahoo.com
Inheritance – Types of Inheritance in Python
Hybrid Inheritance
There is no sequence in Hybrid inheritance that which class will inherit which
particular class. You can use it according to your requirements.
class Parent:
def func1(self):
print("this is function one")
class Child(Parent):
def func2(self):
print("this is function 2")
class Child1(Parent):
def func3(self):
print(" this is function 3"):
ob = Child3()
ob.func1()
mrsaem@yahoo.com
Inheritance – Types of Inheritance in Python
and kick-start your learning enroll to Edureka’s python
certification program and become a python developer in no time.
mrsaem@yahoo.com
Python Inheritance
Inheritance allows us to define a class that inherits all the methods and
properties from another class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived
class.
Example
Create a class named Person, with firstname and lastname properties, and
a printname method:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
x = Person("John", "Doe")
x.printname()
Create a Child Class
To create a class that inherits the functionality from another class, send the
parent class as a parameter when creating the child class:
Example
Create a class named Student, which will inherit the properties and
methods from the Person class:
class Student(Person):
pass
Note: Use the pass keyword when you do not want to add any other properties
or methods to the class.
Now the Student class has the same properties and methods as the Person
class.
Example
Use the Student class to create an object, and then execute
the printname method:
x = Student("Mike", "Olsen")
x.printname()
Note: The __init__() function is called automatically every time the class is
being used to create a new object.
Example
Add the __init__() function to the Student class:
class Student(Person):
def __init__(self, fname, lname):
#add properties etc.
When you add the __init__() function, the child class will no longer inherit the
parent's __init__() function.
To keep the inheritance of the parent's __init__() function, add a call to the
parent's __init__() function:
Example
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
What Is Inheritance?
The method of inheriting the properties of parent class into a child class is known as
inheritance. It is an OOP concept. Following are the benefits of inheritance.
1. Code reusability- we do not have to write the same code again and again, we
can just inherit the properties we need in a child class.
2. It represents a real world relationship between parent class and child class.
3. It is transitive in nature. If a child class inherits properties from a parent class,
then all other sub-classes of the child class will also inherit the properties of
the parent class.
Below is a simple example of inheritance in python.
class Parent():
def first(self):
print('first function')
class Child(Parent):
def second(self):
print('second function')
ob = Child()
ob.first()
ob.second()
Output:
first function
second function
Sub-classing
Calling a constructor of the parent class by mentioning the parent class name in the
declaration of the child class is known as sub-classing. A child class identifies its
parent class by sub-classing.
__init__( ) Function
The __init__() function is called every time a class is being used to make an object.
When we add the __init__() function in a parent class, the child class will no longer be
able to inherit the parent class’s __init__() function. The child’s class __init__() function
overrides the parent class’s __init__() function.
class Parent:
def __init__(self , fname, fage):
self.firstname = fname
self.age = fage
def view(self):
print(self.firstname , self.age)
class Child(Parent):
def __init__(self , fname , fage):
Parent.__init__(self, fname, fage)
self.lastname = "edureka"
def view(self):
print("course name" , self.firstname ,"first
came", self.age , " years ago." , self.lastname, " has
courses to master python")
ob = Child("Python" , '28')
ob.view()
Types Of Inheritance
Depending upon the number of child and parent classes involved, there are four
types of inheritance in python.
Single Inheritance
When a child class inherits only a single parent class.
class Parent:
def func1(self):
print("this is function one")
class Child(Parent):
def func2(self):
print(" this is function 2 ")
ob = Child()
ob.func1()
ob.func2()
Multiple Inheritance
When a child class inherits from more than one parent class.
class Parent:
def func1(self):
print("this is function 1")
class Parent2:
def func2(self):
print("this is function 2")
class Child(Parent , Parent2):
def func3(self):
print("this is function 3")
ob = Child()
ob.func1()
ob.func2()
ob.func3()
Multilevel Inheritance
When a child class becomes a parent class for another child class.
class Parent:
def func1(self):
print("this is function 1")
class Child(Parent):
def func2(self):
print("this is function 2")
class Child2(Child):
def func3("this is function 3")
ob = Child2()
ob.func1()
ob.func2()
ob.func3()
Hierarchical Inheritance
Hierarchical inheritance involves multiple inheritance from the same base or parent
class.
class Parent:
def func1(self):
print("this is function 1")
class Child(Parent):
def func2(self):
print("this is function 2")
class Child2(Parent):
def func3(self):
print("this is function 3")
ob = Child()
ob1 = Child2()
ob.func1()
ob.func2()
Hybrid Inheritance
Hybrid inheritance involves multiple inheritance taking place in a single program.
class Parent:
def func1(self):
print("this is function one")
class Child(Parent):
def func2(self):
print("this is function 2")
class Child1(Parent):
def func3(self):
print(" this is function 3"):
ob = Child3()
ob.func1()
Recursion
WITH MRSAEM
www.mrsaem.com | www.sirsaem.com | 1
Chapter 25
A Level
What is recursion?
Recursion is the process of defining something
in terms of itself.
A physical world example would be to place
two parallel mirrors facing each other. Any
Recursion
def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-1))
Recursion
x = 3
print("The factorial of", x, "is",
factorial(x))
A very efficient way of programming is to make the same function work over and over
again in order to complete a task.
Recursion is a very powerful technique that can be used when programming an algorithm in
which there is a variable number of iterations. Recursive routines have two important
features:
Recursion
As a recursive routine calls itself there must be a way of stopping it or it will continue to call
itself for ever in a continuous loop.
Recursion is where a function or sub-routine calls itself as part of the overall process.
Some kind of limit is built in to the function so that recursion ends when a certain
condition is met.
A classic computer programming problem that make clever use of recursion is to find the
factorial of a number. i.e. 4 factorial is 4! = 4 x 3 x 2 x 1
Recursion
Now go back and see if you can understand the code. In particular, see if you can
identify the three laws of recursion :
•A recursive algorithm must have a base case.
•A recursive algorithm must change its state and move toward the base case.
•A recursive algorithm must call itself, recursively.
Recursion
The base case above is n <= 0. Without a base case and movement towards it at
each repeated function call, the program would never end – similar to what
happens when you write a while loop with a condition which never becomes true.
def greet():
A recursive function is a function which calls itself. print("Hello")
greet()
Now you have seen a recursive function and got some greet()
Recursion
p = fct(3)
Recursion
def fact(n):
if(n==0):
return 1
return n*fact(n-1)
Recursion
result =fact(5)
print(result)
x = txt.capitalize()
print (x)
x = txt.lower()
print(x)
x = txt.upper()
print(x)
Return the number of times the value "apple" appears in the string:
x = txt.count("apple")
print(x)
x = txt.find("welcome")
print(x)
Python Notes for A-Level Computer Science 9618
Join all items in a tuple into a string, using a hash character as separator:
x = "#".join(myTuple)
print(x)
x = txt.replace("bananas", "apples")
print(x)
x = txt.split()
print(x)
x = txt.startswith("Hello")
print(x)
Make the lower case letters upper case and the upper case letters lower case:
x = txt.swapcase()
print(x)
Python Notes for A-Level Computer Science 9618
Iterate String
To iterate through a string in Python, “for…in” notation is used.
str = "hello"
for c in str:
print(c)
# h
# e
# l
# l
# o
String Concatenation
To combine the content of two strings into a single string, Python provides
the + operator. This process of joining strings is called concatenation.
x = 'One fish, '
y = 'two fish.'
z = x + y
print(z)
# Output: One fish, two fish.
Python Notes for A-Level Computer Science 9618
Immutable strings
Strings are immutable in Python. This means that once a string has been
defined, it can’t be changed.
There are no mutating methods for strings. This is unlike data types like lists,
which can be modified once they are created.
IndexError
When indexing into a string in Python, if you try to access an index that
doesn’t exist, an IndexError is generated. For example, the following code
would create an IndexError:
fruit = "Berry"
indx = fruit[6]
If keywords are specified within the placeholders, they are replaced with the
corresponding named arguments to the method.
msg1 = 'Fred scored {} out of {} points.'
msg1.format(3, 10)
# => 'Fred scored 3 out of 10 points.'
print(greeting.lower())
# Prints: welcome to chili's
print(text.split())
# Prints: ['Silicon', 'Valley']
print(text.split('i'))
# Prints: ['S', 'l', 'con Valley']
String replace
The .replace() method is used to replace the occurence of the first argument
with the second argument within the string.
The first argument is the old substring to be replaced, and the second
argument is the new substring that will replace every occurence of the first
one within the string.
fruit = "Strawberry"
print(fruit.replace('r', 'R'))
# StRawbeRRy
print(dinosaur.upper())
# Prints: T-REX
The .join() method is run on the delimiter and the array of strings to be
concatenated together is passed in as an argument.
x = "-".join(["Codecademy", "is", "awesome"])
print(x)
# Prints: Codecademy-is-awesome
fruits.clear()
Python Notes for A-Level Computer Science 9618
Copy the fruits list:
x = fruits.copy()
x = fruits.count("cherry")
fruits.extend(cars)
Insert the value "orange" as the second element of the fruit list:
fruits.insert(1, "orange")
fruits.pop(1)
Python Notes for A-Level Computer Science 9618
Remove the "banana" element of the fruit list:
fruits.remove("banana")
fruits.reverse()
cars.sort()
x = fruits.index("cherry")
Loops
break Keyword
In a loop, the break keyword escapes the loop, regardless of the iteration
number. Once break executes, the program will continue to execute after the
loop.
Python Notes for A-Level Computer Science 9618
In this example, the output would be:
• 0
• 254
• 2
• Negative number detected!
# 0
# 254
# 2
# Negative number detected!
Python List Comprehension
Python list comprehensions provide a concise way for creating lists. It consists
of brackets containing an expression followed by a for clause, then zero or
more for or if clauses: [EXPRESSION for ITEM in LIST <if CONDITIONAL>] .
The expressions can be anything - any kind of object can go into a list.
print(result)
# [0, 4, 16, 36, 64]
Python For Loop
A Python for loop can be used to iterate over a list of items and perform a set
of actions on each item. The syntax of a for loop consists of assigning a
temporary value to a variable on each successive iteration.
Python Notes for A-Level Computer Science 9618
When writing a for loop, remember to properly indent each action, otherwise
an IndentationError will result.
for <temporary variable> in <list variable>:
<action statement>
<action statement>
Proper for loop syntax assigns a temporary value, the current item of the list,
to a variable on each successive iteration: for <temporary value> in <a list>:
The condition of a while loop is always checked first before the block of code
runs. If the condition is not met initially, then the code block will never run.
# This loop will only run 1 time
hungry = True
while hungry:
print("Time to eat!")
hungry = False
# This outer loop will iterate over each list in the groups
list
for group in groups:
# This inner loop will go through each name in each list
for name in group:
print(name)