Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python Notes by MR Saem

Download as pdf or txt
Download as pdf or txt
You are on page 1of 114

Python Notes for A-Level Computer Science 9618

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"

print("l" in game) # Prints: True


print("x" in game) # Prints: False

Indexing and Slicing Strings


Python strings can be indexed using the same notation as lists, since strings
are lists of characters. A single character can be accessed with bracket
notation ([index]), or a substring can be accessed using slicing ([start:end]).

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

# 1D Array using a list


array_1d = [1, 2, 3, 4, 5]
print(array_1d) # Output: [1, 2, 3, 4, 5]
print(array_1d[2]) # Access element at index 2, Output: 3

Using NumPy

import numpy as np

# 1D Array using NumPy


array_1d_np = np.array([1, 2, 3, 4, 5])
print(array_1d_np) # Output: [1 2 3 4 5]
print(array_1d_np[2]) # Access element at index 2, Output: 3

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 a List of Lists

# 2D Array using list of lists


array_2d = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(array_2d)
# Output:
# [[1, 2, 3],
# [4, 5, 6],
# [7, 8, 9]]
print(array_2d[1][2]) # Access element in row 1, column 2, Output: 6

Using NumPy

# 2D Array using NumPy


array_2d_np = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(array_2d_np)
# Output:
# [[1 2 3]
# [4 5 6]
1-dimensional (1D) or 2-dimensional (2D)

# [7 8 9]]
print(array_2d_np[1, 2]) # Access element in row 1, column 2, Output: 6

Advantages of Using NumPy Arrays

• 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

1. 1D Array: A single list of elements, accessed by one index.


2. 2D Array: A list of lists, accessed by two indices (row, column).

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

#1 print word 25 times


word = input('Enter a word: ')
for i in range(25):
print(word)

#2 print word 200 times on same line


word = input('Enter a word: ')
for i in range(200):
print(word, end=' ')
print()

#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()

#8 40 A's, then 50 B's


for i in range(40):
print('A', end='')
for i in range(50):
print('B', end='')
print()

#9 ABC 100 times


for i in range(100):
print('ABC', 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

#11 user says how many A's to print


num = eval(input('How many As to print? '))
for i in range(num):
print('A', end='')
print()
Python Conditions and If statements
Python supports the usual logical conditions from mathematics:

• 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

These conditions can be used in several ways, most commonly in "if


statements" and loops.

An "if statement" is written by using the if keyword.

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")

In this example a is equal to b, so the first condition is not true, but


the elif condition is true, so we print to screen that "a and b are equal".
Else
The else keyword catches anything which isn't caught by the preceding
conditions.

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".

You can also have an else without the elif:

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:

if a > b: print("a is greater than b")


Try it Yourself »

Short Hand If ... Else


If you have only one statement to execute, one for if, and one for else, you can
put it all on the same line:

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

The while Loop


With the while loop we can execute a set of statements as long as a condition is
true.

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.

The break Statement


With the break statement we can stop the loop even if the while condition is
true:

Example
Exit the loop when i is 3:

i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1

Python For Loops


A for loop is used for iterating over a sequence (that is either a list, a tuple, a
dictionary, a set, or a string).

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:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)
The for loop does not require an indexing variable to set beforehand.

Looping Through a String


Even strings are iterable objects, they contain a sequence of characters:

Example
Loop through the letters in the word "banana":

for x in "banana":
print(x)

The break Statement


With the break statement we can stop the loop before it has looped through all
the items:

Example
Exit the loop when x is "banana":

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)
if x == "banana":
break

Example
Exit the loop when x is "banana", but this time the break comes before the
print:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
if x == "banana":
break
print(x)
The range() Function
To loop through a set of code a specified number of times, we can use
the range() function,

The range() function returns a sequence of numbers, starting from 0 by


default, and increments by 1 (by default), and ends at a specified number.

Example
Using the range() function:

for x in range(6):
print(x)

The range() function defaults to 0 as a starting value, however it is possible to


specify the starting value by adding a parameter: range(2, 6), which means
values from 2 to 6 (but not including 6):

Example
Using the start parameter:

for x in range(2, 6):


print(x)

Python Functions
A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

A function can return data as a result.

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

Python List pop()


The pop() method removes the element at the specified position.
Remove the second element of the fruit list:
fruits = ['apple', 'banana', 'cherry']
fruits.pop(1)
print(fruits)
____________________________________________________
The pop() method removes the item at the given index from the list and returns
the removed item.
# create a list of prime numbers
prime_numbers = [2, 3, 5, 7]

# remove the element at index 2


removed_element = prime_numbers.pop(2)

print('Removed Element:', removed_element)


print('Updated List:', prime_numbers)

# create a list of prime numbers


prime_numbers = [2, 3, 5, 7]

# remove the element at index 2


removed_element = prime_numbers.pop(2)

print('Removed Element:', removed_element)


print('Updated List:', prime_numbers)
___________________________________________________________________________

Example 1: Pop item at the given index from the list


# programming languages list
languages = ['Python', 'Java', 'C++', 'French', 'C']

# remove and return the 4th item


return_value = languages.pop(3)

print('Return Value:', return_value)


