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-in help() 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 runtime


2. 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: True or False. 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(), or tuple().

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 characters


6. 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 -> DISCONNECTED


Input 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 integer


7. 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 + 3 evaluates to 13.

  • - (Subtraction): Subtracts the right operand from the left. 10 - 3 evaluates to 7.

  • * (Multiplication): Multiplies two values. 10 * 3 evaluates to 30.

  • / (True Division): Divides operands. Always returns a float. 10 / 3 evaluates to 3.333.

  • // (Floor Division): Divides values and rounds down to the nearest whole integer. 10 // 3 evaluates to 3.

  • % (Modulus): Returns the remainder of a division operation. 10 % 3 evaluates to 1.

  • (Exponentiation): Raises the base to a power (). 10 3 evaluates to 1000.


B. Comparison (Relational) Operators

Compare two values and return a Boolean flag (True or False).

  • == (Equal To): Checks structural value equality. 10 == 3 is False.

  • != (Not Equal To): Checks structural differences. 10 != 3 is True.

  • > (Greater Than): True if left is larger than right. 10 > 3 is True.

  • < (Less Than): True if left is smaller than right. 10 < 3 is False.

  • >= (Greater Than or Equal): True if left matches or exceeds right. 10 >= 10 is True.

  • <= (Less Than or Equal): True if left is smaller or matches right. 3 <= 1 is False.


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: Returns True only if both operands evaluate to True. If the left operand is False, the entire expression returns False immediately, and the right side is ignored.

  • or: Returns True if at least one operand evaluates to True. If the left operand is True, the expression short-circuits and returns True immediately without evaluating the right side.

  • not: Unary operator that inverts the Boolean state of its operand (not True becomes False).


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 to 1 only if both matching bits are 1.

  • | (Bitwise OR): Sets each bit to 1 if at least one of the matching bits is 1.

  • ^ (Bitwise XOR): Sets each bit to 1 only 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: Returns True if the specified element is discovered inside the targeted container.

  • not in: Returns True if 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: True


G. 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: Returns True if both variables point to the exact same object in memory ().

  • is not: Returns True if 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):

  1. () — Parentheses (Explicit Grouping)

  2. — Exponentiation (Math Power)

  3. +x, -x, ~x — Unary Plus, Unary Minus, Bitwise NOT

  4. *, /, //, % — Multiplication, Division, Floor Division, Modulus

  5. +, - — Running Addition, Subtraction

  6. <<, >> — Bitwise Left and Right Shifts

  7. & — Bitwise AND

  8. ^ — Bitwise XOR

  9. | — Bitwise OR

  10. ==, !=, >, >=, <, <=, is, is not, in, not in — Comparisons, Identity Lookups, and Membership Tests

  11. not — Logical NOT

  12. and — Logical AND (Short-Circuit)

  13. or — Logical OR (Short-Circuit)

  14. =, +=, -=, *=, /=, //=, %=, = — Standard and Compound Assignment Operators