|$ curl https://forge-ai.dev/api/markdown?path=docs/python/basics
$cat docs/python-—-basics.md
updated Recently·15 min read·published

Python — Basics

PythonBeginner
Introduction

This section covers the absolute fundamentals: variables, data types, operators, and control flow. These are the building blocks of every Python program.

Variables & Assignment

Python variables are dynamically typed references to objects. You assign with = and don't need type declarations.

variables.py
Python
1# Variable assignment
2message = "Hello, Python!"
3count = 42
4pi = 3.14159
5is_valid = True
6
7# Multiple assignment
8a, b, c = 1, 2, 3
9x = y = z = 0 # all three point to 0
10
11# Swapping — no temp variable needed
12a, b = b, a
13
14# Variable naming rules
15# - Letters, digits, underscores (not starting with digit)
16# - Case-sensitive (myVar != myvar)
17# - Use snake_case by convention
18# - Reserved keywords can't be used:
19# False, None, True, and, as, assert, async, await,
20# break, class, continue, def, del, elif, else, except,
21# finally, for, from, global, if, import, in, is, lambda,
22# nonlocal, not, or, pass, raise, return, try, while, with, yield

info

Python uses snake_case for variables and functions, PascalCase for classes, and UPPER_CASE for constants. This is PEP 8 convention.
Numeric Types & Operators
numbers.py
Python
1# Integers (unbounded — no overflow)
2print(2 ** 1000) # huge number works fine
3
4# Floats (IEEE 754 double precision)
5print(0.1 + 0.2) # → 0.30000000000000004 (float precision!)
6
7# Arithmetic operators
8print(10 + 3) # → 13 addition
9print(10 - 3) # → 7 subtraction
10print(10 * 3) # → 30 multiplication
11print(10 / 3) # → 3.3333... true division
12print(10 // 3) # → 3 floor division
13print(10 % 3) # → 1 modulo (remainder)
14print(10 ** 3) # → 1000 exponentiation
15
16# Augmented assignment
17x = 5
18x += 2 # x = x + 2 → 7
19x *= 3 # x = x * 3 → 21
20
21# Comparison operators
22print(5 == 5) # → True (equal)
23print(5 != 5) # → False (not equal)
24print(5 < 10) # → True
25print(5 >= 5) # → True
26
27# Chained comparisons
28print(1 < x < 10) # → True (equivalent to: 1 < x and x < 10)
Booleans & Logical Operators
booleans.py
Python
1# Boolean literals
2is_ready = True
3is_done = False
4
5# Logical operators
6print(True and False) # → False
7print(True or False) # → True
8print(not True) # → False
9
10# Short-circuit evaluation
11def expensive():
12 print("called!")
13 return True
14
15result = False and expensive() # expensive() never called
16result = True or expensive() # expensive() never called
17
18# Truthiness — every object is truthy or falsy
19# Falsy values: False, None, 0, 0.0, "", [], (), {}, set()
20# Everything else is truthy
21
22if "hello": # truthy — runs
23if 0: # falsy — doesn't run
24if []: # falsy — doesn't run
25
26# The 'is' operator (identity vs equality)
27a = [1, 2, 3]
28b = [1, 2, 3]
29print(a == b) # → True (same value)
30print(a is b) # → False (different objects)
31
32c = a
33print(c is a) # → True (same object)
Strings — Deep Dive
strings.py
Python
1# String creation
2single = 'single quotes'
3double = "double quotes"
4triple = """triple quotes — multi-line"""
5
6# Escape sequences
7print("line1\nline2") # newline
8print("tab\there") # tab
9print("backslash: \\") # backslash
10print('single quote: \'') # single quote
11print("double quote: \"") # double quote
12
13# Raw strings (no escaping — great for regex/paths)
14path = r"C:\Users\name\file.txt"
15regex = r"\d+\.\d+"
16
17# String methods — non-exhaustive
18text = " hello, World! "
19print(text.strip()) # remove whitespace
20print(text.lower()) # lowercase
21print(text.upper()) # uppercase
22print(text.replace("World", "Python")) # replace
23print(text.split(",")) # split into list
24print(",".join(["a", "b", "c"])) # join list into string
25print(text.startswith(" he")) # → True
26print(text.find("World")) # → 8 (index, -1 if not found)
27print("hello" in text) # → True (membership test)
28
29# String formatting — f-strings are best
30name, age = "Alice", 30
31print(f"{name} is {age} years old")
32print(f"{name!r}") # repr of name — "Alice" (with quotes)
33print(f"{age:04d}") # → 0030 (zero-padded)
34print(f"{3.14159:.2f}") # → 3.14 (rounded)
35
36# Older styles (avoid in new code)
37print("%s is %d years old" % (name, age)) # %-formatting
38print("{} is {} years old".format(name, age)) # str.format()
39
40# Unicode support
41print("\u00F1") # ñ
42print("\N{SNOWMAN}") # ☃ (using Unicode name)
Control Flow — Deep Dive
control_flow.py
Python
1# if / elif / else
2score = 85
3if score >= 90:
4 grade = "A"
5elif score >= 80:
6 grade = "B"
7elif score >= 70:
8 grade = "C"
9else:
10 grade = "F"
11
12# Inline if (ternary)
13age = 20
14status = "adult" if age >= 18 else "minor"
15
16# For loop — fundamental iteration
17for i in range(5): # 0, 1, 2, 3, 4
18 print(i)
19
20for i in range(2, 6): # 2, 3, 4, 5
21 print(i)
22
23for i in range(0, 10, 2): # 0, 2, 4, 6, 8
24 print(i)
25
26# Iterate over collection
27fruits = ["apple", "banana", "cherry"]
28for fruit in fruits:
29 print(fruit)
30
31# Enumerate — when you need index
32for idx, fruit in enumerate(fruits):
33 print(f"{idx}: {fruit}")
34
35# Zip — iterate multiple lists in parallel
36names = ["Alice", "Bob", "Charlie"]
37ages = [30, 25, 35]
38for name, age in zip(names, ages):
39 print(f"{name} is {age}")
40
41# While loop
42count = 0
43while count < 3:
44 print(count)
45 count += 1
46
47# Break, continue, else
48for n in range(10):
49 if n % 3 == 0:
50 continue # skip multiples of 3
51 if n > 8:
52 break # stop at 8
53 print(n)
54else:
55 print("loop finished") # runs if no break
56
57# Pass — no-op placeholder
58def future_function():
59 pass
None — The Absence of Value
none.py
Python
1# None is Python's null/undefined
2result = None
3
4# Check for None with 'is', not '=='
5if result is None:
6 print("no result")
7
8if result is not None:
9 print("got result")
10
11# Common use: default return
12def find_user(user_id):
13 # if not found:
14 return None
Type Conversion
conversion.py
Python
1# Explicit conversion
2print(int("42")) # string → int → 42
3print(float("3.14")) # string → float → 3.14
4print(str(100)) # int → string → "100"
5print(bool(1)) # int → bool → True
6print(list("hello")) # string → list → ['h','e','l','l','o']
7
8# Converting between collections
9print(list((1, 2, 3))) # tuple → list
10print(tuple([1, 2, 3])) # list → tuple
11print(set([1, 2, 2, 3])) # list → set (dedupes) → {1, 2, 3}
12
13# Ordering caution: int/float comparison works
14print(1 == 1.0) # → True (value comparison, not type)
$Blueprint — Engineering Documentation·Section ID: PYTHON-BASICS·Revision: 1.0