Programming with Python for Paper 04 Computer Science 9618 A - LEVEL
# Updated List
print('Updated List:', languages)

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")

saem = Human("Saem Tariq","teacher")


saem.do_work()
saem.speaks()

subhan=Human("Subhan Aziz", "student")


subhan.do_work()
subhan.speaks()
Programming with Python for Paper 04 Computer Science 9618 A - LEVEL
___________________________________________________________________________
_______________

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: ")

# split the string into numbers & create a list of numbers


numbers = [int(x) for x in str_input.split()]

count = len(numbers)

for outer in range(count - 1): # bubbles each number to the end


for i in range(count - outer - 1):
if numbers[i] > numbers[i + 1]:
# swap numbers!
numbers[i], numbers[i + 1] = numbers[i + 1], numbers[i]

print(numbers)
Learning Python with Mr Saem

Create a New File


To create a new file in Python, use the open() method, with one of the following
parameters:

"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")

Result: a new empty file is created!

Example
Create a new file if it does not exist:
f = open("myfile.txt", "w")

Write to an Existing File


To write to an existing file, you must add a parameter to the open() function:

"a" - Append - will append to the end of the file

"w" - Write - will overwrite any existing content

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)

Built-in Math Functions


The min() and max() functions can be used to find the lowest or highest value in
an iterable:

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)

The pow(x, y) function returns the value of x to the power of y (xy).

Example
Return the value of 4 to the power of 3 (same as 4 * 4 * 4):

x = pow(4, 3)

print(x)

The Math Module


Python has also a built-in module called math, which extends the list of
mathematical functions.

To use it, you must import the math module:


import math

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))

#random floating number


floating = -30.33
print('Absolute value of -30.33 is:', abs(floating))

Output

Absolute value of -20 is: 20


Absolute value of -30.33 is: 30.33

Python any()
The any() function returns True if any element of an iterable is True. If not, any()
returns False.

Example 1: Using any() on Python Lists

# True since 1,3 and 4 (at least one) is true


l = [1, 3, 4, 0]
print(any(l))

# False since both are False


l = [0, False]
print(any(l))

# True since 5 is true


l = [0, False, 5]
print(any(l))

# False since iterable is empty


l = []
print(any(l))

Python chr()
The chr() method returns a character (a string) from an integer (represents unicode
code point of the character).

Example 1: How chr() works?

print(chr(97))
print(chr(65))
print(chr(1200))

Python len()
The len() function returns the number of items (length) in an object.

Example 1: How len() works with tuples, lists and range?

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))

testRange = range(1, 10)


print('Length of', testRange, 'is', len(testRange))
Output

[] 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.

Example 1: Using reveresed() in string, tuple, list, and


range

# 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

['n', 'o', 'h', 't', 'y', 'P']


['n', 'o', 'h', 't', 'y', 'P']
[8, 7, 6, 5]
[5, 3, 4, 2, 1]
Python round()
The round() function returns a floating-point number rounded to the specified
number of decimals.

Example 1: How round() works in Python?

# for integers
print(round(10))

# for floating point


print(round(10.7))

# 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.

Example 1: Sort string, list, and tuple

# 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

['a', 'e', 'i', 'o', 'u']


['P', 'h', 'n', 'o', 't', 'y']
['a', 'e', 'i', 'o', 'u']

Python sum()
The sum() function adds the items of an iterable and returns the sum.

Example: Working of Python sum()

numbers = [2.5, 3, 4, -5]

# start parameter is not provided


