Python Protocol
Knowledge Base

Essential syntax reference for the CodeStitcher Neural Engine. RUN CODEs directly in the stream.

Comments

  • Always add a space after the # for readability
  • Use comments to explain why the code exists, not what it does
  • Keep comments clear, short, and meaningful
  • Avoid writing unnecessary or obvious comments
comments.py
# This is a comment explaining the code
# print("This code will not run") ← This line is ignored by Python
print("This will run") # Comments do not affect execution

Data Types

  • Python is dynamically typed
  • Use None to represent missing or optional values
  • Use type() to check object type
  • Check for a specific type with isinstance()
  • issubclass() checks if a class is a subclass
data_types.py
print("Type of 42:", type(42))
print("Type of 3.14:", type(3.14))
print("Type of 'Hello':", type("Hello"))
print("Type of True:", type(True))
print("Type of None:", type(None))

print()

print("Is 3.14 a float?", isinstance(3.14, float))
print("Does int inherit from object?", issubclass(int, object))

Variables & Assignment

Variables are created when they are first assigned a value. Choose descriptive and meaningful variable names. Follow the snake_case naming convention. A variable can be reassigned to store a new value.

Basic Assignment

basic_assignment.py
# Basic Assignment
name = "Tamim" # String
age = 7 # Integer
height = 5.6 # Float
is_cat = True # Boolean
flaws = None # None type

print("Name:", name)
print("Age:", age)
print("Height:", height)
print("Is Cat:", is_cat)
print("Flaws:", flaws)

Parallel & Chained Assignments

parallel_chained.py
# Parallel & Chained Assignments
x, y = 10, 20 # Multiple values
a = b = c = 0 # Same value to multiple variables

print("x:", x, "y:", y)
print("a:", a, "b:", b, "c:", c)

Augmented Assignments

augmented_assignments.py
# Augmented Assignments
counter = 0
counter += 1 # Increment
numbers = [1, 2, 3]
numbers += [4, 5] # Extend list
permissions = 0b001 # Binary example
write = 0b010
permissions |= write # Add write permission

print("Counter:", counter)
print("Numbers:", numbers)
print("Permissions:", bin(permissions))

Strings

Learn how to create, manipulate, and format strings in Python.

Creating Strings

strings_example.py
single = 'Hello'
double = "World"
multi = """Multiple
line string"""

String Operations

operations.py
greeting = "me" + "ow!" # "meow!"
repeat = "Meow!" * 3 # "Meow!Meow!Meow!"
length = len("Python") # 6

String Methods

methods.py
"a".upper() # "A"
"A".lower() # "a"
" a ".strip() # "a"
"abc".replace("bc", "ha") # "aha"
"a b".split() # ["a","b"]
"-".join(["a", "b"]) # "a-b"

String Indexing & Slicing

index_slice.py
text = "Python"
print(text[0]) # "P" first
print(text[-1]) # "n" last
print(text[1:4]) # "yth"
print(text[:3]) # "Pyt"
print(text[3:]) # "hon"
print(text[::2]) # "Pto"
print(text[::-1]) # "nohtyP"

String Formatting

formatting.py
name = "Aubrey"
age = 2

# f-strings
print(f"Hello, {name}!")
print(f"{name} is {age} years old")
print(f"Debug: {age=}")

# format() method
template = "Hello, {name}! You're {age}."
print(template.format(name=name, age=age))

Raw Strings

raw_strings.py
# Normal string with tab
text = "This is:\tCool."
print(text)

# Raw string keeps escape sequences
raw_text = r"This is:\tCool."
print(raw_text)

Numbers & Math

Learn about numbers, numeric types, and basic arithmetic operations in Python.

Number Types

number_types.py
integer_num = 42 # int
float_num = 3.14 # float
complex_num = 2 + 3j # complex

print("Integer:", integer_num)
print("Float:", float_num)
print("Complex:", complex_num)

Arithmetic Operators

arithmetic_ops.py
a = 10
b = 3

print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Floor Division:", a // b)
print("Modulus:", a % b)
print("Exponent:", a ** b)

Comparison Operators

comparison_ops.py
x = 5
y = 10

print("Equal:", x == y)
print("Not Equal:", x != y)
print("Greater:", x > y)
print("Less:", x < y)
print("Greater or Equal:", x >= y)
print("Less or Equal:", x <= y)

Logical Operators

logical_ops.py
p = True
q = False

print("AND:", p and q)
print("OR:", p or q)
print("NOT p:", not p)

Assignment Operators

assignment_ops.py
num = 10
num += 5 # Add 5
num -= 3 # Subtract 3
num *= 2 # Multiply by 2
num /= 4 # Divide by 4
num %= 3 # Modulus 3
num **= 2 # Exponent 2

Built-in Math Functions

math_functions.py
print(abs(-7)) # Absolute value
print(round(3.14159, 2)) # Round to 2 decimals
print(pow(2, 3)) # 2^3 = 8
print(max(5, 10, 3)) # Maximum
print(min(5, 10, 3)) # Minimum

