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
# 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
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
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
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
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
double = "World"
multi = """Multiple
line string"""
String Operations
repeat = "Meow!" * 3 # "Meow!Meow!Meow!"
length = len("Python") # 6
String Methods
"A".lower() # "a"
" a ".strip() # "a"
"abc".replace("bc", "ha") # "aha"
"a b".split() # ["a","b"]
"-".join(["a", "b"]) # "a-b"
String Indexing & Slicing
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
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
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
float_num = 3.14 # float
complex_num = 2 + 3j # complex
print("Integer:", integer_num)
print("Float:", float_num)
print("Complex:", complex_num)
Arithmetic Operators
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
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
q = False
print("AND:", p and q)
print("OR:", p or q)
print("NOT p:", not p)
Assignment Operators
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
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-else Statement
if-elif-else Statement
Nested Conditionals
Conditional Expressions (Ternary Operator)
Logical Operators in Conditionals
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).
Iterating Through a List
You can loop directly through items in a collection like a list.
Using enumerate()
Use enumerate() when you need both the index (position) and the value.
While Loop
A while loop runs as long as a specific condition is True.
The break Statement
Use break to exit a loop prematurely, even if the condition is still true.
The continue Statement
Use continue to skip the rest of the current iteration and move to the next one.
Nested Loops
You can place a loop inside another loop.
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.
Parameters & Arguments
Pass data into functions to make them dynamic.
Default Parameters
Set a fallback value if no argument is provided.
Return Values
Use return to send data back to the caller. You can return multiple values as a tuple.
Lambda & Filter
Anonymous one-line functions using the lambda keyword. Often used with filter() or map().
System Introspection
Built-in functions like id() and callable() help analyze objects in memory.
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.
Class vs Instance Attributes
Instance Attributes (`self.name`) are unique to each object.
Class Attributes (`species`) are shared by all objects of that type.
Inheritance
You can create a new class that "inherits" features from an existing one. It prevents you from writing the same code twice.
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.
Else & Finally
else runs if no errors happened.finally runs always, no matter what (good for cleanup).
Common Errors
Different mistakes cause different exceptions. You can catch specific ones.
Raising Exceptions
You can force an error to happen if something is wrong using raise.
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 `[]`.
Tuples (The Immutable Seals)
Ordered but immutable (cannot change after creation). Faster than lists. Use `()`.
Sets (Unique & Math)
Unordered and no duplicates. Great for math operations like Union and Intersection. Use `{}`.
Dictionaries (Key-Value Maps)
Store data in `Key: Value` pairs. Fast lookups using keys.
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.
Dictionary & Set Comprehensions
You can use the same logic to create dictionaries (key-value) and sets (unique items).
Nested Comprehensions
Useful for generating multi-dimensional structures like matrices. A nested comprehension acts like a loop inside another loop.
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 *.
Package Imports
Packages are directories containing multiple modules. Use dot notation to navigate them.
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 pdfor better readability.