Comments and Operators
1. Comments in Python
Comments are non-executing lines of text used to document code architecture, explain logic, or temporarily disable code blocks during debugging. The Python interpreter completely ignores comments during the bytecode compilation phase.
Single-Line Comments: Indicated by the hash symbol (
#). Anything following the#on that line is ignored.Multi-Line Comments (Block Comments): Python does not have a native token for multi-line comments. Instead, you can repeat single-line
#characters on consecutive lines, or use unassigned multi-line string literals ("""or''').Docstrings (Documentation Strings): String literals placed as the absolute first statement inside a function, class, or module. Unlike plain comments, docstrings remain attached to the object runtime structure and can be inspected via the object's
__doc__attribute or the built-inhelp()function.
Python
# Single-line operational comment
api_port = 8080
"""
This is an unassigned multi-line string literal.
It serves as a block comment for structural documentation.
"""
def process_transaction(amount):
"""Executes a financial transaction ledger update. (Docstring)"""
pass
print(process_transaction.__doc__) # Outputs the docstring text at runtime2. Keywords and Identifiers
Keywords
Keywords are reserved, hardcoded words that have specific, fixed meanings to the Python interpreter core. They define the structural syntax of the language and cannot be reused as variable names, function names, or any other identifier label. Python keywords are case-sensitive (e.g., True, False, and None are capitalized; the rest are lowercase).
Python
import keyword
print(keyword.kwlist) # Prints all keywords (e.g., 'False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', etc.)Identifiers
Identifiers are user-defined alphanumeric names used to label variables, functions, classes, modules, or objects. Python enforces strict lexical rules for naming identifiers:
Must begin with a letter (
a-z,A-Z) or an underscore (_).Cannot begin with a digit (
0-9).Can contain alphanumeric characters and underscores (
a-z,A-Z,0-9, and_).Cannot contain special symbols or punctuation marks (like
@,$,!, or-).Cannot match any reserved Python keyword.
3. Variables & Dynamic Typing
In many compiled languages (like C++ or Java), a variable is a named memory box that holds a specific type of data value.
In Python, a Variable is simply a lightweight Reference Pointer (or label) tagged to an object floating inside the Memory Heap. You do not declare a variable's type upfront; the type is bound to the object itself, not the variable pointer.
Python
# The integer object 1024 is allocated in the heap.
# The variable identifier 'network_buffer' points directly to it.
network_buffer = 1024
# Reassignment breaks the old pointer and binds 'network_buffer' to a string object.
network_buffer = "Buffer_Overflow"4. Built-in Data Types
Python groups its core data structures into distinct built-in types based on their behavioral characteristics:
Numeric Types:
int: Handles arbitrary-precision integers.float: Double-precision floating-point numbers.complex: Handles mathematical complex numbers ().Mutability: All numeric types are Immutable.
Boolean Type:
bool: Represents logical states:TrueorFalse. It is a subclass of integers where and .Mutability: Immutable.
Sequence Types:
str: An ordered sequence of Unicode text characters enclosed in quotes. (Immutable)list: An ordered, changeable collection of heterogeneous array elements ([1, "text", 3.4]). (Mutable)tuple: An ordered, unchangeable collection used for fixed records ((443, "HTTPS")). (Immutable)
Set Types:
set: An unordered, un-indexed collection of unique, hashable items. Prevents duplicate values. (Mutable)
Mapping Types:
dict: An associative collection of unique key-value pairs ({"port": 8080}). (Mutable)
5. Type Casting (Explicit vs. Implicit Conversion)
Type casting converts a value from one data type to another.
Implicit Type Conversion: Handled automatically by the Python interpreter to prevent data loss when mixing types during math operations.
Explicit Type Conversion (Type Casting): Triggered manually by the developer using built-in constructor functions like
int(),float(),str(),list(), ortuple().
Python
# IMPLICIT CONVERSION: Python automatically upgrades the integer to a float
result = 10 + 4.5 # int + float -> float (14.5)
# EXPLICIT CASTING: Converting a string input to an integer manually
raw_input = "8080"
listening_port = int(raw_input) # Throws ValueError if string contains non-numeric characters6. Basic Input and Output (I/O)
Output Optimization via print()
The built-in print() function converts objects to text strings and flushes them to the standard output stream (sys.stdout). It includes custom keyword arguments to format output strings cleanly:
sep: Defines the separator string inserted between multiple items (default is a space" ").end: Defines the string appended to the absolute end of the print statement (default is a newline"\n").
Python
print("10.0.0.1", "80", sep=":", end=" -> DISCONNECTED\n")
# Outputs exactly: 10.0.0.1:80 -> DISCONNECTEDInput Ingestion via input()
The input() function pauses script execution and waits for the user to type text into the terminal console. Critical Guardrail: The input() function always reads and returns the user's input data as a String (str). If you need to perform math calculations with the input, you must cast it to a number explicitly.
Python
user_age = int(input("Enter node registration age: ")) # Explicitly cast string return to integer7. Python Operators Deep Dive
Operators are symbols that trigger specific mathematical, relational, or logical evaluations on data arguments (operands).
A. Arithmetic Operators
Used to perform standard mathematical operations.
+(Addition): Adds two numeric operands.10 + 3evaluates to13.-(Subtraction): Subtracts the right operand from the left.10 - 3evaluates to7.*(Multiplication): Multiplies two values.10 * 3evaluates to30./(True Division): Divides operands. Always returns a float.10 / 3evaluates to3.333.//(Floor Division): Divides values and rounds down to the nearest whole integer.10 // 3evaluates to3.%(Modulus): Returns the remainder of a division operation.10 % 3evaluates to1.(Exponentiation): Raises the base to a power ().10 3evaluates to1000.
B. Comparison (Relational) Operators
Compare two values and return a Boolean flag (True or False).
==(Equal To): Checks structural value equality.10 == 3isFalse.!=(Not Equal To): Checks structural differences.10 != 3isTrue.>(Greater Than): True if left is larger than right.10 > 3isTrue.<(Less Than): True if left is smaller than right.10 < 3isFalse.>=(Greater Than or Equal): True if left matches or exceeds right.10 >= 10isTrue.<=(Less Than or Equal): True if left is smaller or matches right.3 <= 1isFalse.
C. Logical Operators
Used to combine conditional statements. Python evaluation uses Short-Circuit Logic; if the final Boolean outcome can be determined by evaluating the first condition, the second condition is skipped.
and: ReturnsTrueonly if both operands evaluate toTrue. If the left operand isFalse, the entire expression returnsFalseimmediately, and the right side is ignored.or: ReturnsTrueif at least one operand evaluates toTrue. If the left operand isTrue, the expression short-circuits and returnsTrueimmediately without evaluating the right side.not: Unary operator that inverts the Boolean state of its operand (not TruebecomesFalse).
D. Assignment Operators
Used to assign values to variables, often combining an arithmetic operation with assignment (In-Place Compound Assignment).
=: Standard assignment.x = 5+=: Add and assign.x += 3(Equivalent to:x = x + 3)=: Exponent and assign.x = 2(Equivalent to:x = x 2)
E. Bitwise Operators
Operate directly on the raw binary bits (0s and 1s) of integer data values.
&(Bitwise AND): Sets each bit to1only if both matching bits are1.|(Bitwise OR): Sets each bit to1if at least one of the matching bits is1.^(Bitwise XOR): Sets each bit to1only if the two matching bits are different.~(Bitwise NOT): Inverts all the bits of the operand (flips 1s to 0s and 0s to 1s).<<(Left Shift): Shifts binary bits to the left, padding empty right slots with 0s (multiplies by ).>>(Right Shift): Shifts binary bits to the right, discarding overflowing right bits (divides by ).
F. Membership Operators
Used to test whether a value or variable is present inside a sequence container (such as a string, list, tuple, set, or dictionary).
in: ReturnsTrueif the specified element is discovered inside the targeted container.not in: ReturnsTrueif the specified element is missing from the targeted container.
Python
active_ports = [80, 443, 8080]
print(443 in active_ports) # Outputs: True
print(22 not in active_ports) # Outputs: TrueG. Identity Operators
Compare whether two separate variables point to the exact same memory address location in the system heap. They check memory identity, not structural value equality.
is: ReturnsTrueif both variables point to the exact same object in memory ().is not: ReturnsTrueif the variables point to different objects in memory.
Python
list_alpha = [1, 2, 3]
list_beta = [1, 2, 3]
list_gamma = list_alpha
print(list_alpha == list_beta) # True (They contain the exact same data values)
print(list_alpha is list_beta) # False (They are separate objects sitting at different heap addresses)
print(list_alpha is list_gamma) # True (They point to the exact same memory location)8. Operator Precedence Hierarchy
When an expression contains multiple operators, Python evaluates them in a strict order based on their precedence. You can override this order at any time by wrapping expressions inside explicit grouping parentheses ().
This list ranks Python operators from the highest precedence (evaluated first) down to the lowest precedence (evaluated last):
()— Parentheses (Explicit Grouping)— Exponentiation (Math Power)+x,-x,~x— Unary Plus, Unary Minus, Bitwise NOT*,/,//,%— Multiplication, Division, Floor Division, Modulus+,-— Running Addition, Subtraction<<,>>— Bitwise Left and Right Shifts&— Bitwise AND^— Bitwise XOR|— Bitwise OR==,!=,>,>=,<,<=,is,is not,in,not in— Comparisons, Identity Lookups, and Membership Testsnot— Logical NOTand— Logical AND (Short-Circuit)or— Logical OR (Short-Circuit)=,+=,-=,*=,/=,//=,%=,=— Standard and Compound Assignment Operators