DCIT23 · Computer Programming 2 · Finals

Python
Reviewer

The complete cram sheet — fundamentals, data types & operators, functions, classes & OOP, files & exceptions, and NumPy. Every concept, mnemonic, and code pattern from the six decks, in one place.

06 CHAPTERS30 SECTIONS10 MNEMONICSCHEAT SHEET
Compiled for Moitet
↓ scroll to begin

Ch 1–2 · Python Fundamentals

01

What is Python?

Introduction

Python is a high-level, interpreted, general-purpose and dynamic programming language that focuses on code readability.

Its syntax lets programmers write code in fewer steps than Java or C++.


Four words to remember Python by:

  • High-level — close to human language, far from machine code
  • Interpreted — run line by line, no separate compile step
  • General-purpose — usable for web, data, scripting, anything
  • Dynamic — variable types resolved at run-time, not declared
02

Python Character Set

Fundamentals
A character set is the bunch of identifying elements (the building blocks) of the language.

Letters

A–Z and a–z

Digits

0 to 9

Special Symbols

space + - / ( ) [ ] = != < > , ' " $ # ; : ? &

White Spaces

Blank space, horizontal tab, vertical tab, carriage return

Other Characters

Python can process all 256 ASCII and Unicode characters.

03

Tokens / Lexical Units

Fundamentals
A token (or lexical unit) is an individual element identified by the language. There are 5 types.
K I L O P
"Keep It Logical, Or Panic"
KKeywords — reserved words with special meaning
IIdentifiers — names you give to things
LLiterals — fixed constant values
OOperators — trigger a computation
PPunctuators — separators like brackets, commas
04

Keywords

Token type 1

Keywords (reserved words) have a special, predefined meaning in the Python interpreter. Because of that, they cannot be used as identifiers.

andassertbreakclasscontinuedefdelelifelseexceptexecfinallyforfromglobalifimportinislambdanotorpassprintraisereturntrywhilewithyield
05

Identifiers & Naming Conventions

Token type 2
An identifier is a name given to a function, class, variable, module, or object — basically any name that appears in the program (e.g. a, b, c).

The 8 naming rules

  • Can combine uppercase, lowercase, underscores, and digits (0–9) — e.g. myClass, var_1
  • The first character must be a letter (or underscore)
  • No special characters such as %, @, $ inside identifiers
  • Cannot begin with a number2variable ✗, variable2
  • Python is case-sensitiveLabourlabour
  • Cannot use Python keywords as identifiers
  • Use underscores to separate multiple words

✓ Valid

Myfile1 · DATE9_7_8 · y3m9d3 · _xs · MYFILE · _FXd

✗ Invalid

MY-REC · 28dre · break · elif · false · del

06

Literals & Strings

Token type 3
Literals (constants) are values that never change during program execution. There are 5 types.
S N B N C
"Smart Nerds Build Neat Code"
SString literals — text in quotes
NNumeric literals — int, float, complex
BBoolean literals — True / False
NNone — the special "no value" literal
CCollections — tuple, list, etc.

String literals

A sequence of letters in quotes. Python accepts both forms: 'Hello' = "Hello".

Single-line

Begins and ends on one line.

Item = "Computer"

Multi-line

Spread across lines using a backslash \ to continue.

Item = 'Key\
board'

Indexing works forward (0,1,2…) and backward (-1,-2…):

>>> s = "Hello Python"
>>> s[0]        # 'H'  (first)
>>> s[-1]       # 'n'  (last)
>>> s[len(s)-1]  # 'n'  (len() = length of string)

String sizing & triple quotes

  • '\\' → size 1 (the backslash is one escape sequence)
  • 'abc' → size 3  ·  "\ab" → size 2
  • In triple-quoted strings, the EOL (End-Of-Line / Enter) character at each line break is counted in the size.

Escape sequences