numbers_sum = sum(numbers)
print(numbers_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

Write algorithms in python to insert an item into a stack

Code in Python Pseudocode

# Stack implementation using // Stack implementation using a list


a list stack ← EmptyList
stack = [] // Function to check if the stack is empty
Function IsEmpty()
def is_empty(): // Output: True if the stack is empty,
return len(stack) == 0 False otherwise
Return Length(stack) = 0
def push(item): End Function
stack.append(item) // Function to push items onto the stack
print(f"Pushed {item} Procedure Push(item)
into the stack") // Input: item - the item to be pushed
onto the stack
# Example Usage: Append(stack, item)
# Insert items into the Output "Pushed", item, "into the
stack stack"
push(5) End Procedure
push("Hello") // Example Usage:
push(3.14) // Insert items into the stack
Call Push(5)
Call Push("Hello")
Call Push(3.14)

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

User defined stack limit input

Code in Python

def create_stack_with_limit(limit):
return [], limit

def is_empty(stack):
return len(stack) == 0

def is_full(stack, limit):


return len(stack) == limit

def push(stack, limit, item):


if is_full(stack, limit):
print("Stack is full. Cannot push item:", item)
else:
stack.append(item)
print(f"Pushed {item} into the stack")

def display_stack(stack):
print("Stack:", stack)

# User input for stack size


stack_limit = int(input("Enter the stack size: "))

# Explicitly assign the values from create_stack_with_limit


stack, limit = create_stack_with_limit(stack_limit)

# User input for items


num_items = int(input("Enter the number of items to push: "))
for x in range(num_items):
item = input("Enter item to push into the stack: ")
push(stack, limit, item)

# Display the current stack


display_stack(stack)
A-LEVEL CS 9618 LINKED LIST/QUEUES/STACKS/BINARY TREE

Pseudocode

// Function to create a stack with a limit


Function CreateStackWithLimit(limit)
// Output: a new stack and its limit
Return EmptyList, limit
End Function
// Function to check if the stack is empty
Function IsEmpty(stack)
// Input: stack - the stack to check
// Output: True if the stack is empty, False otherwise
Return Length(stack) = 0
End Function
// Function to check if the stack is full
Function IsFull(stack, limit)
// Input: stack - the stack to check, limit - the limit of the
stack
// Output: True if the stack is full, False otherwise
Return Length(stack) = limit
End Function
// Procedure to push an item onto the stack
Procedure Push(stack, limit, item)
// Input: stack - the stack to push onto, limit - the limit of
the stack, item - the item to push
If IsFull(stack, limit) Then
Output "Stack is full. Cannot push item:", item
Else
Append(stack, item)
Output "Pushed", item, "into the stack"
End If
End Procedure
// Procedure to display the current state of the stack
Procedure DisplayStack(stack)
// Input: stack - the stack to display
Output "Stack:", stack
End Procedure
// User input for stack size
stack_limit ← Input("Enter the stack size:")

// Explicitly assign the values from CreateStackWithLimit


stack, limit ← CreateStackWithLimit(stack_limit)

// User input for items


num_items ← Input("Enter the number of items to push:")
For x in Range(num_items)
item ← Input("Enter item to push into the stack:")
Call Push(stack, limit, item)
End For

// Display the current stack


Call DisplayStack(stack)
A-LEVEL CS 9618 LINKED LIST/QUEUES/STACKS/BINARY TREE

Write algorithms in python to delete an item from a stack

Code in Python

# Stack implementation using a list


stack = []

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)

# Delete (pop) items from the stack


pop()
pop()
pop()
pop() # Trying to pop from an empty stack

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

// Stack implementation using a list


stack ← EmptyList

// Function to check if the stack is empty


Function IsEmpty()
// Output: True if the stack is empty, False otherwise
Return Length(stack) = 0
End Function

// Function to push items onto the stack


Procedure Push(item)
// Input: item - the item to be pushed onto the stack
Append(stack, item)
Output "Pushed", item, "into the stack"
End Procedure

// Function to pop an item from the stack


Function Pop()
// Output: the popped item from the stack, or an
indication if the stack is empty
If NOT IsEmpty() Then
item ← RemoveLast(stack)
Output "Popped", item, "from the stack"
Return item
Else
Output "Stack is empty. Cannot pop."
End If
End Function

// Example Usage: // Insert items into the stack


Call Push(5)
Call Push("Hello")
Call Push(3.14)

// Delete (pop) items from the stack


Call Pop()
Call Pop()
Call Pop()
Call Pop() // Trying to pop from an empty stack
A-LEVEL CS 9618 LINKED LIST/QUEUES/STACKS/BINARY TREE

Write algorithms in python to insert an item into a queue


Code in Python

# Queue implementation using a list


queue = []

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

# Queue implementation using a list

# Initialize an empty queue


queue <- []

# Function to check if the queue is empty


function is_empty() -> boolean
return length(queue) = 0

# Function to enqueue an item


function enqueue(item)
append item to queue
output "Enqueued " + item + " into the queue"

# Example Usage:
# Insert items into the queue
enqueue(5)
enqueue("Hello")
enqueue(3.14)
A-LEVEL CS 9618 LINKED LIST/QUEUES/STACKS/BINARY TREE

Write algorithms in python to delete an item from a queue


To delete (dequeue) an item from a queue in Python, you can use the pop method of a list, or you can
use the collections.deque class for more efficient dequeue operations. Here's an example using a
simple list:
Code in Python

# Queue implementation using a list


queue = []

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)

# Delete (dequeue) items from the queue


dequeue()
dequeue()
dequeue()
dequeue() # Trying to dequeue from an empty queue

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

# Queue implementation using a list


# Initialize an empty queue
queue <- []
# Function to check if the queue is empty
function is_empty() -> boolean
return length(queue) = 0
# Function to enqueue an item
function enqueue(item)
append item to queue
output "Enqueued " + item + " into the queue"
# Function to dequeue an item
function dequeue() -> item
if not is_empty() then
item <- remove first item from queue
output "Dequeued " + item + " from the queue"
return item
else
output "Queue is empty. Cannot dequeue."
return null
# Example Usage:
# Insert items into the queue
enqueue(5)
enqueue("Hello")
enqueue(3.14)

# Delete (dequeue) items from the queue


dequeue()
dequeue()
dequeue()
dequeue() # Trying to dequeue from an empty queue
A-LEVEL CS 9618 LINKED LIST/QUEUES/STACKS/BINARY TREE

Write algorithms in python to insert an item into a linked list

Code in Python

def create_node(data):
return {"data": data, "next": None}

def insert_at_end(head, new_data):


new_node = create_node(new_data)

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

# Insert items into the linked list


head = insert_at_end(head, 5)
head = insert_at_end(head, 10)
head = insert_at_end(head, 15)

