Everything you need to check syntax fast β plus a short recap of what each session taught. Keep this tab open while you code.
# 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.
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.
"hello" | str β text |
42 | int β whole number |
3.14 | float β decimal |
True / False | bool β yes/no |
["a","b"] | list β many things |
str(42) | number β text |
int("42") | text β number |
len(x) | how long it is |
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!"
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.
words = "correct horse battery".split() # ["correct", "horse", "battery"] "-".join(words) # "correct-horse-battery"
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
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.
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.
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.)
if len(pw) >= 12: print("Strong length β ") elif len(pw) >= 8: print("Okay-ish π") else: print("Too short β")
== | is equal to (two equals!) |
!= | is NOT equal to |
> < >= <= | bigger / smaller |
and | both must be true |
or | either can be true |
not | flips true/false |
= stores a value. == compares. Mixing them up is super common.
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.
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.
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.
import random, string pool = string.ascii_letters + string.digits + "!@#$%" pw = "".join(random.choice(pool) for _ in range(16)) print(pw)
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.
from bs4 import Comment comments = soup.find_all( string=lambda t: isinstance(t, Comment)) for c in comments: print(c.strip())
# β 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.
Usually: a missing : at the end of an if/for/def line, or an unclosed bracket ( / quote ". Check the line above the arrow too.
Fix: a typo, or you used it before creating it. In Colab: did you run the earlier cell? Order matters.
# β 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.
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.
!pip install requests beautifulsoup4
Fix: in Colab, run that in a cell first (the ! is required), then re-run your import.
data- attributes, robots.txt, hidden elements and cookies.P@ss1.