SeqMeaning
\\Back slash
\'Single quote
\"Double quote
\aASCII bell
\bASCII backspace
\fASCII formfeed
SeqMeaning
\nNew line
\rCarriage return
\tHorizontal tab
\vVertical tab
\x16-bit hex value
\oooOctal value (3 digits)
07

Numeric Literals

Literals · deep dive
I F C
"I Find Complexity"
Iint — whole numbers, +ve or −ve, unlimited length
Ffloat — real values with a fractional part
Ccomplex — complex numbers (e.g. 1j)

Integer bases & conversion

BasePrefixExample
Decimalnone255
Octal (8)0o0o377
Hex (16)0x / 0X0xFF
Binary (2)0b / 0B0b1010

Convert an int to its string representation with these built-ins:

oct(7)     # '0o7'
hex(2572)  # hexadecimal string
bin(12)    # binary string

Floating-point forms

  • Fractional form — e.g. 15.75
  • Exponent form — mantissa + exponent. 5.80.58E01 (mantissa 0.58, exponent E01)
08

Punctuators, Comments & Statements

Token types 4 & 5

Punctuators (separators)

[ ]  ( )  { }  ,  ;  :  *  …  =  #

Brackets, parentheses, braces, comma, semicolon, colon, asterisk, ellipsis, equal sign, pound sign.

Comments

Non-executable statements.

  • Single-line starts with #
  • Multi-line uses triple quotes — also called a docstring

Statements, functions & conventions

  • A statement = one instruction. A collection of statements = a program (a.k.a. code).
  • A function is a self-contained segment that does one well-defined task.
  • No statement terminator — Python uses no symbol (like ;) to end a line.
  • Max line length = 79 characters.
  • Put whitespace around operators, but not around parentheses.
  • A code block is a group of statements that are part of another statement/function.
  • Python is case-sensitive.
09

Variables & Assignment

Fundamentals
Variables are named labels for memory locations. In Python, variables do not have fixed locations (unlike C/Java) — the label just points to wherever the value lives.

Lvalue

The expression on the Left-Hand Side of =.

Rvalue

The expression on the Right-Hand Side of =.

Multiple assignment

# same value to many variables
a = b = c = d = e = 10

# many values to many variables
p, q, r = 5, 10, 15

# swap (no temp variable needed)
p, q = q, p          # now p=10, q=5

Expressions separated by commas evaluate left to right. With y, y = 12, 15 it assigns y=12 then y=15, so y ends as 15.

Dynamic typing & type()

A variable pointing to one type can be re-pointed to a value of a different type — that's dynamic typing.

x = 10
print(x)
x = "Hello World"   # perfectly legal

# caution: types must make sense for the operation
x = 'day'
y = x / 2          # Error! a string can't be divided

# type() reveals the current type
type(10)        # <class 'int'>
type(20.4)      # <class 'float'>
type("Hi")     # <class 'str'>
10

input() & print()

Built-in functions

input() — read from the user

A built-in function that reads a value typed by the user. Syntax: variable = input(message). It always returns a string, so wrap it in int() / float() / complex() to convert.

p = input("Enter the value")
age = int(input("Enter age"))      # to integer
sal = float(input("Enter salary"))  # to float

print() — display on screen

Prints any number of values separated by commas. Full signature:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
ParamRole
*objectsOne or more values to print (* = many)
sepSeparator between objects. Default: ' '
endPrinted at the very end. Default: '\n'
fileOutput target. Default: screen (sys.stdout)
flushForce-flush the stream. Default: False
print("Python is fun.")
a = 5
print("a =", a)        # a = 5
print("a = \n", a)     # newline before the value

Ch 2 · Data Types, Operators & Statements

11

Execution & Indentation

Statements

Two ways to run Python

# 1. directly in the command line
>>> print("Hello, World!")
Hello, World!

# 2. as a .py file
C:\Users\Name> python myfile.py

Indentation matters

Indentation = the spaces at the start of a line. In most languages it's cosmetic; in Python it's required — it defines a block of code.

if 5 > 2:
    print("Five is greater than two!")
