■ Python Programming
Complete Study Notes for Computer Science
Data Structures · Keywords · Syntax Rules · Coding Examples
Includes: Error Handling · Functions · OOP Intro · Debugging Tips
Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5
Data Types Python Syntax Operators Functions
& Structures Keywords Rules & Logic & Scope
Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10
Input / Error OOP Algorithms Practice
Output Handling Intro & Sorting Examples
■ Table of Contents
1. Data Types & Data Structures
• 1.1 Primitive Data Types
• 1.2 Strings
• 1.3 Lists
• 1.4 Tuples
• 1.5 Dictionaries
• 1.6 Sets
• 1.7 Type Conversion
2. Python Keywords
• 2.1 Full keyword table with definitions
3. Fundamental Syntax Rules
• 3.1 Indentation
• 3.2 Comments
• 3.3 Variables & Naming
• 3.4 Statements & Line Continuation
• 3.5 Code Structure Overview
4. Operators & Logic
• 4.1 Arithmetic
• 4.2 Comparison
• 4.3 Logical
• 4.4 Assignment
• 4.5 Bitwise & Membership
5. Functions & Scope
• 5.1 Defining Functions
• 5.2 Parameters & Arguments
• 5.3 Return Values
• 5.4 Scope (Local vs Global)
6. Input & Output
• 6.1 input()
• 6.2 print() & Formatting
• 6.3 f-strings
7. Control Flow
• 7.1 if / elif / else
• 7.2 for loops
• 7.3 while loops
• 7.4 break, continue, pass
8. Error Handling
• 8.1 try / except
• 8.2 Common Errors & Fixes
9. OOP Introduction
• 9.1 Classes & Objects
• 9.2 __init__ method
• 9.3 Attributes & Methods
10. Practice Examples
• 10 fully worked coding problems
Chapter 1 — Data Types & Data Structures
Understanding how Python stores and organises information
1.1 What Is a Data Type?
A data type tells Python what kind of value a variable holds and what operations can be performed on it.
Every value in Python has a type. You can check a value's type using the built-in type() function.
Primitive (Basic) Data Types
<b>Type</b> <b>Keyword</b> <b>Example</b> <b>Description</b>
Integer int 42, -7, 0 Whole numbers (no decimal)
Float float 3.14, -0.5, 2.0 Numbers with decimal points
String str "Hello", 'World' Text / sequence of characters
Boolean bool True, False Logical values (True or False)
NoneType None None Represents absence of a value
Complex complex 2+3j Numbers with real & imaginary parts
# Examples of primitive types
age = 17 # int
gpa = 3.85 # float
name = 'Lordia' # str
passed = True # bool
nothing = None # NoneType
print(type(age)) # <class 'int'>
print(type(gpa)) # <class 'float'>
1.2 Strings (str)
A string is an ordered, immutable sequence of characters enclosed in single or double quotes. Strings
support many built-in methods.
<b>Method</b> <b>What It Does</b> <b>Example</b>
.upper() Convert to uppercase "hello".upper() → "HELLO"
.lower() Convert to lowercase "HELLO".lower() → "hello"
.strip() Remove whitespace at ends " hi ".strip() → "hi"
.split(x) Split into list by delimiter "a,b".split(",") → ["a","b"]
.replace(a,b) Replace a with b "cat".replace("c","b") → "bat"
.find(x) Index of first occurrence "hello".find("l") → 2
len(s) Length of string len("hello") → 5
s[i] Access character at index i "hello"[0] → "h"
s[a:b] Slice from index a to b-1 "hello"[1:4] → "ell"
■ Remember: Strings are immutable — you cannot change individual characters. You must create a new
string.
1.3 Lists [ ]
A list is an ordered, mutable collection that can hold items of any data type, including mixed types. Lists
are one of the most commonly used data structures.
fruits = ['apple', 'banana', 'cherry']
nums = [10, 20, 30, 40, 50]
mixed = [1, 'hello', True, 3.14]
# Accessing elements (index starts at 0)
print(fruits[0]) # apple
print(fruits[-1]) # cherry (negative index = from end)
# Modifying a list
[Link]('mango') # add to end
[Link](1, 'grape') # insert at position 1
[Link]('banana') # remove by value
[Link]() # remove last item
[Link]() # sort alphabetically
print(len(fruits)) # number of items
<b>Method</b> <b>Description</b>
.append(x) Add x to the end
.insert(i, x) Insert x at index i
.remove(x) Remove first occurrence of x
.pop(i) Remove & return item at index i (default: last)
.sort() Sort list in place (ascending)
.reverse() Reverse list in place
.index(x) Return index of first x
.count(x) Count occurrences of x
.clear() Remove all items
len(list) Return number of items
1.4 Tuples ( )
A tuple is like a list but is immutable — once created, it cannot be changed. Use tuples for data that
should not be modified (e.g. coordinates, RGB colours).
point = (3, 7) # 2D coordinate
rgb_red = (255, 0, 0) # RGB colour
single = (42,) # Single-item tuple — note the comma!
print(point[0]) # 3
print(len(rgb_red)) # 3
# Tuple unpacking
x, y = point
print(x, y) # 3 7
■ Tip: Use a tuple instead of a list when your data should never change. It is also slightly faster.
1.5 Dictionaries { key: value }
A dictionary stores data as key-value pairs. Keys must be unique and immutable. Values can be any data
type. Dictionaries are unordered (Python 3.7+ maintains insertion order).
student = {
'name' : 'Lordia',
'age' : 17,
'grade' : 'A',
'passed': True
}
# Accessing values
print(student['name']) # Lordia
print([Link]('age')) # 17 (safe — won't crash if key missing)
# Adding / updating
student['school'] = 'GIS' # add new key
student['age'] = 18 # update existing key
# Removing
del student['grade']
[Link]('passed')
# Looping through a dictionary
for key, value in [Link]():
print(key, ':', value)
print([Link]()) # all keys
print([Link]()) # all values
1.6 Sets { }
A set is an unordered collection of unique items. Duplicate values are automatically removed. Useful for
membership testing and removing duplicates.
colours = {'red', 'blue', 'green', 'red'} # duplicate 'red' removed
print(colours) # {'red', 'blue', 'green'}
[Link]('yellow') # add item
[Link]('blue') # remove item (no error if missing)
# Set operations
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print(A | B) # Union: {1,2,3,4,5,6}
print(A & B) # Intersection: {3,4}
print(A - B) # Difference: {1,2}
1.7 Type Conversion (Casting)
You can convert between data types using built-in functions. This is called type casting.
x = '25' # string
y = int(x) # convert to integer → 25
z = float(x) # convert to float → 25.0
a = 3.99
b = int(a) # int truncates (does NOT round) → 3
c = 100
d = str(c) # convert to string → '100'
e = bool(0) # 0 → False; any non-zero → True
# Common use case: reading numbers from input()
num = int(input('Enter a number: '))
Data Structure Quick-Reference Summary
<b>Structure</b> <b>Syntax</b> <b>Ordered</b> <b>Mutable</b><b>Duplicates</b> <b>Key:Value</b>
List [] Yes Yes Yes No
Tuple () Yes No Yes No
Dictionary { k:v } Yes* Yes No* Yes
Set {} No Yes No No
String "" Yes No Yes No
Chapter 2 — Python Keywords
Reserved words with special meanings — cannot be used as variable names
Python has 35 reserved keywords. They are part of the language's syntax and cannot be used as
variable or function names.
<b>Keyword</b> <b>Definition & Purpose</b>
False Boolean value representing logical false
True Boolean value representing logical true
None Represents the absence of a value (null)
and Logical AND — True only if both conditions are True
or Logical OR — True if at least one condition is True
not Logical NOT — reverses a boolean value
if Begins a conditional statement
elif Else-if — additional condition in an if chain
else Runs when all if/elif conditions are False
for Starts a for loop (iterate over a sequence)
while Starts a while loop (runs while condition is True)
break Exits the current loop immediately
continue Skips to the next iteration of the loop
pass Does nothing — placeholder for empty blocks
def Defines a function
return Exits a function and returns a value
lambda Creates a small anonymous (one-line) function
class Defines a class (blueprint for objects)
import Imports a module into your program
from Used with import to bring specific items from a module
as Creates an alias for an import or exception
in Tests membership in a sequence; also used in for loops
is Tests object identity (same object in memory)
not in Tests that a value is NOT in a sequence
is not Tests that two variables are NOT the same object
try Starts a block to test for errors
except Handles errors caught by try
finally Runs code after try/except regardless of result
raise Manually raises an exception/error
with Used for context managers (e.g. opening files)
global Declares a variable as global inside a function
nonlocal Declares a variable from an enclosing scope
del Deletes a variable or item from a list/dict
yield Pauses a generator function and returns a value
assert Tests a condition; raises AssertionError if False
Chapter 3 — Fundamental Syntax Rules
The grammar of Python — how to write valid code
3.1 Indentation — Python's Most Important Rule
Unlike most languages that use braces { }, Python uses indentation (spaces/tabs) to define code blocks.
All lines in the same block must have the same indentation level. The standard is 4 spaces per level.
# CORRECT — consistent 4-space indentation
if age >= 18:
print('Adult') # 4 spaces in
if age >= 65:
print('Senior') # 8 spaces in (nested block)
# WRONG — mixing spaces causes IndentationError
if age >= 18:
print('Adult') # 2 spaces
print('Also adult') # 4 spaces — ERROR!
■■ Warning: NEVER mix tabs and spaces. Configure your editor to use spaces only. This is the #1 beginner
mistake.
3.2 Comments
Comments explain your code. Python ignores them at runtime.
# This is a single-line comment
x = 5 # inline comment — explains the line
'''
This is a multi-line string
often used as a docstring or block comment.
'''
def greet(name):
"""Return a greeting message.""" # docstring
return f"Hello, {name}!"
3.3 Variables & Naming Rules
• Must start with a letter or underscore (_), NOT a number
• Can contain letters, numbers, and underscores
• Case-sensitive: name, Name, and NAME are three different variables
• Cannot be a Python keyword (e.g. if, for, while, class)
• Convention: use snake_case for variables and functions (e.g. student_name)
• Convention: use UPPER_CASE for constants (e.g. MAX_SIZE = 100)
• Convention: use PascalCase for class names (e.g. StudentRecord)
# Valid variable names
student_name = 'Lordia'
_private = 42
total2024 = 500
# Invalid variable names
2fast = 10 # starts with number — SyntaxError
my-var = 5 # hyphen not allowed — SyntaxError
class = 'A' # keyword — SyntaxError
3.4 Statements & Line Continuation
# Each statement is usually on its own line
x = 10
y = 20
z = x + y
# Multiple statements on one line (not recommended)
a = 1; b = 2; c = 3
# Line continuation with backslash
total = 100 + 200 + \
300 + 400
# Implicit continuation inside brackets
result = (100 + 200 +
300 + 400) # no backslash needed
3.5 Python Program Structure Overview
# 1. Imports (always at the top)
import math
from random import randint
# 2. Constants
PI = 3.14159
MAX_STUDENTS = 40
# 3. Function definitions
def greet(name):
return f'Hello, {name}!'
# 4. Main program logic
student = input('Enter your name: ')
message = greet(student)
print(message)
Chapter 4 — Operators & Logic
Symbols that perform operations on values
4.1 Arithmetic Operators
<b>Op</b> <b>Name</b> <b>Example</b> <b>Result</b>
+ Addition 5+3 8
- Subtraction 5-3 2
* Multiplication 5*3 15
/ Division 5/2 2.5
// Floor Division 5 // 2 2
% Modulus 5%2 1
** Exponentiation 2 ** 4 16
4.2 Comparison Operators (return True/False)
<b>Op</b> <b>Meaning</b> <b>Example</b> <b>Result</b>
== Equal to 5 == 5 True
!= Not equal to 5 != 3 True
> Greater than 7>3 True
< Less than 2<5 True
>= Greater than or equal 5 >= 5 True
<= Less than or equal 3 <= 2 False
4.3 Logical Operators
<b>Op</b> <b>Meaning</b> <b>Example</b> <b>Result</b>
and Both must be True True and False False
or At least one must be True True or False True
not Reverses the boolean not True False
4.4 Assignment Operators
<b>Op</b> <b>Equivalent To</b> <b>Example</b> <b>Result (if x=10)</b>
= Assign x=5 x is 5
+= x=x+n x += 3 x is 13
-= x=x-n x -= 2 x is 8
*= x=x*n x *= 2 x is 20
/= x=x/n x /= 4 x is 2.5
//= x = x // n x //= 3 x is 3
%= x=x%n x %= 3 x is 1
**= x = x ** n x **= 2 x is 100
Chapter 5 — Functions & Scope
Reusable blocks of code that perform a specific task
5.1 Defining & Calling Functions
# Syntax
def function_name(parameters):
# body of function
return value # optional
# Example
def greet(name):
message = f'Hello, {name}!'
return message
result = greet('Lordia')
print(result) # Hello, Lordia!
5.2 Parameters & Default Values
def power(base, exponent=2): # exponent has a default value
return base ** exponent
print(power(3)) # 9 (uses default exponent=2)
print(power(3, 4)) # 81 (overrides default)
# Keyword arguments — order doesn't matter
print(power(exponent=3, base=2)) # 8
5.3 Scope — Local vs Global
x = 100 # GLOBAL variable
def show():
y = 50 # LOCAL variable — only exists inside show()
print(x) # can ACCESS global x
print(y) # can access local y
show()
print(x) # works
# print(y) # NameError — y doesn't exist outside function
# Modifying a global variable inside a function
count = 0
def increment():
global count # tell Python to use the global count
count += 1
increment()
print(count) # 1
Chapter 6 — Input & Output
Getting data from the user and displaying results
6.1 input() — Reading User Input
input() always returns a string. You must cast it if you need a number.
name = input('Enter your name: ') # returns string
age = int(input('Enter your age: ')) # cast to int
gpa = float(input('Enter your GPA: ')) # cast to float
print('Name:', name, '| Age:', age, '| GPA:', gpa)
6.2 print() & Formatting
# Basic print
print('Hello World')
print('Score:', 95)
# sep and end parameters
print('a', 'b', 'c', sep='-') # a-b-c
print('Loading', end='...') # Loading... (no newline)
# 6.3 f-strings (most modern way — Python 3.6+)
name = 'Lordia'
score = 98.5
print(f'Student: {name}, Score: {score}') # Student: Lordia, Score: 98.5
print(f'Score rounded: {score:.1f}') # Score rounded: 98.5
print(f'Score as %: {score/100:.1%}') # Score as %: 98.5%
# .format() method (older style)
print('Hello, {}!'.format(name)) # Hello, Lordia!
print('Score: {:.2f}'.format(score)) # Score: 98.50
Chapter 7 — Control Flow
Controlling which parts of your code run and how many times
7.1 if / elif / else
score = int(input('Enter your score: '))
if score >= 80:
grade = 'A'
elif score >= 70:
grade = 'B'
elif score >= 60:
grade = 'C'
elif score >= 50:
grade = 'D'
else:
grade = 'F'
print(f'Your grade is: {grade}')
7.2 for Loops
# Loop through a list
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
# Loop with range()
for i in range(5): # 0,1,2,3,4
print(i)
for i in range(1, 11): # 1 to 10
print(i)
for i in range(0, 20, 2): # 0,2,4,...,18 (step=2)
print(i)
# Loop with index using enumerate()
for index, value in enumerate(fruits):
print(index, ':', value)
7.3 while Loops & 7.4 break / continue / pass
# while loop
count = 0
while count < 5:
print(count)
count += 1 # IMPORTANT: update counter or infinite loop!
# break — exit loop early
for n in range(10):
if n == 5:
break # stop when n reaches 5
print(n) # prints 0,1,2,3,4
# continue — skip current iteration
for n in range(6):
if n == 3:
continue # skip 3
print(n) # prints 0,1,2,4,5
# pass — do nothing (placeholder)
def my_function():
pass # to be implemented later
Chapter 8 — Error Handling
Writing programs that handle mistakes gracefully
8.1 try / except / finally
try:
num = int(input('Enter a number: '))
result = 100 / num
print('Result:', result)
except ValueError:
print('Error: Please enter a valid integer!')
except ZeroDivisionError:
print('Error: Cannot divide by zero!')
except Exception as e:
print(f'Unexpected error: {e}')
finally:
print('Program finished.') # always runs
8.2 Common Python Errors
<b>Error Type</b> <b>Cause</b> <b>Example</b>
SyntaxError Invalid Python code — grammar mistake if x = 5: (should be ==)
IndentationError Wrong indentation Missing spaces inside if block
NameError Using a variable before defining it print(x) when x not assigned
TypeError Wrong data type for operation '5' + 5 (str + int)
ValueError Right type, wrong value int('hello')
ZeroDivisionError Dividing by zero 10 / 0
IndexError List index out of range lst[10] when lst has 3 items
KeyError Dictionary key does not exist d['xyz'] when key missing
AttributeError Object doesn't have that attribute/method [Link]()
ImportError Module not found or doesn't have named item import maths (typo)
Chapter 9 — Introduction to OOP
Classes and Objects — the building blocks of object-oriented programming
Object-Oriented Programming (OOP) organises code into classes (blueprints) and objects (instances
of those blueprints). This mirrors the real world — a 'Student' class can create many individual student
objects.
# Define a class
class Student:
# __init__ is the constructor — runs when an object is created
def __init__(self, name, age, grade):
[Link] = name # instance attribute
[Link] = age
[Link] = grade
# Method — a function that belongs to the class
def introduce(self):
return f'I am {[Link]}, age {[Link]}, grade {[Link]}.'
def is_passing(self):
return [Link] >= 50
# Create objects (instances)
s1 = Student('Lordia', 17, 92)
s2 = Student('Kofi', 16, 45)
print([Link]()) # I am Lordia, age 17, grade 92.
print(s2.is_passing()) # False
print([Link]) # Lordia
# Modifying attributes
[Link] = 55
print(s2.is_passing()) # True
■ Key Terms: class = blueprint | object = instance | self = reference to current object | __init__ = constructor
Chapter 10 — Practice Examples
10 fully worked coding problems with explanations
Example 1 — Even or Odd Checker
Task: Write a program that asks the user for a number and says if it is even or odd.
num = int(input('Enter a number: '))
if num % 2 == 0:
print(f'{num} is Even')
else:
print(f'{num} is Odd')
■ Concepts used: Uses: int(), input(), if/else, % modulus operator, f-string
Example 2 — Sum of a List
Task: Write a function that calculates the sum of all numbers in a list.
def list_sum(numbers):
total = 0
for num in numbers:
total += num
return total
my_list = [10, 25, 8, 42, 15]
print('Sum:', list_sum(my_list)) # Sum: 100
# Alternatively using built-in:
print(sum(my_list)) # 100
■ Concepts used: Uses: def, for loop, += operator, return, list
Example 3 — Times Table
Task: Print the times table for a number entered by the user.
num = int(input('Times table for: '))
for i in range(1, 13):
print(f'{num} x {i} = {num * i}')
■ Concepts used: Uses: int(), input(), for loop, range(), f-string, arithmetic
Example 4 — Grade Calculator
Task: Ask for 5 test scores and calculate the average, then assign a letter grade.
scores = []
for i in range(1, 6):
score = float(input(f'Enter score {i}: '))
[Link](score)
average = sum(scores) / len(scores)
print(f'Average: {average:.1f}')
if average >= 80: grade = 'A'
elif average >= 70: grade = 'B'
elif average >= 60: grade = 'C'
elif average >= 50: grade = 'D'
else: grade = 'F'
print(f'Grade: {grade}')
■ Concepts used: Uses: list, for loop, append(), sum(), len(), if/elif/else, f-string
Example 5 — Password Validator
Task: Check whether a password meets minimum requirements (8+ chars, has a digit).
def validate_password(pw):
if len(pw) < 8:
return 'Too short — needs at least 8 characters'
has_digit = False
for ch in pw:
if [Link]():
has_digit = True
break
if not has_digit:
return 'Must contain at least one digit'
return 'Password is valid!'
pw = input('Enter password: ')
print(validate_password(pw))
■ Concepts used: Uses: def, len(), for loop, str methods (.isdigit()), break, if/else, return
Example 6 — Find Maximum Without max()
Task: Find the largest number in a list without using the built-in max().
numbers = [34, 78, 12, 99, 45, 67]
largest = numbers[0] # assume first is largest
for n in numbers:
if n > largest:
largest = n
print('Largest number:', largest) # 99
■ Concepts used: Uses: list indexing, for loop, if comparison, variable reassignment
Example 7 — Word Frequency Counter
Task: Count how many times each word appears in a sentence.
sentence = input('Enter a sentence: ').lower()
words = [Link]() # split into list of words
frequency = {} # empty dictionary
for word in words:
if word in frequency:
frequency[word] += 1
else:
frequency[word] = 1
for word, count in [Link]():
print(f'{word}: {count}')
■ Concepts used: Uses: str methods, split(), dictionary, for loop, if/else, .items()
Example 8 — Simple Calculator with Error Handling
Task: Build a basic calculator that handles division by zero and invalid input.
def calculate(a, b, op):
if op == '+': return a + b
elif op == '-': return a - b
elif op == '*': return a * b
elif op == '/':
if b == 0:
return 'Error: division by zero'
return a / b
else:
return 'Unknown operator'
try:
a = float(input('First number: '))
op = input('Operator (+, -, *, /): ')
b = float(input('Second number: '))
print('Result:', calculate(a, b, op))
except ValueError:
print('Please enter valid numbers!')
■ Concepts used: Uses: def, if/elif/else, try/except, ValueError, float(), input()
Example 9 — Fibonacci Sequence
Task: Generate the first n terms of the Fibonacci sequence.
def fibonacci(n):
sequence = []
a, b = 0, 1
for _ in range(n):
[Link](a)
a, b = b, a + b # swap values simultaneously
return sequence
n = int(input('How many terms? '))
print(fibonacci(n))
# Sample output for n=8:
# [0, 1, 1, 2, 3, 5, 8, 13]
■ Concepts used: Uses: def, list, for loop, tuple unpacking, append(), return
Example 10 — Student Report Using a Class
Task: Use a class to store student data and generate a report.
class Student:
def __init__(self, name, scores):
[Link] = name
[Link] = scores
def average(self):
return sum([Link]) / len([Link])
def grade(self):
avg = [Link]()
if avg >= 80: return 'A'
elif avg >= 70: return 'B'
elif avg >= 60: return 'C'
elif avg >= 50: return 'D'
else: return 'F'
def report(self):
return (f'Student : {[Link]}\n'
f'Scores : {[Link]}\n'
f'Average : {[Link]():.1f}\n'
f'Grade : {[Link]()}')
s = Student('Lordia', [88, 92, 79, 95, 84])
print([Link]())
■ Concepts used: Uses: class, __init__, self, methods, sum(), len(), if/elif/else, f-string
Quick Debugging Checklist
What to check when your code doesn't work
<b>#</b> <b>Check This</b> <b>How to Fix It</b>
1 Read the error message Python tells you the error type and line number. Start there.
2 Check indentation Are all lines in the same block indented the same way?
3 Check variable names Typos? Is the variable defined before you use it?
4 Check data types Are you trying to add a string to a number? Use int() or str().
5 Add print() statements Print variables at key points to see their values.
6 Check loop conditions Will your while loop ever stop? Is the counter updated?
7 Check list indices Does your index exist? Remember: first index is 0, not 1.
8 Check dictionary keys Use .get() to avoid KeyError, or check with 'key in dict'.
9 Test with simple input Use small, known values to trace through your logic manually.
10 Comment out sections Isolate the problem by disabling parts of your code with #.
■ Final Advice: The best way to learn Python is to TYPE the code yourself — not copy-paste. Make mistakes.
Read the errors. Fix them. Repeat. Every professional programmer Googles things. Practice daily, even 15
minutes, and you will improve rapidly.