๐Ÿ PythonManual
๐Ÿ”

๐Ÿ“ข The print() Function

The print() function is used to output text, numbers, or variables to the screen.

print("hello", "\nworld")

Spacing: You can use a comma , to combine variables, strings, and numbers in the same print statement. Python automatically adds a space between items separated by a comma.

Concatenation: You can also use the + operator to combine items, but be careful: you can only concatenate strings with other strings, or add numbers to other numbers. Mixing them will cause a type error! The benefit of + is that it doesn't add any spaces automatically.

๐Ÿ“ฆ Variable Assignment

Variables are like boxes that store values. You assign a value to a variable using a single equals sign =.

# Assigning a number
a = 5

# Assigning text (strings)
a = "hello"

โž— Python Operators

Python uses standard symbols to do calculations. Below is your quick reference guide. Click on any example value to evaluate it live in the simulator!

Symbol
What it does
Example
Result
+
Addition
print(8 + 2)
10
-
Subtraction
print(8 - 2)
6
*
Multiplication
print(8 * 2)
16
/
Division
print(10 / 4)
2.5
%
Modulus (Remainder)
print(10 % 3)
1
//
Floor Divide (Whole number)
print(10 // 4)
2
**
Exponent (Power of)
print(10 ** 4)
10000
* (on text)
String Multiplication
print("7" * 2)
77

๐Ÿ’ป Calculations in Python

This program demonstrates how you can combine different operators to perform calculations.

# Assigning values to variables
width = 10
height = 3

# Basic arithmetic
perimeter = (width + height) * 2
area = width * height

# Division, floor division, and modulus
items = 10
people = 3
share = items / people       # 3.333... (float division)
even_share = items // people # 3 (integer division)
leftover = items % people    # 1 (remainder)

print("Area:", area)
print("Share:", share)
print("Remainder:", leftover)

๐Ÿ“ฅ Read User Inputs

The input() function allows programs to pause and ask the user for information.

# 1. Text Inputs (Default)
name = input("Hi! What's your name? ")

By default, everything entered is treated as Text (a string). You cannot perform mathematical operations on text, even if the user types in numbers like 123.

# 2. Number Inputs
MyAge = int(input("When were you born? "))

By wrapping input() inside int(), the text input is converted into an **Integer (a whole number)**, allowing you to calculate values with it.

โฐ Time Delays (time.sleep)

You can create pauses or delays in your code using the time module. Please note in run mode the entire program runs at once and so you will only see the completed code. Display mode will not wait for the sleep function.

import time

print("Wait for it...")
time.sleep(2)  # Pause for 2 seconds
print("Worth waiting for!")

๐Ÿ”€ Selection: If & Else

Selection allows programs to make decisions and execute different blocks of code depending on conditions.

test = input("Is it raining? y/n ")
if test == "y":
    print("Oh dear, no football today!")
else: 
    print("Great, let's go and play football!")

๐Ÿ”€ Elif (Else If)

Use elif when you need to check multiple conditions sequentially. Once a condition is met, the subsequent checks are skipped.

age = 18

if age < 17:
  print("You are not old enough to drive or vote.")
elif age == 17:
  print("You are old enough to drive!")
else:
  print("You are old enough to drive and vote!")

๐Ÿง  Quick Quiz: Selection

Given this code block, what will it print if the user inputs 18?

age = int(input("Age: "))
if age >= 17:
    print("Drive!")
elif age >= 18:
    print("Vote!")
else:
    print("Wait!")

๐Ÿ” Iteration: While Loops

Loops allow computers to repeat instructions quickly. A while loop repeats as long as a condition is true.

love_status = "y"
while love_status == "y":
    love_status = input('Do you love iteration? y/n ')

๐Ÿ›‘ The Break Statement

You can end a loop instantly using the break statement, even if the loop condition is still true.

while True:
  user_input = input("Enter Q to quit: ")
  if user_input == "Q":
    break

๐Ÿ” For Loops & range()

A for loop repeats a set number of times. You can use range() to customize the loop sequence.

# 1. Repeat 20 times (0 to 19)
for i in range(20):
    print(i)

# 2. Start, Stop, and Steps
# Goes from 1 to 99 in steps of 2 (stops before 100)
for i in range(1, 100, 2):
    print(i)

๐Ÿ“ String Length: len()

The len() function returns the number of characters in a string.

greeting = "Good Day!"
print(len(greeting)) # Outputs: 9

๐Ÿ” Logical Operator: or

Use the or operator to check if at least one of multiple statements is true.

number = 0
while number < 15 or number > 20:
    print("Please enter a number between 15 and 20")
    number = int(input("enter a number: "))

๐Ÿ—‚๏ธ Working with Lists

Lists store collections of items under a single variable name using square brackets [ ].

# Empty List
emptylist = []

# List with items
MyList = ["Kuala Lumpur", "London", "Paris", "New York", "Bangkok"]

Indexing: Lists start counting from index 0.
โ€ข Print index 0: print(MyList[0]) -> Prints Kuala Lumpur.
โ€ข Print a range: print(MyList[0:3]) -> Prints indexes 0, 1, 2.
โ€ข Format range print: print(*MyList[0:3], sep=", ") -> Removes brackets and separates with commas.
โ€ข Right-to-left: print(MyList[-1]) -> Prints the last item Bangkok.

๐Ÿ› ๏ธ Interactive List Playground

Play with the list visualization below! Modify items or slice ranges to see the changes visually.

๐Ÿข Basic Turtle Graphics

Turtle allows you to draw shapes and lines in Python. Below are the basic movements and configuration options.

Turtle Command
What it does
turtle.forward(50)
Go forward 50 steps
turtle.backward(50)
Go backward 50 steps
turtle.right(90)
Turn right 90 degrees
turtle.left(90)
Turn left 90 degrees
turtle.penup()
Lifts the pen up (moving without drawing)
turtle.pendown()
Drops the pen back down (draws when moving)
turtle.pencolor("Red")
Changes the drawing pen line color
turtle.fillcolor("Brown")
Changes the shape fill color
turtle.begin_fill()
Starts tracking lines to fill shape
turtle.end_fill()
Fills shape drawn since begin_fill()
turtle.speed(0)
Fastest speed. Normal speeds are 1 (slow) to 9 (fast).

๐ŸŽจ Drawing Shapes with Turtle

This program demonstrates how to import the turtle module and use loops to draw a filled square.

import turtle

# Configure drawing colors and speed
turtle.pencolor("Red")
turtle.fillcolor("Gold")
turtle.speed(3)

# Start tracking lines to fill
turtle.begin_fill()

# Draw four sides of the square
for i in range(4):
    turtle.forward(100)
    turtle.right(90)

# Fill the drawn shape
turtle.end_fill()

โ–ฆ 2D Lists: Rows and Columns

A 2D list is a list containing other lists. Use grid[row][column] to access one cell. Rows and columns both start at index 0.

seats = [
    ["A", "A", "B"],
    ["A", "B", "A"],
    ["A", "A", "A"]
]

print(seats[0][2])   # B
seats[1][1] = "A"    # update row 1, column 1

๐ŸŽฏ Pick a Cell, Build the Code

Choose a sample grid, then click a cell. The Python code updates to show the exact grid[row][column] access and a short example of using that value effectively.

Click a cell to see its row and column.

๐Ÿ” Traversing a Grid

Nested loops visit every cell. The outer loop usually controls the row; the inner loop controls each column in that row.

total = 0
sales = [
    [10, 12, 9],
    [7, 11, 15]
]

for row in sales:
    for value in row:
        total = total + value

print(total)

๐Ÿ’พ Reading and Writing Files

File handling lets programs save data after the program stops. Use "r" to read, "w" to overwrite, and "a" to append to the end.

file = open("score.txt", "w")
file.write("120")
file.close()

file = open("score.txt", "r")
score = int(file.readline())
file.close()

print(score)

๐Ÿ“„ Looping Through Lines

Many A-level file tasks load text, split records, count words, or filter rows. strip() removes the newline at the end of each line.

file = open("players.tsv", "r")

for line in file:
    fields = line.strip().split("\t")
    name = fields[0]
    rating = int(fields[1])
    if rating >= 80:
        print(name)

file.close()

๐Ÿ“– Dictionaries: Key-Value Pairs

A dictionary stores values under named keys. It is useful when a list index is not meaningful enough.

capitals = {
    "Malaysia": "Kuala Lumpur",
    "Malta": "Valletta",
    "England": "London"
}

print(capitals["Malaysia"])
print(capitals.get("Japan", "Unknown"))

Safe access: .get() avoids a KeyError if the key is missing.

๐Ÿ” Dictionary Loops and Frequencies

Dictionaries are excellent for counting frequencies because each word can become a key and its count can become the value.

counts = {}
words = ["to", "be", "or", "not", "to", "be"]

for word in words:
    counts[word] = counts.get(word, 0) + 1

for word, count in counts.items():
    print(word, count)

๐Ÿงฉ Procedures, Functions and Parameters

A procedure performs a named block of steps. A function returns a value. Parameters are variable names in the definition; arguments are the values passed in the call.

def print_receipt(name, price):
    print(name, "costs", price)

def add_tax(price):
    return price * 1.06

total = add_tax(100)
print_receipt("Keyboard", total)

๐ŸŽฏ Scope, Return and Decomposition

Local variables exist inside a function. Global variables exist outside. Good programs decompose a large problem into smaller subroutines with clear jobs.

def is_valid_mark(mark):
    if mark < 0 or mark > 100:
        return False
    return True

mark = int(input("Mark: "))
if is_valid_mark(mark):
    print("Accepted")
else:
    print("Rejected")

โœ… Validation vs Verification

Validation checks whether data is sensible before processing. Verification checks whether data has been copied or entered accurately.

Check
Purpose
presence
Rejects an empty value.
range
Checks a number is between limits.
length
Checks text has the required number of characters.
type
Checks the value can be treated as a particular data type.
format
Checks the pattern, such as letters followed by digits.

๐Ÿงช Try Common Checks

These are the same kinds of checks used in the validation and verification course: range, length, type, presence, format, visual check and double entry.

Try 85, 101 or -4 for the range check.

๐Ÿ”’ Input Validation Loop

A validation loop keeps asking until the data passes the required check.

mark_text = input("Enter mark 0-100: ")

while not mark_text.isdigit() or int(mark_text) < 0 or int(mark_text) > 100:
    print("Invalid mark")
    mark_text = input("Enter mark 0-100: ")

mark = int(mark_text)
print("Accepted:", mark)

๐Ÿ“Š Searching Algorithms

Linear search checks items one by one. Binary search needs sorted data and repeatedly discards half of the search space.

items = [3, 8, 12, 20, 31]
target = 20
low = 0
high = len(items) - 1
found = False

while low <= high and not found:
    mid = (low + high) // 2
    if items[mid] == target:
        found = True
    elif target < items[mid]:
        high = mid - 1
    else:
        low = mid + 1

print(found)

๐Ÿ”ƒ Sorting and Big O

Sorting algorithms arrange data into order. Complexity describes how work grows as the input size n grows.

Term
Meaning
O(1)
Constant time: work does not grow with the input size.
O(log n)
Logarithmic time: the problem is repeatedly divided.
O(n)
Linear time: one pass through the data.
O(n^2)
Quadratic time: nested passes over the data.

๐Ÿ“ˆ Big O Growth Visualizer

Move n to see how the common complexity classes grow. The numbers are simplified operation counts so the shape is clear; this is about comparing growth, not timing real hardware.

๐Ÿ Python Examples to Try

These are static code examples in this manual, not an embedded editor. Use the Edit button on a snippet to open it in the Python editor and try it there.

O(1) Constant

One direct lookup.

scores = [82, 91, 77, 88]
first = scores[0]
print(first)

O(log n) Binary Search

The search space halves each step.

items = [3, 8, 12, 20, 31, 44, 50, 72]
target = 44
low = 0
high = len(items) - 1
found = False

while low <= high:
    mid = (low + high) // 2
    if items[mid] == target:
        found = True
        break
    elif target < items[mid]:
        high = mid - 1
    else:
        low = mid + 1

print(found)

O(n) Linear Search

One pass through the list.

items = [3, 8, 12, 20, 31, 44, 50, 72]
target = 44
found = False

for item in items:
    if item == target:
        found = True

print(found)

O(n log n) Merge Sort

Split into halves, then merge each level. (Not in A-level)

def merge(left, right):
    result = []
    while len(left) > 0 and len(right) > 0:
        if left[0] < right[0]:
            result.append(left.pop(0))
        else:
            result.append(right.pop(0))
    return result + left + right

def merge_sort(items):
    if len(items) <= 1:
        return items
    mid = len(items) // 2
    left = merge_sort(items[:mid])
    right = merge_sort(items[mid:])
    return merge(left, right)

print(merge_sort([7, 3, 9, 2, 6]))

O(nยฒ) Bubble Sort

Nested comparisons over the data. Note that Big O represents the worst-case scenario, so both Bubble Sort and Insertion Sort share this same O(nยฒ) time complexity.

values = [7, 3, 9, 2, 6]
n = len(values)

for pass_num in range(n):
    for i in range(n - 1):
        if values[i] > values[i + 1]:
            values[i], values[i + 1] = values[i + 1], values[i]

print(values)

O(2โฟ) Naive Fibonacci

Each call branches into two more calls.

def fib(n):
    if n <= 1:
        return n
    return fib(n - 1) + fib(n - 2)

print(fib(8))

O(n!) Permutations

Try every possible ordering.

from itertools import permutations

items = ["A", "B", "C"]

for ordering in permutations(items):
    print(ordering)

๐Ÿซง Interactive Bubble Sort

Bubble sort repeatedly compares neighbouring items and swaps them when they are in the wrong order. Step through the comparisons one at a time.

๐Ÿ’ป Bubble Sort Implementation

Here is a complete Python implementation of the bubble sort algorithm to sort a list of numbers.

def bubble_sort(arr):
    n = len(arr)
    for i in range(n):
        # Last i elements are already in place
        for j in range(0, n - i - 1):
            # Swap if the element found is greater than the next element
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]

