Python Fundamentals: Complete Guide
Overview
This comprehensive document contains 12 Python educational modules covering core programming
concepts. Each module explores fundamental aspects of the Python language through well-
documented code examples and explanations.
1. Constants and Variables
Constants (constants.py)
Python doesn't have a built-in constant type, but constants are conventionally defined using all-caps
naming. The Final type annotation from the typing module can indicate to tools like mypy that
variables shouldn't be reassigned.
PI = 3.14159
PLANCK_CONSTANT: Final[float] = 6.62607015e-34
_PRIVATE_CONSTANT: Final[int] = 42
Private constants can be declared with a leading underscore to prevent exporting to other modules.
Variables (variables.py)
Variables in Python store data and are created when values are assigned. Python is dynamically
typed, meaning variable types are determined at runtime. Variables are block-scoped, with file-scope
variables being global to the module.
Key concepts include:
Global variables: Accessible throughout a module but require the global keyword to modify
Local variables: Block-scoped and accessible only within their scope
Nonlocal variables: Used to modify variables in enclosing function scopes
Type hints can be added to indicate intended types, though Python itself doesn't enforce them at
runtime.
2. Data Types
Number Literals (number_literals.py)
Python supports three types of numeric literals:
Integer Literals:
Decimal: 42
Binary: 0b101010 (prefix with 0b)
Octal: 0o52 (prefix with 0o)
Hexadecimal: 0x2A (prefix with 0x)
Python 3 supports arbitrary precision integers limited only by available memory.
Floating Point Literals:
Standard: 42.0
Scientific notation: 42.0e3 or 42.0E3
With underscores: 123_456_789.012_345
Complex Numbers:
Purely imaginary: 42j
Complex: 42 + 42j
Booleans (booleans.py)
Python has two boolean literals: True and False. The bool() function converts values to boolean:
Falsy values: 0, 0.0, "", [], (), {}, set(), None
Truthy values: Any non-zero number, non-empty sequences, functions, classes
Strings and Bytes (strings_and_bytes.py)
Strings:
Sequences of Unicode code points
Single or double-quoted; triple quotes for multi-line
Immutable after creation
Can be concatenated using + operator
Bytes:
Immutable sequences of bytes
Useful for binary data
Prefix with b (e.g., b'Hello')
Convert using encode() and decode() methods
String comparison can be tricky with accents and diacritics. The unidecode library helps normalize
Unicode strings for reliable comparisons.
Sequences (sequences.py)
Immutable sequences: Strings, tuples, bytes, frozen sets
Mutable sequences: Lists, bytearrays, arrays
Sequences are ordered collections indexed by non-negative integers.
3. Operators (operators.py)
Operator Types
Arithmetic Operators: +, -, *, /, //, %, **
Comparison Operators: ==, !=, >, <, >=, <=
Logical Operators: and, or, not
Bitwise Operators: &, |, ^, ~, <<, >>
Assignment Operators: =, +=, -=, *=, /=, //=, %=, **=, &=, |=, ^=, <<=, >>=
Identity Operators: is, is not
Membership Operators: in, not in
Ternary Operator: x if condition else y
Walrus Operator: := (assignment expression, Python 3.8+)
Key distinction: Unlike JavaScript, Python doesn't perform type coercion during comparison. If types
don't match, comparison returns False.
4. Control Flow (control_flow.py)
Conditional Statements
if Statement:
if x > 3:
print('x is greater than 3')
if-elif-else Statement:
if x > 3:
print('x is greater than 3')
elif x == 3:
print('x is equal to 3')
else:
print('x is less than 3')
match Statement (Pattern Matching, Python 3.10+):
match x:
case 1:
print('x is 1')
case _:
print('x is something else')
Loop Statements
for Loop:
for i in range(5):
print(i)
while Loop:
i = 0
while i < 5:
print(i)
i += 1
for-else Statement: The else block executes when the loop exits without encountering a break
Loop Control
break: Exit a loop
continue: Skip to next iteration
pass: Placeholder for future code
Other Control Flow
assert: Check if expression is True, raise AssertionError if False
return: Return value from function
with: Context manager for resource management
5. Special Values (none_not_implemented.py)
None
None indicates the absence of a value, similar to null in other languages. It's a singleton object in
Python.
Use the is operator for comparison: if value is None:
Optional[T] type hint indicates a function can return None.
NotImplemented
NotImplemented indicates that a method isn't implemented for specific operand types. Unlike raising
NotImplementedError, NotImplemented allows Python's runtime to continue chain computation (e.g.,
trying reverse operations).
Common use: Implement __add__ and __radd__ methods for custom types.
6. Printing (printing.py)
The print() function outputs to console with several parameters:
print(*args, sep=' ', end='\n', file=sys.stdout)
sep: Separator between arguments (default: space)
end: Terminating string (default: newline)
file: Output destination (default: sys.stdout)
Examples:
print('Hello', 'World', sep=', ', end='!\n')
print('Error', file=sys.stderr)
7. Classes Basics (class_basics.py)
Class Definition
Classes are blueprints for creating objects using the class keyword:
class MyClass:
"""Class docstring"""
def __init__(self):
"""Constructor"""
self.value = 42
Key Concepts
Instance: Object created from a class
Constructor: __init__ method called when creating instances
Instance attributes: Variables associated with specific objects
self: Automatically passed reference to the instance
Docstrings: Documentation using triple quotes
Empty class definitions require the pass statement or a docstring.
8. Inheritance (inheritance.py)
Inheritance allows classes to inherit behavior from parent classes.
Abstract Base Classes (ABC):
from abc import ABC, abstractmethod
class HasIntegerAdd(ABC):
@abstractmethod
def __add__(self, other: int) -> HasIntegerAdd:
"""Add the object to an integer"""
Abstract base classes define interfaces that subclasses must implement. The @abstractmethod
decorator marks methods that must be overridden.
Best Practices Summary
1. Type Hints: Use type annotations for clarity and static type checking
2. Documentation: Include docstrings for modules, classes, and functions
3. Variable Scope: Minimize use of global variables; prefer local and function-scoped variables
4. Constants: Use Final annotation and all-caps naming for constants
5. String Handling: Be careful with Unicode; use unidecode for normalization
6. Comparisons: Use is for None comparisons, not ==
7. Classes: Properly implement __init__ and use docstrings
8. Error Handling: Use context managers (with statements) for resource management
Python Version Note
This guide assumes Python 3.12+ unless otherwise noted. Some features like:
Pattern matching (match/case): Python 3.10+
Walrus operator (:=): Python 3.8+
Union type syntax (|): Python 3.10+
require specific Python versions.
[1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12]
1. operators.py
2. constants.py
3. booleans.py
4. control_flow.py
5. strings_and_bytes.py
6. none_not_implemented.py
7. printing.py
8. class_basics.py
9. inheritance.py
10. variables.py
11. sequences.py
12. number_literals.py