Conditionals

Learn how to make decisions in Python using conditional statements.

if Statement

if_example.py
x = 10 if x > 5: print("x is greater than 5") if x < 5: print("x is less than 5")

if-else Statement

if_else_example.py
y = 7 if y % 2 == 0: print("y is even") else: print("y is odd")

if-elif-else Statement

if_elif_else.py
score = 85 if score >= 90: print("Grade: A") elif score >= 75: print("Grade: B") elif score >= 60: print("Grade: C") else: print("Grade: F")

Nested Conditionals

nested_conditionals.py
num = 15 if num > 0: if num % 2 == 0: print("Positive even number") else: print("Positive odd number") else: print("Non-positive number")

Conditional Expressions (Ternary Operator)

ternary_example.py
age = 18 status = "Adult" if age >= 18 else "Minor" print(status)

Logical Operators in Conditionals

logical_conditionals.py
a = 10 b = 5 c = 7 if a > b and a > c: print("a is the largest") if b > a or b > c: print("b is greater than at least one") print("End of checks")

Cycle Loops

Loops are used to repeat a block of code multiple times. Python primarily uses for and while loops.

For Loop with range()

The range() function generates a sequence of numbers (starting from 0 by default).

range_example.py
for i in range(5): print(f"Current number: {i}")

Iterating Through a List

You can loop directly through items in a collection like a list.

list_loop.py
fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(f"Scanning: {fruit}")

Using enumerate()

Use enumerate() when you need both the index (position) and the value.

enumerate_example.py
fruits = ["apple", "banana"] for index, fruit in enumerate(fruits): print(f"Index {index} is {fruit}")

While Loop

A while loop runs as long as a specific condition is True.

while_loop.py
count = 0 while count < 3: print(f"Count is: {count}") count += 1

The break Statement

Use break to exit a loop prematurely, even if the condition is still true.

break_example.py
for n in range(10): if n == 5: print("Breaching Loop...") break print(f"Processing: {n}")

The continue Statement

Use continue to skip the rest of the current iteration and move to the next one.

continue_example.py
for n in range(5): if n == 2: print("Skipping 2...") continue print(f"Number: {n}")

Nested Loops

You can place a loop inside another loop.

nested_loops.py
for i in range(2): for j in range(2): print(f"Coordinates: {i}, {j}")

Neural Functions

Functions encapsulate logic into reusable blocks. Define once using def, execute anywhere.

Defining & Calling

Use def to create a function and () to call it.

basic_func.py
def initialize_system(): print("System: Online") print("Ready for input.") # Call the function initialize_system()

Parameters & Arguments

Pass data into functions to make them dynamic.

params.py
def authenticate(user): print(f"Access granted to: {user}") authenticate("Commander") authenticate("Guest_01")

Default Parameters

Set a fallback value if no argument is provided.

defaults.py
def set_power(level=100): print(f"Power Level: {level}%") set_power(50) # Uses provided value set_power() # Uses default (100)

Return Values

Use return to send data back to the caller. You can return multiple values as a tuple.

return_data.py
def analyze_data(data): return min(data), max(data) low, high = analyze_data([10, 50, 90]) print(f"Low: {low}") print(f"High: {high}")

Lambda & Filter

Anonymous one-line functions using the lambda keyword. Often used with filter() or map().

lambda_logic.py
square = lambda x: x**2 print(f"Squared: {square(5)}") signals = [1, 2, 3, 4, 5] # Filter even numbers evens = list(filter(lambda x: x % 2 == 0, signals)) print(f"Even Signals: {evens}")

System Introspection

Built-in functions like id() and callable() help analyze objects in memory.

system_check.py
x = "Data" print(f"Can print be called? {callable(print)}") print(f"Memory ID: {id(x)}") print(f"Type: {type(x)}")

Object Classes

Classes are blueprints. Objects are the things you build from those blueprints. Use them to group data and functions together.

The Blueprint (Class)

Use class to define the blueprint. The __init__ function sets up the object when created. self refers to the specific object being built.

dog_blueprint.py
class Dog: def __init__(self, name, age): self.name = name # Save the name self.age = age # Save the age def bark(self): return f"{self.name} says Woof!" # Create an object (Instance) my_dog = Dog("Frieda", 3) print(my_dog.bark()) print(f"Age: {my_dog.age}")

Class vs Instance Attributes

Instance Attributes (`self.name`) are unique to each object.
Class Attributes (`species`) are shared by all objects of that type.

cats.py
class Cat: species = "Felis catus" # Shared by all cats def __init__(self, name): self.name = name # Unique to this cat cat1 = Cat("Luna") cat2 = Cat("Milo") print(f"{cat1.name} is a {cat1.species}") print(f"{cat2.name} is a {cat2.species}")

Inheritance

You can create a new class that "inherits" features from an existing one. It prevents you from writing the same code twice.