# Print the linked list


print_linked_list(head)
A-LEVEL CS 9618 LINKED LIST/QUEUES/STACKS/BINARY TREE

Write algorithms in python to delete an item from a linked list

Code in Python

class Node:
def __init__(self, data):
self.data = data
self.next = None

def delete_node(head, key):


current = head
previous = None

# Search for the node with the key


while current is not None and current.data != key:
previous = current
current = current.next

# If the node with the key is found, delete it


if current is not None:
# If the node to be deleted is the first node
if previous is None:
head = current.next
else:
previous.next = current.next

print(f"Deleted node with data: {key}")


else:
print(f"Node with data {key} not found in the linked list")

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)

# Print the original linked list


print("Original Linked List:")
print_linked_list(head)

# Delete a node with data 3


head = delete_node(head, 3)

# Print the linked list after deletion


print("\nLinked List after Deletion:")
print_linked_list(head)
A-LEVEL CS 9618 LINKED LIST/QUEUES/STACKS/BINARY TREE

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

Write algorithms in python to delete an item from a linked list

PseudoCode in Python

# Node creation function


function create_node(data) -> node
return {"data": data, "next": null}

# Function to insert a node at the end of the linked list


function insert_at_end(head, new_data) -> head
new_node <- create_node(new_data)

if head is null then


head <- new_node
else
current <- head
while current["next"] is not null do
current <- current["next"]
end while
current["next"] <- new_node

return head

# Function to print the linked list


function print_linked_list(head)
current <- head
while current is not null do
output current["data"], " -> "
current <- current["next"]
end while
output "None"

# Example Usage:
# Create a linked list
head <- null

# Insert items into the linked list


head <- insert_at_end(head, 5)
head <- insert_at_end(head, 10)
head <- insert_at_end(head, 15)

# Print the linked list


print_linked_list(head)
A-LEVEL CS 9618 LINKED LIST/QUEUES/STACKS/BINARY TREE

USING A CLASS INSERT INTO A LINKED LIST


class Node:
def __init__(self, data):
self.data = data
self.next = None

def insert_at_end(head, new_data):


new_node = Node(new_data)

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

# Insert items into the linked list


head = insert_at_end(head, 5)
head = insert_at_end(head, 10)
head = insert_at_end(head, 15)

# Print the linked list


print_linked_list(head)

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

Write algorithms in python to insert an item into a Binary Tree

class TreeNode:
def __init__(self, key):
self.key = key
self.left = None
self.right = None

def insert(root, key):


if root is None:
return TreeNode(key)

if key < root.key:


root.left = insert(root.left, key)
elif key > root.key:
root.right = insert(root.right, key)

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]

for key in keys:


root = insert(root, key)

# Print the inorder traversal to verify insertion


inorder_traversal(root)

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.

Write algorithms in python to delete an item from a Binary Tree

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 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 Best-case: O(n) (when the list is already sorted).

o Worst-case/Average: O(n²).

• Bubble Sort:

o Best-case: O(n) (when the list is already sorted).

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.

3. Number of Comparisons and Swaps

• 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

For an array [5, 1, 4, 2, 8]:

• Insertion Sort:

o Start with the second element (1), compare and insert before 5 → [1, 5, 4, 2, 8]

o Next, 4 is inserted between 1 and 5 → [1, 4, 5, 2, 8]

o Continue until sorted → [1, 2, 4, 5, 8]

• Bubble Sort:

o Compare 5 and 1, swap them → [1, 5, 4, 2, 8]

o Compare 5 and 4, swap them → [1, 4, 5, 2, 8]

o Continue swapping adjacent elements until no more swaps are needed → [1, 2, 4, 5, 8]

Summary of Differences:

Feature Insertion Sort Bubble Sort

Type Insert elements in the correct position Swap adjacent elements if out of order

Best-case O(n) (already sorted) O(n) (already sorted)

Worst- O(n²) O(n²)


case

Swaps Fewer swaps, more shifts More swaps, even for partially sorted
arrays

Efficiency More efficient on small/nearly sorted Less efficient in general


arrays

Use Case Small or nearly sorted datasets Simple sorting, often for teaching
INSERTION SORT VS. BUBBLE SORT

BUBBLE SORT

PYTHON CODE PSEUOCODE


# Bubble Sort Algorithm # Bubble Sort Algorithm
def bubble_sort(arr): def bubble_sort(arr):
n = len(arr) n = len(arr)

# Traverse through all array elements


# Traverse through all array elements
for i in range(n):
for i in range(n): # Last i elements are already
# Last i elements are already sorted sorted
for j in range(0, n - i - 1): for j in range(0, n - i - 1):
# Swap if the element found is # Swap if the element found is
greater than the next element greater than the next element
if arr[j] > arr[j + 1]: if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j arr[j], arr[j + 1] = arr[j
+ 1], arr[j] # Swap using tuple unpacking + 1], arr[j] # Swap using tuple unpacking

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

PYTHON CODE PSEUOCODE


