Foundations reference

Python Reference

Variables through algorithms, with the JavaScript equivalent noted beside each idea.

Getting started

Python reads close to English and uses indentation where other languages use braces. Everything below runs in the editor on any lesson page.

Output

print shows a value so you can see it.

print("Sankofa Code")
print(52 * 7)
  • JavaScript writes console.log() instead.

Variables

A name for a value. Python needs no keyword at all.

score = 10
score = 25          # reassigned

NAME = "Amara"      # capitals mean do not change this
  • Python has no const. All caps is a convention, not enforcement.
  • JavaScript writes let or const in front.

Comments and indentation

A hash starts a comment. Indentation is not style here, it is the syntax.

# a note for a human

if score > 10:
    print("inside the if")
print("outside again")
  • Getting the indentation wrong changes what the program does, not just how it looks.

Data types

The types you use daily

Whole numbers, decimals, text, booleans and the absence of a value.

42            # int
3.14          # float, a separate type
"text"        # str
True / False  # bool, capitalised
None          # nothing
  • JavaScript has one number type, lowercase true and false, and both null and undefined.

Strings

Text. An f-string drops values straight in.

name = "Amara"
greeting = f"Hello, {name}"

len(name)            # 5
name.upper()         # "AMARA"
name[0]              # "A"
"  hi  ".strip()     # "hi"
"a,b,c".split(",")   # ["a", "b", "c"]
  • JavaScript uses backtick templates and name.length rather than len().

Converting between types

Input arrives as text. Convert before doing arithmetic.

int("42")       # 42
float("3.5")    # 3.5
str(42)         # "42"

"7" + "3"       # "73"  joined
int("7") + 3    # 10    added

"42".isdigit()  # check before converting
  • isdigit() is how you check text is safe to convert without an exception.

Collections

Lists

An ordered collection. JavaScript calls the same idea an array.

names = ["Ama", "Kofi", "Zuri"]

names[0]            # "Ama"
len(names)          # 3
names.append("Nia")
"Ama" in names      # True
names[0:2]          # a copy of the first two
  • Assigning a list to another name shares it. Use names.copy() to make a real copy.

Dictionaries

Named fields. JavaScript calls the same idea an object.

member = {"name": "Ama", "hours": 40}

member["name"]            # "Ama"
member.get("city", "?")   # a safe default
member["city"] = "Atlanta"
member.keys()
  • .get() returns a default instead of raising a KeyError, which is often what you want.

Sets and comprehensions

A set holds unique values. A comprehension builds a list in one line.

unique = set(names)          # duplicates removed

evens = [n for n in nums if n % 2 == 0]
doubled = [n * 2 for n in nums]

sorted(members, key=lambda m: m["hours"], reverse=True)
  • Membership in a set is far faster than scanning a list, which is how O(n squared) becomes O(n).

Control flow

Conditionals

Ordered tests. The first true branch wins, so put the most specific first.

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
else:
    grade = "Keep going"
  • Python writes elif where JavaScript writes else if.
  • One equals assigns, two compares.

Loops

for walks a collection directly. while repeats until a condition stops being true.

for n in numbers:
    total += n

for i in range(5):     # 0 to 4
    print(i)

while balance < goal:
    balance += 75
  • range stops before the number you give it.
  • A while loop needs something inside it to change, or it never ends.

Errors

Wrap risky work, handle the failure, and let finally clean up either way.

try:
    n = int(text)
except ValueError:
    n = 0
finally:
    print("Always runs")

raise ValueError("empty list")
  • Catch the specific error you expect rather than everything.

Functions

Defining and returning

A named, reusable operation. Returning hands the value back; printing throws it away.

def total(items):
    result = 0
    for i in items:
        result += i
    return result


def greet(name="friend"):
    return f"Hello, {name}"
  • A function that prints instead of returning cannot be used as a building block.
  • JavaScript writes function total(items) with braces.

Scope

Assigning inside a function creates a local variable. The outer one is untouched.

count = 10

def change():
    count = 99      # a different variable

change()
# count is still 10
  • Arguments are local too, so reassigning one inside a function does not affect the caller.

JSON and files

JSON

An agreed text format for structured data. Parse it before you can use it.

import json

data = json.loads(text)        # text  -> data
text = json.dumps(data)        # data  -> text
  • Wrap the parse in try/except. Input you did not create can always be malformed.

Files

with open guarantees the file is closed, even if something fails partway.

with open("notes.txt") as f:
    contents = f.read()

with open("out.txt", "w") as f:
    f.write("done\n")
  • A browser cannot touch your filesystem, so this one is for Python on your own machine.

Algorithms and complexity

The patterns that cover most problems

Counting, accumulating, searching, filtering, mapping and finding extremes.

# running maximum
biggest = numbers[0]
for n in numbers:
    if n > biggest:
        biggest = n

# duplicates in one pass
seen = set()
for x in items:
    if x in seen:
        return True
    seen.add(x)
  • Start a maximum from the first real element, never from 0, or an all-negative list returns 0.

Complexity

How the work grows as the input grows. Sequence adds, nesting multiplies.

O(1)       indexing
O(log n)   binary search
O(n)       one loop
O(n log n) a good sort
O(n^2)     nested loops
  • Swapping a nested search for a set lookup turns O(n squared) into O(n).
  • Make it correct first, measure, then optimise.

Edge cases worth testing every time

The six that catch the overwhelming majority of real defects.

[]           # empty
[x]          # one item
[x, x, x]    # all identical
             # answer first
             # answer last
[-3, -9]     # negatives
0            # zero

Want to learn how to build with this?

A reference tells you what exists. The course teaches you when to reach for it, and has you build something real while you learn.