numbers = [7, 3, 9, 2, 6]
bubble_sort(numbers)
print("Sorted list:", numbers)

๐Ÿ“ฅ Interactive Insertion Sort

Insertion sort builds a sorted section on the left. Each new key moves left until it reaches its correct position.

๐Ÿ’ป Insertion Sort Implementation

Here is a complete Python implementation of the insertion sort algorithm to sort a list of numbers.

def insertion_sort(arr):
    # Traverse from 1 to len(arr)
    for i in range(1, len(arr)):
        key = arr[i]
        j = i - 1
        # Move elements of arr[0..i-1], that are greater than key,
        # to one position ahead of their current position
        while j >= 0 and arr[j] > key:
            arr[j + 1] = arr[j]
            j -= 1
        arr[j + 1] = key

numbers = [7, 3, 9, 2, 6]
insertion_sort(numbers)
print("Sorted list:", numbers)

๐Ÿ“š Stacks

A stack is a Last In, First Out structure. The newest item is always the next item removed.

Operation
Meaning
push
Add an item to the top.
pop
Remove and return the top item.
peek
Look at the top item without removing it.

๐ŸŽ›๏ธ Stack Visual

Watch how every operation happens at the top of the stack.

๐Ÿ’ป Stack Implementation (using Lists)

In Python, you can easily implement a stack structure using a list, with append() to push and pop() to pop.