# Insertion Sort Algorithm FUNCTION InsertionSort(arr)
def insertion_sort(arr): // Input: arr (array of elements)
# Traverse through 1 to len(arr) // Output: Sorted array
for i in range(1, len(arr)):
key = arr[i] # Element to be inserted FOR i FROM 1 TO LENGTH(arr) - 1 DO
j = i - 1 key ← arr[i] // The current
# j is initialized to the index right before i, as we want to compare key with each element before it to element to be inserted
find the correct insertion position.
# Move elements of arr[0...i-1], that are j ← i - 1
greater than key,
# to one position ahead of their current // Move elements of arr[0...i-1],
position that are greater than key, to one position
while j >= 0 and arr[j] > key: ahead
arr[j + 1] = arr[j] # Shift element WHILE j ≥ 0 AND arr[j] > key DO
to the right arr[j + 1] ← arr[j] // Shift
j -= 1 element to the right
# j -= 1 moves the index j one step back to keep checking the previous elements. j ← j - 1
arr[j + 1] = key # Insert the key at the END WHILE
correct position
arr[j + 1] ← key // Insert the key
arr = [12, 11, 13, 5, 6] at its correct position
insertion_sort(arr) END FOR
print("Sorted array:", arr) END FUNCTION
BINARY SEARCH AND LINEAR SEARCH
The key differences between binary search and linear search lie in how they
operate and their efficiency. Here's a comparison:

1. Algorithm Type

• Linear Search: A sequential search algorithm. It checks each element one


by one from the start until the target element is found or the list ends.
• Binary Search: A divide-and-conquer algorithm. It repeatedly divides the
sorted list in half, checking if the middle element matches the target, and then
deciding whether to search the left or right half.

2. Efficiency (Time Complexity)

• Linear Search: Time complexity is O(n), where n is the number of elements.


In the worst case, it needs to check every element.
• Binary Search: Time complexity is O(log n), where n is the number of
elements. The list size is halved with each comparison, making it faster for
large datasets, but the list must be sorted.

3. Precondition

• Linear Search: Works on both sorted and unsorted lists.


• Binary Search: Only works on sorted lists.

4. Implementation Simplicity

• Linear Search: Simple to implement. No need for pre-sorting or index