12

Variables & Casting

Data Types

Python has no declaration command — a variable is born the moment you assign a value.

x = 5
y = "Hello, World!"

Casting — force a type

x = str(3)    # '3'
y = int(3)    # 3
z = float(3)  # 3.0

Multi-word naming styles

C P S
Camel · Pascal · Snake
CCamelmyVariableName
PPascalMyVariableName
SSnakemy_variable_name

Variable-name rules (recap)

  • Must start with a letter or underscore — never a number
  • Only alphanumerics and underscores (A–z, 0–9, _)
  • Case-sensitive: age, Age, AGE are three different variables
  • Cannot be a Python keyword
13

Data Types — 8 Categories

Built-in types
T N S M S B B N
"Ten New Students Make Some Big Brilliant Notes"
TTextstr
NNumericint, float, complex
SSequencelist, tuple, range
MMappingdict
SSetset, frozenset
BBooleanbool
BBinarybytes, bytearray, memoryview
NNoneNoneType

The three numeric types

int
Integer

Whole number, +ve/−ve, no decimals, unlimited length.

x = 1
float
Float

Number with one or more decimals, +ve/−ve.

y = 2.8
complex
Complex

Has an imaginary part written with j.

z = 1j
14

Strings & Methods

Text type

Strings use single or double quotes — 'hello' = "hello" — and print with print().

a = "Hello, World!"
print(a.upper())   # HELLO, WORLD!
print(a.lower())   # hello, world!

b = " Hello, World! "
print(b.strip())   # "Hello, World!"  (removes whitespace)

print(a.replace("H", "J"))   # Jello, World!
print(a.split(","))         # ['Hello', ' World!']

Concatenation — combine strings with + (add a space manually):

a = "Hello"; b = "World"
c = a + " " + b   # "Hello World"

Key string methods to know

MethodDoes
upper() / lower()Convert case
capitalize()First character to upper case
title()First char of each word to upper
swapcase()Lower↔upper for every char
strip() / lstrip() / rstrip()Trim whitespace (both/left/right)
replace(a, b)Swap a specified value for another
split(sep)Split into a list at the separator
join()Join an iterable onto the string
find() / index()Position of a value
count()How many times a value occurs
startswith() / endswith()True if string starts/ends with value
isalnum() / isalpha() / isdigit()True if all chars match the test
format()Insert specified values into a string
zfill(n)Pad the front with 0s

Python ships ~45 string methods total — the ones above are the high-yield set.

15

Booleans

Boolean type

Booleans represent one of two values: True or False. When you compare two values, Python evaluates the expression and returns a Boolean.

print(10 > 9)    # True
print(10 == 9)   # False
print(10 < 9)    # False
16

Operators — 7 Groups

Operators
Operators perform operations on variables and values. Python divides them into 7 groups.
A A C L I M B
"All Animals Can Leap Into Muddy Bogs"
AArithmetic — math
AAssignment — assign values
CComparison — compare two values
LLogical — combine conditions
IIdentity — same object?
MMembership — is it inside?
BBitwise — compare binary bits

Arithmetic

OpName
+Addition
-Subtraction
*Multiplication
/Division
%Modulus (remainder)
**Exponentiation
//Floor division

Comparison

OpName
==Equal
!=Not equal
>Greater than
<Less than
>=Greater or equal
<=Less or equal

Logical

OpTrue when…
andboth are true
orone is true
notreverses result

Identity

OpTrue when…
issame object
is notnot same object

Compares memory location, not just equality.

Membership

OpTrue when…
invalue is present
not invalue is absent

Assignment & Bitwise

Assignment — shorthand for "do then store":

=   +=   -=   *=   /=   %=   //=   **=   &=   |=   ^=   >>=   <<=   :=

e.g. x += 3 is the same as x = x + 3. The := "walrus" assigns inline.

Bitwise — operate on binary bits:

OpName
&AND
|OR
^XOR
~NOT (invert)
<<Zero-fill left shift
>>Signed right shift
17