inheritance.py
# Parent Class class Animal: def __init__(self, name): self.name = name def speak(self): print("Some sound...") # Child Class (Inherits from Animal) class Dog(Animal): def speak(self): print(f"{self.name} Barks!") pet = Dog("Buddy") pet.speak()

Error Handling

When Python encounters an error, it stops. This is called an "Exception". You can handle these errors so your program doesn't crash.

Try & Except

Wrap risky code in a try block. If it fails, the except block runs instead of crashing.

safe_division.py
try: numerator = 10 denominator = 0 result = numerator / denominator print(result) except ZeroDivisionError: print("Error: You cannot divide by zero!") print("Program continues...")

Else & Finally

else runs if no errors happened.
finally runs always, no matter what (good for cleanup).

process_check.py
try: print("Attempting connection...") status = "Connected" except Exception: print("Connection Failed.") else: print(f"Success: {status}") finally: print("--- Operation Closed ---")

Common Errors

Different mistakes cause different exceptions. You can catch specific ones.

error_types.py
my_list = ["A", "B", "C"] try: print(my_list[5]) # Index 5 does not exist except IndexError: print("Error: That item is not in the list!") except TypeError: print("Error: Wrong data type.")

Raising Exceptions

You can force an error to happen if something is wrong using raise.

validator.py
def set_age(age): if age < 0: raise ValueError("Age cannot be negative!") print(f"Age set to {age}") try: set_age(-5) except ValueError as e: print(f"Blocked: {e}")

Data Collections

Collections are containers for storing multiple items. Each type has a specific superpower.

Lists (The Flexible Arrays)

Ordered, mutable (changeable), and allow duplicates. Use `[]`.

list_ops.py
fruits = ["banana", "apple"] # Modify List fruits.append("orange") # Add to end fruits.insert(0, "kiwi") # Add to start print(f"Fruits: {fruits}") print(f"First: {fruits[0]}") print(f"Total: {len(fruits)}") # Check existence if "apple" in fruits: print("Apple detected.")

Tuples (The Immutable Seals)

Ordered but immutable (cannot change after creation). Faster than lists. Use `()`.

tuple_unpack.py
point = (3, 4) # Unpacking (Assign to variables) x, y = point print(f"X: {x}, Y: {y}") # Extended Unpacking data = (1, 2, 3, 4) first, *rest = data print(f"First: {first}") print(f"Rest: {rest}")

Sets (Unique & Math)

Unordered and no duplicates. Great for math operations like Union and Intersection. Use `{}`.

set_math.py
a = {1, 2, 3} b = {3, 4, 5} # Math Operations print(f"Union (All): {a | b}") print(f"Intersect (Common): {a & b}") print(f"Difference (Only A): {a - b}")

Dictionaries (Key-Value Maps)

Store data in `Key: Value` pairs. Fast lookups using keys.

dict_ops.py
pet = {"name": "Leo", "age": 4} # Modify pet["sound"] = "Meow" # Add pet["age"] = 5 # Update print(f"Pet: {pet}") # Accessing Methods print(f"Keys: {list(pet.keys())}") print(f"Values: {list(pet.values())}")

Pythonic Comprehensions

Comprehensions provide a concise way to create collections. They are generally faster and more readable than traditional loops.

List Comprehensions

Create a new list by applying an expression to each item in an iterable.

list_comp.py
# Basic: Squares of 0-9 squares = [x**2 for x in range(10)] print(f"Squares: {squares}") # With Condition: Even numbers only evens = [x for x in range(20) if x % 2 == 0] print(f"Evens: {evens}")

Dictionary & Set Comprehensions

You can use the same logic to create dictionaries (key-value) and sets (unique items).

other_comp.py
words = ["hello", "world", "python"] # Dictionary: {word: length} word_map = {w: len(w) for w in words} print(f"Dict: {word_map}") # Set: Unique lengths unique_lens = {len(w) for w in words} print(f"Set: {unique_lens}")

Nested Comprehensions

Useful for generating multi-dimensional structures like matrices. A nested comprehension acts like a loop inside another loop.

matrix_comp.py
# Create a 3x3 Identity Matrix matrix = [[1 if r == c else 0 for c in range(3)] for r in range(3)] for row in matrix: print(row)

Imports & Modules

Modules allow you to organize code into separate files. You can import built-in libraries, third-party packages, or your own code.

Import Styles

There are different ways to bring external code into your script. Prefer explicit imports over import *.

import_styles.py
import math print(math.sqrt(16)) # Specific import from math import pi print(f"Pi is {pi}") # Import with Alias import datetime as dt print(dt.datetime.now())

Package Imports

Packages are directories containing multiple modules. Use dot notation to navigate them.

package_example.py
# General syntax (Pseudo-code) # from package.module import function import statistics as stats data = [1, 5, 10] print(f"Mean: {stats.mean(data)}")

Import Best Practices

  • Group your imports: Start with Standard Libraries, then Third-party, then your own Modules.
  • Avoid from module import *: It clutters your namespace and makes debugging difficult.
  • Use Aliases: Shorten long module names like import pandas as pd for better readability.