QUICK REFERENCE

🐍 Python Cheat Sheet & Debrief

Everything you need to check syntax fast β€” plus a short recap of what each session taught. Keep this tab open while you code.

Basics Strings Lists Loops If / Else Functions Camp recipes Fix my error Session debrief

1️⃣ The absolute basics

Variables & printing

# store a value in a name
name = "Alex"
age  = 12
score = 9.5
is_safe = True

print("Hello", name)
print(f"Hi {name}, age {age}")  # f-string

An f-string (the f before the quote) lets you drop variables straight inside text.

Asking the user

word = input("Type a password: ")
print("You typed:", word)

# input() ALWAYS gives text.
# Want a number? convert it:
n = int(input("How many? "))

Forgetting int() is the #1 cause of "can't add text to a number" errors.

Types & converting

"hello"str β€” text
42int β€” whole number
3.14float β€” decimal
True / Falsebool β€” yes/no
["a","b"]list β€” many things
str(42)number β†’ text
int("42")text β†’ number
len(x)how long it is

2️⃣ Strings (text) β€” your main tool

Everyday string moves

pw = "Str0ngPass!"

len(pw)              # 11 β€” how many characters
pw.upper()          # "STR0NGPASS!"
pw.lower()          # "str0ngpass!"
pw[0]               # "S"  (first β€” counting starts at 0!)
pw[-1]              # "!"  (last)
pw[0:3]             # "Str" (slice)
"a" in pw           # False β€” is "a" inside?
pw.replace("0","o") # "StrongPass!"

Checking what's in a password

import string

has_upper = any(c.isupper() for c in pw)
has_digit = any(c.isdigit() for c in pw)
has_symbol = any(c in string.punctuation for c in pw)

print(has_upper, has_digit, has_symbol)

any() = "is it true for at least one?" Handy for password rules.

Joining & splitting

words = "correct horse battery".split()
# ["correct", "horse", "battery"]

"-".join(words)
# "correct-horse-battery"

3️⃣ Lists

Making & changing lists

flags = ["comment", "robots"]

flags.append("cookie")   # add to the end
flags[0]                  # "comment"
len(flags)               # 3
"robots" in flags       # True
flags.remove("robots")   # take it out
sorted(flags)            # A→Z copy

Picking at random

import random

random.choice(["a","b","c"])   # one item
random.randint(1, 6)          # 1..6 inclusive
random.shuffle(flags)         # mixes in place

Used in the password generator project.

4️⃣ Loops β€” doing it many times

for β€” go through each item

for letter in "cyber":
    print(letter)

for flag in flags:
    print("Found:", flag)

for i in range(5):      # 0,1,2,3,4
    print(i)

⚠️ The indented lines are the loop's body. Indentation is the code.

while β€” keep going until…

guesses = 0
while guesses < 3:
    print("Try again")
    guesses = guesses + 1

Make sure something changes inside, or it loops forever. (Stop it in Colab with the ⏹ button.)

5️⃣ If / Else β€” making decisions

The shape of a decision

if len(pw) >= 12:
    print("Strong length βœ…")
elif len(pw) >= 8:
    print("Okay-ish 😐")
else:
    print("Too short ❌")

Comparing & combining

==is equal to (two equals!)
!=is NOT equal to
> < >= <=bigger / smaller
andboth must be true
oreither can be true
notflips true/false

= stores a value. == compares. Mixing them up is super common.

6️⃣ Functions β€” name your own move

Make one, then use it

def check_strength(password):
    score = 0
    if len(password) >= 12: score += 2
    if any(c.isdigit() for c in password): score += 1
    return score

print(check_strength("hunter2"))   # 1

return hands a value back. Without it you get None.

Importing tools

import hashlib      # hashing
import random       # randomness
import string       # letter sets
import requests     # fetch web pages

from bs4 import BeautifulSoup  # read HTML

Imports go at the very top of your file.

🎯 Camp recipes β€” the exact code you used

πŸ” Hash a password (SHA-256)

import hashlib

pw = "correct-horse"
h = hashlib.sha256(pw.encode()).hexdigest()
print(h)

.encode() turns text into bytes β€” hashing needs bytes. A hash is one-way: you can't un-hash it.

🎲 Generate a strong password

import random, string

pool = string.ascii_letters + string.digits + "!@#$%"
pw = "".join(random.choice(pool) for _ in range(16))
print(pw)

πŸ”Ž HTML Detective β€” read a page

import requests
from bs4 import BeautifulSoup

page = requests.get("https://example.com")
soup = BeautifulSoup(page.text, "html.parser")

for link in soup.find_all("a"):
    print(link.get("href"))

Only scan sites you own or that invite testing β€” the Detective's Code.

πŸ•΅οΈ Find hidden comments

from bs4 import Comment

comments = soup.find_all(
    string=lambda t: isinstance(t, Comment))
for c in comments:
    print(c.strip())

🚨 "Fix my error" β€” the usual suspects

IndentationError

# βœ— wrong
for i in range(3):
print(i)

Fix: indent the lines inside a for, while, if or def β€” 4 spaces. Don't mix tabs and spaces.

SyntaxError: invalid syntax

Usually: a missing : at the end of an if/for/def line, or an unclosed bracket ( / quote ". Check the line above the arrow too.

NameError: name 'x' is not defined

Fix: a typo, or you used it before creating it. In Colab: did you run the earlier cell? Order matters.

TypeError: can only concatenate str

# βœ— print("Age: " + 12)
# βœ“ print("Age: " + str(12))
# βœ“ print(f"Age: {12}")

Fix: you mixed text and numbers β€” convert with str() or use an f-string.

IndexError: list index out of range

Fix: you asked for an item that isn't there. Remember lists start at 0, so a 3-item list has indexes 0,1,2.

ModuleNotFoundError

!pip install requests beautifulsoup4

Fix: in Colab, run that in a cell first (the ! is required), then re-run your import.

🧠 Session debrief β€” 60-second recaps

Session 1 Β· Foundations

What cyber security actually is

Ask yourself: which part of the CIA triad does a backup protect?
Session 2 Β· Web Detective

Websites hide more than they show

Ask yourself: why is hiding a price with CSS not a real protection?
Session 3 Β· Passwords & People

The human is the easiest way in

Ask yourself: why is a 16-character passphrase harder to brute-force than an 8-character jumble?
Session 4 Β· Secret Codes

Cryptography β€” from Caesar to HTTPS

Ask yourself: if someone steals a public key, can they read your messages?
Session 5 Β· Attack & Defend

How attacks work β€” so you can stop them

Ask yourself: name one defence that costs the attacker time rather than blocking them outright.
Session 6 Β· AI Frontier & Finale

AI changes both sides

Ask yourself: what's the one check you'd run before believing a shocking video?