Operator Precedence

Order of operations
Precedence = the order operations run in. Parentheses always win; multiplication beats addition.
print((6+3) - (6+3))  # 0  → () first
print(100 + 5 * 3)    # 115 → * before +

High → Low

LevelOperators
Highest( ) parentheses
** exponentiation
+x -x ~x unary
* / // %
+ -
<< >> shifts
& then ^ then |
comparison / identity / membership
notandor

Ch 3 · Functions

18

Function Basics

Functions
A function is a block of code that only runs when called. You can pass parameters in, and it can return data.

Define with def

def my_function():
    print("Hello from a function")

Call with name()

def my_function():
    print("Hello from a function")

my_function()   # runs it

Anatomy of a definition

def greet():
    print('Hello World!')
  • def → keyword used to create a function
  • greet → the function name
  • () → parameters (empty here)
  • indentation → required; marks the function body
19

Parameters vs Arguments

Functions
The two terms are used loosely, but precisely: a parameter lives in the definition; an argument is the value sent at call-time.

Parameter

The variable listed inside the parentheses in the function definition.

Hook: Parameter = the Plan.

Argument

The value that is sent to the function when it's called. Often shortened to args.

Hook: Argument = what Arrives.

def my_function(fname):       # fname = parameter
    print(fname + " Refsnes")

my_function("Emil")          # "Emil" = argument
my_function("Tobias")

Number of arguments: by default a call must pass exactly as many arguments as there are parameters — not more, not fewer, or you get an error.

20

Argument Types

Functions · the big one

*args — Arbitrary Arguments

Unknown number of arguments? Put one * before the parameter. The function receives a tuple.

def my_function(*kids):
    print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")

Keyword Arguments (kwargs)

Send values as key = value. Order then doesn't matter.

def my_function(child3, child2, child1):
    print("The youngest is " + child3)

my_function(child1="Emil", child2="Tobias", child3="Linus")

**kwargs — Arbitrary Keyword Arguments

Unknown number of keyword args? Put two ** before the parameter. The function receives a dictionary.

def my_function(**kid):
    print("His last name is " + kid["lname"])

my_function(fname="Tobias", lname="Refsnes")

Default Parameter Value

If no argument is passed, the default is used.

def my_function(country="Norway"):
    print("I am from " + country)

my_function()          # I am from Norway
my_function("Brazil")

Passing a List

Any data type can be passed; it stays that type inside.

def my_function(food):
    for x in food:
        print(x)

fruits = ["apple", "banana", "cherry"]
my_function(fruits)

Positional-only vs Keyword-only

add , /
Positional-only

Args before / must be positional.

def f(x, /):
    print(x)
f(3)
add *,
Keyword-only

Args after * must be keyword.

def f(*, x):
    print(x)
f(x=3)
combine
Both at once

Before / positional, after * keyword.

def f(a,b,/,*,c,d):
    print(a+b+c+d)
f(5,6,c=7,d=8)
21

Return Values & pass

Functions

return — hand a value back

def my_function(x):
    return 5 * x

print(my_function(3))   # 15
print(my_function(5))   # 25

pass — a legal empty body

A definition can't be empty. If you need a placeholder, use pass to avoid an error.

def myfunction():
    pass

Classes & Object-Oriented Programming

22

Procedural vs Function

Why functions

A function is a reusable block of code that performs a specific task — it helps organize code and avoid repetition.

Without a function (repeats)

print('Hello')
print('Hello')
print('Hello')

With a function (reusable)

def greet():
    print('Hello')

Procedural / direct-execution code

Runs immediately, top to bottom, once.

a = 33           # store 33
b = 200          # store 200
if b > a:         # check 200 > 33 → True
    print("b is greater than a")

✗ No reuse · ✗ no structure · ✗ no grouping of logic · runs once only.

Same logic as a function

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