manipulation.
• Binary Search: More complex to implement, requires indexing and list sorting
(if the list isn't sorted initially).

5. Use Case

• Linear Search: Preferred for small or unsorted datasets.


• Binary Search: Preferred for large datasets that are already sorted.

6. Best Case Time Complexity

• 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: Looking for an item in a list of 10 elements might take up to


10 comparisons in the worst case.
• Binary Search: Searching the same sorted list only takes a maximum of 4
comparisons (log2(10) ≈ 3.32), making it much faster for large data sets.
BINARY SEARCH AND LINEAR SEARCH

LINEAR SEARCH

PYTHON CODE PSEUOCODE


def search(list, n): FUNCTION LinearSearch(arr, target)
for element in list:
if element == n: FOR i FROM 0 TO LENGTH(arr) - 1 DO
return True IF arr[i] = target THEN
return False RETURN i // Target found, return the
index
list = [5, 8, 4, 6, 9, 2] END IF
n = 8 END FOR

if search(list, n): RETURN -1 // Target not found


print("Found") END FUNCTION
else:
print("Not Found")
BINARY SEARCH AND LINEAR SEARCH

BINARY SEARCH

PYTHON CODE PSEUOCODE


# Binary Search Algorithm FUNCTION BinarySearch(arr, target)
def binary_search(arr, target):
low = 0 low ← 0
high = len(arr) - 1 high ← LENGTH(arr) - 1

while low <= high: WHILE low ≤ high DO


mid = (low + high) // 2 # Calculate the mid ← (low + high) DIV 2 //
middle index Calculate the middle index
if arr[mid] == target: IF arr[mid] = target THEN
return mid # Target found, return its RETURN mid // Target found,
index return its index
elif arr[mid] < target: ELSE IF arr[mid] < target THEN
low = mid + 1 # Search the right half low ← mid + 1 // Search in the
else: right half
high = mid - 1 # Search the left half ELSE
high ← mid - 1 // Search in the
return -1 # Target not found left half
END IF
arr = [1, 3, 5, 7, 9, 11, 13] END WHILE
target = 7
result = binary_search(arr, target) RETURN -1 // Target not found
END FUNCTION
if result != -1:
print(f"Element found at index {result}")
else:
print("Element not found")
Python Classes
In Python, a class is a blueprint for creating objects. Classes encapsulate data
(attributes) and behavior (methods) together, making code more organized and
reusable. Here’s an introduction to Python classes with examples.
Basic Structure of a Class
A class typically contains:
• Attributes: Variables that hold data related to the class.
• Methods: Functions defined inside the class that describe its behavior.
Example 1: Simple Class
Here's a basic example of a class representing a Car.
class Car:
# Constructor method
def __init__(self, make, model, year):
# Attributes
self.make = make
self.model = model
self.year = year

# Method to describe the car


def description(self):
return f"{self.year} {self.make} {self.model}"

# Method to start the car


def start(self):
print(f"{self.model} is starting...")

# Creating an instance of the Car class


my_car = Car("Toyota", "Corolla", 2020)

# Accessing attributes and methods


print(my_car.description()) # Output: 2020 Toyota Corolla
my_car.start() # Output: Corolla is starting...
Explanation
• __init__ is the constructor method. It initializes the object with the provided
make, model, and year.
• description and start are methods that define behaviors for the Car class.
Python Classes
• my_car is an instance of the Car class, with attributes accessed via
my_car.attribute_name.
Example 2: Class with Encapsulation
Encapsulation is the concept of hiding data from direct access. This is achieved by
defining private attributes (using a single underscore _ or double underscores __).
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.__balance = balance # Private attribute

# Method to deposit money


def deposit(self, amount):
if amount > 0:
self.__balance += amount
print(f"Deposited ${amount}. New balance is ${self.__balance}.")
else:
print("Deposit amount must be positive.")

# Method to withdraw money


def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
print(f"Withdrew ${amount}. New balance is ${self.__balance}.")
else:
print("Invalid withdrawal amount.")

# Method to get the balance


def get_balance(self):
return self.__balance

# Creating an instance of the BankAccount class


account = BankAccount("Alice", 100)

# 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

# Derived class for Dog


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

# Derived class for Cat


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

# Creating instances of subclasses


dog = Dog("Buddy")
cat = Cat("Whiskers")

print(dog.speak()) # Output: Buddy says Woof!


print(cat.speak()) # Output: Whiskers says Meow!
Explanation
• The Animal class is the base class.
Python Classes
• Dog and Cat are derived classes that inherit from Animal and override the
speak method.
Key Points
• Class: Blueprint for creating objects.
• Object: An instance of a class.
• Constructor (__init__): Initializes new objects.
• Encapsulation: Hides data using private attributes.
• Inheritance: Allows classes to inherit methods and attributes from a parent
class.
This introduction should help you start working with classes in Python!
Python Classes and Inheritance Activities
Python Object-Oriented Programming (OOP) Exercise: Classes and
Objects Exercises

Exercise 1: Create a Vehicle class with max_speed and mileage


instance attributes

-----------------------------------------------------------------------------------
Exercise 2: Create a Vehicle class without any variables and
methods
-----------------------------------------------------------------------------------
Exercise 3: Inside the class called ‘Phone create two user-defined
functions:

make_call() and play_game().


make_call() method is just printing out “making a phone call” and
play_game() method is just printing out ‘Playing Game’.

-----------------------------------------------------------------------------------

Exercise 4:
Create a class vehicle that will consist of a constructor to hold
parameters Milage and cost of the vehicle.

Hint- Use def show_details to print the output.


Python Classes and Inheritance Activities
Exercise 5: Define property that should have the same value for
every class instance
Define a class attribute”color” with a default value white. I.e., Every Vehicle
should be white.
Use the following code for this exercise.
class Vehicle:
def __init__(self, name, max_speed, mileage):
self.name = name
self.max_speed = max_speed
self.mileage = mileage

class Bus(Vehicle):
pass

class Car(Vehicle):
pass

complete the rest

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

Exercise 6: Class Inheritance


Given:
Create a Bus child class that inherits from the Vehicle class. The default fare
charge of any vehicle is seating capacity * 100. If Vehicle is Bus instance, we
need to add an extra 10% on full fare as a maintenance charge. So total fare for
bus instance will become the final amount = total fare + 10% of the total fare.

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

modelX = Vehicle(240, 18)


print(modelX.max_speed, modelX.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:

def __init__(self, name, max_speed, mileage):


self.name = name
self.max_speed = max_speed
self.mileage = mileage

class Bus(Vehicle):
pass

School_bus = Bus("School Volvo", 180, 12)


print("Vehicle Name:", School_bus.name, "Speed:",
School_bus.max_speed, "Mileage:", School_bus.mileage)
Inheritance – Types of Inheritance in Python

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

Create a Parent Class


Any class can be a parent class, so the syntax is the same as creating any other
class:

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)

#Use the Person class to create an object, and then execute


the printname method:

mrsaem@yahoo.com
Inheritance – Types of Inheritance in Python
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()

Add the __init__() Function


So far we have created a child class that inherits the properties and methods
from its parent.

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.

Note: The child's __init__() function overrides the inheritance of 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.

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

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.

When a child class inherits only a single parent class.

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.

Parent Class 01 Parent Class 01

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

C Grand 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.

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"):

class Child3(Parent , Child1):


def func4(self):
print(" this is function 4")

ob = Child3()
ob.func1()

Inheritance is one of the most important concept of OOP. It


provides code reusability, readability and transition of properties
which helps in optimized and efficient code building. Python
programming language is loaded with concepts like inheritance.
Enormous python applications calls for increased number of
python programmers in the recent market. To master your skills

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.

Create a Parent Class


Any class can be a parent class, so the syntax is the same as creating any other
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)

#Use the Person class to create an object, and then execute


the printname method:

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()

Add the __init__() Function


So far we have created a child class that inherits the properties and methods
from its parent.

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.

Note: The child's __init__() function overrides the inheritance of 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"):

class Child3(Parent , Child1):


def func4(self):
print(" this is function 4")

ob = Child3()
ob.func1()

Inheritance is one of the most important concept of OOP. It