# Initialize an empty stack
stack = []

# Push items onto the stack
stack.append("A")
stack.append("B")
stack.append("C")
print("Stack after pushes:", stack)

# Pop an item from the stack
removed = stack.pop()
print("Popped item:", removed)
print("Stack after pop:", stack)

# Peek at the top item
top_item = stack[-1]
print("Top item (peek):", top_item)

๐Ÿšถ Queues

A queue is a First In, First Out structure. New items join at the rear, and old items leave from the front.

Operation
Meaning
enqueue
Add an item to the rear of the queue.
dequeue
Remove and return the item at the front.
front/rear
Pointers or indexes used to track the next item out and newest item in.

๐ŸŽ›๏ธ Queue Visual

See the difference between the front and rear of the queue.

๐Ÿ’ป Queue Implementation (using Lists)

In Python, you can implement a queue structure using a list, with append() to enqueue and pop(0) to dequeue.

# Initialize an empty queue
queue = []

# Enqueue items at the rear
queue.append("A")
queue.append("B")
queue.append("C")
print("Queue after enqueues:", queue)

# Dequeue an item from the front
removed = queue.pop(0)
print("Dequeued item:", removed)
print("Queue after dequeue:", queue)

# Peek at the front item
front_item = queue[0]
print("Front item:", front_item)