compare(33, 200)
ProceduralFunction version
Runs immediatelyDoesn't run until called
Uses fixed valuesAccepts different values
Cannot easily reuseReuse many times
No name for the logicGroups logic under a name
23

Classes — __init__ & self

OOP
A class is a blueprint for creating objects. It defines attributes (variables) and methods (functions inside the class).

Basic structure

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age
  • __init__ → the constructor (runs automatically when an object is made)
  • self → refers to the current object

Adding & using a method

class Student:
    def __init__(self, name):
        self.name = name
    def greet(self):
        print('Hi, I am ' + self.name)

student1 = Student('Carlos')
student1.greet()        # Hi, I am Carlos
24

Objects

OOP
Class = blueprint. Object = the actual thing created from that blueprint. e.g. Class Car → Objects Toyota, Honda, Ford.

Creating objects

student1 = Student('Ana', 20)
print(student1.name)   # Ana
print(student1.age)    # 20
class Car:
    def __init__(self, brand, color):
        self.brand = brand
        self.color = color
    def start(self):
        print(self.brand + ' is starting...')

car1 = Car('Toyota', 'Red')
car2 = Car('Honda', 'Blue')
car1.start()   # Toyota is starting...
25

OOP Principles

OOP
C O M
The 3 building blocks of OOP
CClasses — the blueprints
OObjects — instances of classes
MMethods — functions inside classes
O M R R
"Organized Means Reusable & Real"
OOrganized code
MMaintainable — easy to maintain
RReusable code
RReal-world modeling

OOP is a programming style that uses classes, objects, and methods to organize large programs.

One-line summary: Function → reusable block · Class → blueprint/template · Object → instance of a class · OOP → organizing a program using objects.

Files & Exceptions

26

File Handling & Modes

Files
File handling = working with files (like .txt). It lets data live permanently instead of vanishing when the program ends.
P D L C
"Please Don't Lose Code" — why file handling matters
PPermanent storage — survives after the program ends (unlike variables)
DData sharing — move data between programs/systems
LLarge datasets — handle data too big for memory
CConfig & logging — store settings, log activity for debugging

open() and the 4 file modes

Open a file before using it; close it with close() afterward to free resources.

ModeNameBehavior
rReadFile must already exist
wWriteCreates new / overwrites existing (old content deleted!)
aAppendAdds to the end, keeps old content
r+Read/WriteBoth reading and writing

Read

file = open('data.txt', 'r')
print(file.read())

Gets all content.

Write

file = open('data.txt', 'w')
file.write('Hello World')

Overwrites — use carefully!

Append & Delete

file = open('data.txt', 'a')
file.write(' New text')

import os
os.remove('data.txt')
27

with & Reading Methods

Files

The with statement

Guarantees the file always closes, even if an error happens. Cleaner and more "Pythonic".

with open('data.txt') as file:
    print(file.read())
# auto-closed here

Three ways to read

MethodReturns
read()Entire file as one string
readline()One line at a time
readlines()All lines as a list

Practical applications

  • Data logging — save logs for debugging/auditing
  • Configuration files — store user preferences/settings
  • Data processing — read & process large datasets
  • Backup & restore — copy important data
28

Exceptions (try / except)

Errors
Exceptions are errors that happen during execution (e.g. "file not found"). Use try / except to handle them and avoid crashes.
try:
    file = open('data.txt')
except:
    print('File not found')

Why use exceptions?

  • Prevent the program from crashing
  • Show friendly error messages
  • Control the program's flow

NumPy · Numerical Python

29

NumPy & Arrays

NumPy
NumPy = Numerical Python. A library for scientific computing and working with arrays — faster and more efficient than Python lists for big batches of numbers.
I C I S D R U
"I Can Instantly Slice Data Really Ultrafast" — the 7 lesson topics
IIntroduction to NumPy
CCreating arrays
IIndexing
SSlicing
DDatatypes
RRandom
Uufunc (universal functions)

Creating arrays

Build from Python lists; supports 1D, 2D, and multi-dimensional arrays. Helpers: zeros(), ones(), arange().