provides code reusability, readability and transition of properties
which helps in optimized and efficient code building. Python
programming language is loaded with concepts like inheritance.
Enormous python applications calls for increased number of
python programmers in the recent market. To master your skills
and kick-start your learning enroll to Edureka’s python
certification program and become a python developer in no time.
Chapter 25

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

object in between them would be reflected


recursively.

www.mrsaem.com | www.sirsaem.com | mrsaem@yahoo.com


2
Chapter 25
A Level
Recursion

www.mrsaem.com | www.sirsaem.com | mrsaem@yahoo.com


3
Chapter 25
A Level

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))

www.mrsaem.com | www.sirsaem.com | mrsaem@yahoo.com


4
Chapter 25
A Level
Recursion

www.mrsaem.com | www.sirsaem.com | mrsaem@yahoo.com


5
Chapter 25
A Level
Recursion

www.mrsaem.com | www.sirsaem.com | mrsaem@yahoo.com


6
Chapter 25
A Level

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

•a recursive routine calls itself

•it must have a terminating condition.

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.

www.mrsaem.com | www.sirsaem.com | mrsaem@yahoo.com


7
Chapter 25
A Level
Another Defination
One way of doing this is to use 'Recursion'.

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

www.mrsaem.com | www.sirsaem.com | mrsaem@yahoo.com


8
Chapter 25
A Level

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.

www.mrsaem.com | www.sirsaem.com | mrsaem@yahoo.com


9
Chapter 25
A Level

In terms of a basic intuitive understanding, the third


law is probably the most important:

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

understanding of what they involve, it’s time for some


practice. Following are two exercises to help you
develop your skill and understanding with recursion.
Make sure you give each one a really good try on your
own before looking at the solution, in order to get the
most out of the exercises.

www.mrsaem.com | www.sirsaem.com | mrsaem@yahoo.com


10
Chapter 25
A Level

To start it off the following


statement is written

p = fct(3)
Recursion

www.mrsaem.com | www.sirsaem.com | mrsaem@yahoo.com


11
Chapter 25
A Level

def fact(n):
if(n==0):
return 1
return n*fact(n-1)
Recursion

result =fact(5)
print(result)

www.mrsaem.com | www.sirsaem.com | mrsaem@yahoo.com


12
Chapter 25
A Level
Advantages of Recursion

1.Recursive functions make the code look clean and elegant.


2.A complex task can be broken down into simpler sub-problems using recursion.
3.Sequence generation is easier with recursion than using some nested iteration.
Recursion

www.mrsaem.com | www.sirsaem.com | mrsaem@yahoo.com


13
Chapter 25
A Level
Disadvantages of Recursion

1.Sometimes the logic behind recursion is hard to follow through.


2.Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
3.Recursive functions are hard to debug.
Recursion

www.mrsaem.com | www.sirsaem.com | mrsaem@yahoo.com


14
Python Notes for A-Level Computer Science 9618
txt = "hello, and welcome to my world."

x = txt.capitalize()

print (x)

txt = "Hello my FRIENDS"

x = txt.lower()

print(x)

txt = "Hello my friends"

x = txt.upper()

print(x)

Return the number of times the value "apple" appears in the string:

txt = "I love apples, apple are my favorite fruit"

x = txt.count("apple")

print(x)

Where in the text is the word "welcome"?:

txt = "Hello, welcome to my world."

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:

myTuple = ("John", "Peter", "Vicky")

x = "#".join(myTuple)

print(x)

Replace the word "bananas":

txt = "I like bananas"

x = txt.replace("bananas", "apples")

print(x)

Split a string into a list where each word is a list item:

txt = "welcome to the jungle"

x = txt.split()

print(x)

Check if the string starts with "Hello":

txt = "Hello, welcome to my world."

x = txt.startswith("Hello")

print(x)

Make the lower case letters upper case and the upper case letters lower case:

txt = "Hello My Name Is PETER"

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

Built-in Function len()


In Python, the built-in len() function can be used to determine the length of
an object. It can be used to compute the length of strings, lists, sets, and other
countable objects.
length = len("Hello")
print(length)
# Output: 5

colors = ['red', 'yellow', 'green']


print(len(colors))
# Output: 3

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]

Python String .format()


The Python string method .format() replaces empty brace ({}) placeholders in
the string with its arguments.

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.'

msg2 = 'Fred {verb} a {adjective} {noun}.'


msg2.format(adjective='fluffy', verb='tickled', noun='hamster')
# => 'Fred tickled a fluffy hamster.'

String Method .lower()


The string method .lower() returns a string with all uppercase characters
converted into lowercase.
Python Notes for A-Level Computer Science 9618
greeting = "Welcome To Chili's"

print(greeting.lower())
# Prints: welcome to chili's

String Method .strip()


The string method .strip() can be used to remove characters from the
beginning and end of a string.

A string argument can be passed to the method, specifying the set of


characters to be stripped. With no arguments to the method, whitespace is
removed.
text1 = ' apples and oranges '
text1.strip() # => 'apples and oranges'

text2 = '...+...lemons and limes...-...'

# Here we strip just the "." characters


text2.strip('.') # => '+...lemons and limes...-'