๐Ÿ”— Linked Lists

A linked list is made from nodes. Each node stores data and a pointer to the next node. A null pointer marks the end.

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

start = Node("A")
start.next = Node("B")

current = start
while current is not None:
    print(current.data)
    current = current.next

Vocabulary: node, pointer, start pointer, null pointer, free list, traversal.

๐ŸŽ›๏ธ Linked List Visual

Nodes do not need to sit next to each other in memory. Each node points to the next node.

๐ŸŒ€ Recursion

Recursion is when a function solves a problem by calling itself. Every recursive algorithm needs a base case to stop and a general case that moves closer to the base case.

def factorial(n):
    if n == 0:
        return 1          # base case
    return n * factorial(n - 1)  # general case

print(factorial(5))

๐Ÿ“š Call Stack and Unwinding

Each recursive call creates a stack frame storing parameters, local variables and a return address. When the base case is reached, the calls return in reverse order. This is called unwinding.

๐Ÿ›๏ธ Classes, Objects and Constructors

A class is a blueprint. An object is an instance created from that class. The constructor __init__ sets up the object's attributes.

class Character:
    def __init__(self, name, health):
        self.name = name
        self.health = health

    def take_damage(self, amount):
        self.health = self.health - amount

hero = Character("Ada", 100)
hero.take_damage(25)
print(hero.health)

