Python Fundamentals for Beginners
Master Python programming with visual diagrams, data flow charts, code examples covering variables, collections, functions, OOP, and best practices
Python is a high-level, interpreted programming language known for its simplicity, readability, and versatility in web development, data science, AI, and automation.
Python Execution Architecture
flowchart TB
A[Python Source .py] --> B[Python Interpreter]
B --> C[Bytecode Compilation]
C --> D[.pyc files]
D --> E[Python Virtual Machine]
E --> F[Execute Instructions]
G[Memory Management] --> H[Reference Counting]
G --> I[Garbage Collection]
style A fill:#2196F3
style B fill:#4CAF50
style C fill:#FF9800
style E fill:#9C27B0
style G fill:#F44336
Key Points:
- Interpreted Language: Python code is executed line by line by the interpreter
- Bytecode: Source code compiled to bytecode (.pyc) for faster execution
- PVM: Python Virtual Machine executes bytecode instructions
- Dynamic Typing: Variable types determined at runtime, not compile time
- Automatic Memory: Reference counting and garbage collection manage memory
Data Types Hierarchy
graph TB
A[Python Data Types] --> B[Numeric]
A --> C[Sequence]
A --> D[Mapping]
A --> E[Set]
A --> F[Boolean]
B --> B1[int - Integers]
B --> B2[float - Decimals]
B --> B3[complex - Complex Numbers]
C --> C1[str - Strings Immutable]
C --> C2[list - Lists Mutable]
C --> C3[tuple - Tuples Immutable]
D --> D1[dict - Key-Value Pairs]
E --> E1[set - Unique Unordered]
E --> E2[frozenset - Immutable Set]
F --> F1[True/False]
style A fill:#2196F3
style B fill:#4CAF50
style C fill:#FF9800
style D fill:#9C27B0
style E fill:#F44336
style F fill:#00BCD4
Key Points:
- Numeric Types: int (unlimited precision), float (64-bit), complex (a+bj)
- Sequences: Ordered collections with indexing (str, list, tuple)
- Mutable vs Immutable: Lists mutable, strings and tuples immutable
- Dictionaries: Fast key-value lookups using hash tables
- Sets: Unordered collections with unique elements, fast membership testing
Variable Assignment Flow
sequenceDiagram
participant Code
participant Interpreter
participant Memory
participant Object
Code->>Interpreter: x = 42
Interpreter->>Memory: Allocate space
Memory->>Object: Create int object
Object->>Memory: Store value 42
Memory->>Interpreter: Return reference
Interpreter->>Code: Bind x to reference
Note over Code,Object: Everything is an Object
Key Points:
- Dynamic Typing: No type declaration needed, type inferred from value
- Object References: Variables store references to objects, not values directly
- Multiple Assignment: x = y = z = 10 assigns same object to all variables
- Type Checking: Use type() to check type, isinstance() for validation
Collection Operations Comparison
graph LR
A[Collections] --> B[List]
A --> C[Tuple]
A --> D[Set]
A --> E[Dict]
B --> B1[Mutable]
B --> B2[Ordered]
B --> B3[Indexed]
C --> C1[Immutable]
C --> C2[Ordered]
C --> C3[Indexed]
D --> D1[Mutable]
D --> D2[Unordered]
D --> D3[Unique]
E --> E1[Mutable]
E --> E2[Key-Value]
E --> E3[Fast Lookup]
style A fill:#2196F3
style B fill:#4CAF50
style C fill:#FF9800
style D fill:#9C27B0
style E fill:#F44336
Key Points:
- Lists: Use for ordered, changeable collections with duplicates allowed
- Tuples: Use for immutable data, function returns, dictionary keys
- Sets: Use for unique elements, fast membership testing, set operations
- Dictionaries: Use for key-value mappings, fast lookups by key
List Comprehension Flow
flowchart LR
A[Expression] --> B[for item in iterable]
B --> C{Condition?}
C -->|True| D[Include in Result]
C -->|False| E[Skip]
D --> F[New List]
E --> B
style A fill:#2196F3
style B fill:#4CAF50
style C fill:#FF9800
style F fill:#9C27B0
Key Points:
- Concise Syntax: Create lists in single line instead of loops
- Performance: Faster than traditional for loops for list creation
- Readability: More Pythonic and easier to understand
- Filtering: Add conditions to filter elements during creation
Function Execution Model
sequenceDiagram
participant Caller
participant Function
participant LocalScope
participant Return
Caller->>Function: Call with arguments
Function->>LocalScope: Create local namespace
LocalScope->>LocalScope: Execute body
LocalScope->>Return: Compute result
Return->>Caller: Return value
LocalScope->>LocalScope: Destroy namespace
Note over LocalScope: Local variables destroyed
Key Points:
- Local Scope: Function parameters and variables exist only during execution
- Return Values: Functions can return single or multiple values (tuple)
- Default Arguments: Provide default values for optional parameters
- Variable Arguments: *args for positional, **kwargs for keyword arguments
Decorator Pattern
flowchart TB
A[Original Function] --> B[Decorator]
B --> C[Wrapper Function]
C --> D[Enhanced Behavior]
E[Before Execution] --> F[Call Original]
F --> G[After Execution]
D --> E
style A fill:#2196F3
style B fill:#4CAF50
style C fill:#FF9800
style D fill:#9C27B0
Key Points:
- Function Wrapper: Decorators wrap functions to add functionality
- @ Syntax: Syntactic sugar for applying decorators
- Common Uses: Logging, timing, authentication, caching
- Preserves Function: Original function behavior maintained with additions
Class and Object Architecture
graph TB
A[Class Definition] --> B[Attributes]
A --> C[Methods]
A --> D[Constructor __init__]
B --> B1[Instance Variables]
B --> B2[Class Variables]
C --> C1[Instance Methods]
C --> C2[Class Methods @classmethod]
C --> C3[Static Methods @staticmethod]
E[Object Creation] --> F[Memory Allocation]
F --> G[__init__ Called]
G --> H[Instance Ready]
style A fill:#2196F3
style B fill:#4CAF50
style C fill:#FF9800
style E fill:#9C27B0
Key Points:
- Class: Blueprint for creating objects with shared behavior
- Instance Variables: Unique to each object, defined in init
- Methods: Functions defined inside class, first parameter is self
- Inheritance: Classes can inherit from parent classes using class Child(Parent)
Exception Handling Flow
flowchart TB
A[Try Block] --> B{Exception?}
B -->|No| C[Execute Normally]
B -->|Yes| D[Catch Exception]
D --> E{Matching except?}
E -->|Yes| F[Handle Exception]
E -->|No| G[Propagate Up]
F --> H[Finally Block]
C --> H
H --> I[Cleanup Code]
style A fill:#2196F3
style B fill:#4CAF50
style D fill:#FF9800
style F fill:#9C27B0
style H fill:#F44336
Key Points:
- try-except: Catch and handle exceptions gracefully
- Multiple except: Handle different exception types separately
- finally: Always executes for cleanup (close files, connections)
- raise: Manually raise exceptions with custom messages
File Operations Workflow
sequenceDiagram
participant Code
participant FileSystem
participant File
participant Buffer
Code->>FileSystem: open(filename, mode)
FileSystem->>File: Locate file
File->>Buffer: Load to buffer
Buffer->>Code: Return file object
Code->>Buffer: read/write operations
Buffer->>File: Flush changes
Code->>FileSystem: close()
FileSystem->>File: Release resources
Key Points:
- Context Manager: Use 'with' statement for automatic file closing
- Modes: 'r' read, 'w' write, 'a' append, 'b' binary, '+' read/write
- Methods: read(), readline(), readlines(), write(), writelines()
- Always Close: Ensure files closed to prevent resource leaks
Code Examples
Basic Operations
# Variables and types
name = "Python"
version = 3.11
is_popular = True
# Collections
fruits = ["apple", "banana", "cherry"]
person = {"name": "Venu", "age": 30}
# List comprehension
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
Functions
# Basic function
def greet(name="Guest"):
return f"Hello, {name}!"
# Lambda function
add = lambda x, y: x + y
# Decorator
def timer(func):
def wrapper(*args):
# Add timing logic
return func(*args)
return wrapper
OOP
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hi, I'm {self.name}"
# Inheritance
class Employee(Person):
def __init__(self, name, age, job):
super().__init__(name, age)
self.job = job