# Here we strip both "." and "+" characters


text2.strip('.+') # => 'lemons and limes...-'

# Here we strip ".", "+", and "-" characters


text2.strip('.+-') # => 'lemons and limes'

String Method .title()


The string method .title() returns the string in title case. With title case, the
first character of each word is capitalized while the rest of the characters are
lowercase.
my_var = "dark knight"
print(my_var.title())

# Prints: Dark Knight

String Method .split()


Python Notes for A-Level Computer Science 9618
The string method .split() splits a string into a list of items:

• If no argument is passed, the default behavior is to split on whitespace.


• If an argument is passed to the method, that value is used as the
delimiter on which to split the string.

text = "Silicon Valley"

print(text.split())
# Prints: ['Silicon', 'Valley']

print(text.split('i'))
# Prints: ['S', 'l', 'con Valley']

Python string method .find()


The Python string method .find() returns the index of the first occurrence of
the string passed as the argument. It returns -1 if no occurrence is found.
mountain_name = "Mount Kilimanjaro"
print(mountain_name.find("o")) # Prints 1 in the console.

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

String Method .upper()


The string method .upper() returns the string with all lowercase characters
converted to uppercase.
Python Notes for A-Level Computer Science 9618
dinosaur = "T-Rex"

print(dinosaur.upper())
# Prints: T-REX

String Method .join()


The string method .join() concatenates a list of strings together to create a
new string joined with the desired delimiter.

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

Python List/Array Methods


Add an element to the fruits list:

fruits = ['apple', 'banana', 'cherry']


fruits.append("orange")

Remove all elements from the fruits list:

fruits = ['apple', 'banana', 'cherry', 'orange']

fruits.clear()
Python Notes for A-Level Computer Science 9618
Copy the fruits list:

fruits = ['apple', 'banana', 'cherry', 'orange']

x = fruits.copy()

Return the number of times the value "cherry" appears int


the fruits list:

fruits = ['apple', 'banana', 'cherry']

x = fruits.count("cherry")

Add the elements of cars to the fruits list:

fruits = ['apple', 'banana', 'cherry']

cars = ['Ford', 'BMW', 'Volvo']

fruits.extend(cars)

Insert the value "orange" as the second element of the fruit list:

fruits = ['apple', 'banana', 'cherry']

fruits.insert(1, "orange")

Remove the second element of the fruit list:

fruits = ['apple', 'banana', 'cherry']

fruits.pop(1)
Python Notes for A-Level Computer Science 9618
Remove the "banana" element of the fruit list:

fruits = ['apple', 'banana', 'cherry']

fruits.remove("banana")

Reverse the order of the fruit list:

fruits = ['apple', 'banana', 'cherry']

fruits.reverse()

Sort the list alphabetically:

cars = ['Ford', 'BMW', 'Volvo']

cars.sort()

What is the position of the value "cherry":

fruits = ['apple', 'banana', 'cherry']

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!

numbers = [0, 254, 2, -1, 3]

for num in numbers:


if (num < 0):
print("Negative number detected!")
break
print(num)

# 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.

A list comprehension always returns a list.


# List comprehension for the squares of all even numbers
between 0 and 9
result = [x**2 for x in range(10) if x % 2 == 0]

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>

#each num in nums will be printed below


nums = [1,2,3,4,5]
for num in nums:
print(num)
The Python continue Keyword
In Python, the continue keyword is used inside a loop to skip the remaining
code inside the loop code block and begin the next loop iteration.
big_number_list = [1, 2, -1, 4, -5, 5, 2, -9]

# Print only positive numbers:


for i in big_number_list:
if i < 0:
continue
print(i)
Python for Loops
Python for loops can be used to iterate over and perform an action one time
for each element in a list.

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>:

forloop bodies must be indented to avoid an IndentationError.


dog_breeds = ["boxer", "bulldog", "shiba inu"]

# Print each breed:


for breed in dog_breeds:
print(breed)
Python Loops with range().
In Python, a for loop can be used to perform an action a specific number of
times in a row.
Python Notes for A-Level Computer Science 9618
The range() function can be used to create a list that can be used to specify the
number of iterations in a for loop.
# Print the numbers 0, 1, 2:
for i in range(3):
print(i)

# Print "WARNING" 3 times:


for i in range(3):
print("WARNING")
Infinite Loop
An infinite loop is a loop that never terminates. Infinite loops result when the
conditions of the loop prevent it from terminating. This could be due to a typo
in the conditional statement within the loop or incorrect logic. To interrupt a
Python program that is running forever, press the Ctrl and C keys together on
your keyboard.
Python while Loops
In Python, a while loop will repeatedly execute a code block as long as a
condition evaluates to True.

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 loop will run 5 times


i = 1
while i < 6:
print(i)
i = i + 1
Python Nested Loops
In Python, loops can be nested inside other loops. Nested loops can be used
to access items of lists which are inside other lists. The item selected from the
outer loop can be used as the list for the inner loop to iterate over.
Python Notes for A-Level Computer Science 9618
groups = [["Jobs", "Gates"], ["Newton", "Euclid"], ["Einstein",
"Feynman"]]

# 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)

You might also like