๐Ÿงฑ Encapsulation, Inheritance and Polymorphism

Encapsulation keeps data and methods together. Inheritance lets a subclass reuse a superclass. Polymorphism allows different classes to respond to the same method name in different ways.

class Enemy:
    def attack(self):
        print("Basic attack")

class Dragon(Enemy):
    def attack(self):
        print("Fire attack")

creature = Dragon()
creature.attack()

๐ŸŒณ Binary Search Trees

A binary tree node can have up to two children. In a binary search tree, smaller values go left and larger values go right.

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

root = Node("mango")
root.left = Node("apple")
root.right = Node("pear")

The local word data used in the tree course includes examples such as mango, apple, banana, pear, kiwi and orange.

๐Ÿ”Ž Traversal and Tree Search

In-order traversal visits left subtree, current node, then right subtree. In a binary search tree this outputs values in sorted order.

def inorder(node):
    if node is not None:
        inorder(node.left)
        print(node.data)
        inorder(node.right)

๐ŸŒณ Binary Tree Visualiser

Insert and search values to see the exact path through a binary search tree. Smaller values move left; larger or equal values move right.

๐Ÿ”— Further Learning & Reference

If you want to dive deeper into Python programming, these highly recommended tutorials and documentations are excellent places to expand your knowledge:

๐Ÿ“š W3Schools Python Tutorial

An exceptionally beginner-friendly, structured guide with simple explanations and lots of small interactive code examples.

๐Ÿ Official Python Documentation

The definitive source for Python standard libraries, syntax rules, and official explanations. Great for looking up specific modules or features.

๐Ÿ‘‘ Real Python Tutorials

A collection of high-quality, practical articles and step-by-step guides covering core concepts and real-world Python applications.

๐Ÿ” Python Search Engines

Looking for a specific function, library, or error solution? Use these specialized search portals to search directly within trusted python documentation:

Python Official Search

Search official guides, modules, and built-in function references.

W3Schools Python Search

Search user-friendly tutorials and code examples on W3Schools.

๐Ÿ” Search Results

Results matching your query will appear here.