import numpy as np

arr1 = np.array([1,2,3])
arr2 = np.zeros((2,2))
arr3 = np.arange(1,10)
print(arr1)
30

Index · Slice · Datatypes · Random · ufunc

NumPy

Indexing

Zero-based; can reach rows/columns in 2D arrays.

arr = np.array([10,20,30])
print(arr[0])   # 10

Slicing

Extract parts with start:end:step.

arr = np.array([1,2,3,4,5])
print(arr[1:4])  # [2 3 4]

Datatypes

Arrays have fixed dtypes (int, float, bool, string). Check with .dtype.

arr = np.array([1,2,3])
print(arr.dtype)

Random

Generate random numbers — great for simulations & ML. rand(), randint(), choice().

x = np.random.randint(1, 100)
print(x)

ufunc — Universal Functions

Fast, element-wise math operations: add(), subtract(), multiply(), sin().

a = np.array([1,2,3])
b = np.array([4,5,6])
print(np.add(a, b))   # [5 7 9]

★ Finals Cheat Sheet

Mnemonics & Rapid Review

Every mnemonic in one place

Topic#KeyPhrase
Tokens / Lexical Units5K I L O P"Keep It Logical, Or Panic"
Literals5S N B N C"Smart Nerds Build Neat Code"
Numeric types3I F C"I Find Complexity"
Data Type categories8T N S M S B B N"Ten New Students Make Some Big Brilliant Notes"
Multi-word naming3C P SCamel · Pascal · Snake
Operator groups7A A C L I M B"All Animals Can Leap Into Muddy Bogs"
OOP building blocks3C O MClasses · Objects · Methods
Why OOP matters4O M R R"Organized Means Reusable & Real"
Why file handling matters4P D L C"Please Don't Lose Code"
NumPy lesson topics7I C I S D R U"I Can Instantly Slice Data Really Ultrafast"

High-priority identification items

QuestionAnswer
Python is high-level, interpreted, general-purpose, and…Dynamic (focuses on code readability)
5 types of tokensKeywords, Identifiers, Literals, Operators, Punctuators
Reserved words that can't be identifiersKeywords
Max line length in Python79 characters
Statement terminator symbolNone — Python uses no terminator
EOL stands forEnd Of Line
Triple-quoted comment is calledDocstring
Re-pointing a variable to a new type isDynamic typing
Function to check a value's typetype()
input() always returns aString (cast with int()/float())
8 data type categoriesText, Numeric, Sequence, Mapping, Set, Boolean, Binary, None
3 numeric typesint, float, complex
7 operator groupsArithmetic, Assignment, Comparison, Logical, Identity, Membership, Bitwise
Highest precedenceParentheses ( )
is vs ==is → same object (memory); == → equal value
Keyword to define a functiondef
Parameter vs ArgumentParameter = in definition; Argument = value sent at call
One * vs two ** before a parameter*args → tuple; **kwargs → dictionary
Symbol for positional-only / keyword-only, / (positional) · *, (keyword)
Empty-body placeholder keywordpass
Class vs ObjectClass = blueprint; Object = instance
The constructor method__init__
self refers toThe current object
3 OOP building blocksClasses, Objects, Methods
4 file modesr (read), w (write/overwrite), a (append), r+ (read/write)
Mode that deletes old contentw (write)
Statement that auto-closes a filewith
3 read methodsread(), readline(), readlines()
Handle errors withtry / except
NumPy stands forNumerical Python
NumPy is faster thanPython lists
ufunc meansUniversal Functions
Slicing syntaxstart:end:step

Python keywords (quick scan)

andassertbreakclasscontinuedefdelelifelseexceptexecfinallyforfromglobalifimportinislambdanotorpassprintraisereturntrywhilewithyield
Python Finals Reviewer · Moitet · DCIT23 Computer Programming 2
Fundamentals · Data Types & Operators · Functions · Classes & OOP · Files & Exceptions · NumPy