Skip to main content
< All Topics

Python

By reading these notes, you will gain knowledge tailored to your role, whether you are a beginner or practitioner focusing on Python Programming foundations.

Note – This page contains a complete summary of the topics. To learn more about each topic, click on the (Expand)Topic-HeadingImage, or ‘Click Here’ hyperlink.

Before reading this document, please read Programming Basics & Foundations

You can practice Python online https://pythontutor.com/python-compiler.html

Python is high level, interpreted, object oriented, high-level programming language with dynamic semantics. It is used everywhere: Scripting, Application development, websites to Artificial Intelligence and Data Science.

Python Foundation

TopicKey ConceptsNotesOfficial Documentation Link
Python HistoryVersions of Python
Types of Python
The Origins: Started as a 1989 Christmas hobby project by Guido van Rossum to create a language with ABC’s clean syntax and C’s power.
The Name: Named after the British comedy show Monty Python’s Flying Circus, not the snake.
Python 1.0: The 1994 milestone that introduced functional tools like lambda, map, and filter.
Python 2.0: The 2000 release that added list comprehensions and shifted to a community-driven open-source model.
Python 3.0: A major 2008 overhaul that fixed deep design flaws but was famous for not being backward compatible with Python 2.
The “2 vs 3” Era: A 12-year transition period where both versions coexisted until Python 2 officially reached “End of Life” in 2020.
Modern Era: Transitioned from a “Benevolent Dictator” (Guido) to a Steering Council, focusing on annual speed and security boosts.
CPython: The standard, most popular version of Python written in C it’s what you likely have installed right now.
PyPy: A high-speed version that uses a “Just-In-Time” compiler to run pure Python code much faster than the standard version.
Jython/IronPython: Specialized versions that allow Python to run directly inside Java (JVM) or Windows (.NET) environments.
MicroPython: A tiny, “shrunken” version of Python designed specifically to run on small hardware like Arduinos and sensors.
History and License
Python BasicsVariables,
Memory,
Data Types
Variables: Think of these as “name tags” or labels attached to data stored in memory, rather than boxes that hold the data themselves.
Naming Rules: Variable names must start with a letter or underscore, cannot use special symbols (except _), and are strictly case-sensitive.
Naming Conventions: Professional Python code uses snake_case for variables, PascalCase for Classes, and UPPER_CASE for constants (PEP 8).
Assigning Values: Python uses “Dynamic Typing,” meaning you can reassign a variable from a number to a string without declaring its type first.
Input Handling: The input() function always captures data as a String, so you must manually convert it if you need a number or boolean.
Outputting Variables: F-strings (f"Hello {name}") are the modern industry standard for printing because they are fast, readable, and clean.
Global vs. Local: Local variables live only inside a function, while Global variables are accessible to the whole script but should be used sparingly.
Memory Management: Python uses “Reference Counting” to track data and a “Garbage Collector” to automatically delete data when no tags point to it.
Data Types: Python categorizes data into types like int, str, and list, which determine how the computer handles and stores that specific information.
Mutable-vs.-Immutable: “Mutable” objects (like lists) can be changed in place, while “Immutable” objects (like strings) create a whole new object if modified.
Type Casting: The manual process of forcing data from one “currency” to another, such as converting the string "8080" into a mathematical integer.
Dynamic Typing: A flexible system where the “type” is attached to the value itself, not the variable name, allowing for rapid and adaptive coding.
Virtual Environments (venv): Isolated “digital kitchens” that keep each project’s libraries separate to prevent version conflicts and system crashes.
Error Handling: Using try and except blocks allows your script to catch “Exceptions” (crashes) and handle them gracefully instead of stopping.
Comments & Docstrings: Use # for quick “why” notes and """Triple Quotes""" for professional documentation that explains what your functions do.
Python Tutorial
Data TypesNumeric Data TypesIntegers – whole numbers that grow automatically to fit any size
float – Numbers with decimals used for measuring things, though they are “approximations”
complex – Numbers with a real part and an imaginary j part, used like 2D coordinates for advanced engineering and physics.
Booleans – Simple True or False switches that Python actually treats as the numbers 1 and 0 under the hood.
NoneType – A unique placeholder that represents “nothing” or “no value,” used to signal that data is missing or a task failed.
Type-Casting – The process of manually changing data from one type to another, like turning the string "8080" into the integer 8080.
Mathematical-Functions – Built-in toolboxes (like the math module) that handle complex calculations like square roots, rounding, and trigonometry instantly.
OperatorsArithmetic, Logical, Comparison// is floor division (drops decimal).
** is power ($2^3$).
is compares memory identity, == compares value.
Code: if x > 5 and y < 10:
Operators
Control FlowConditionals, Loops• Indentation is mandatory.
range(start, stop, step).
break exits loop; continue skips to next iteration.
Code: for i in range(5): print(i)
Control Flow
Strings (Advanced)Slicing, f-strings, Methods• Strings are immutable.
Slicing: text[start:stop:step]text[::-1] reverses string.
f-string: f"Hello {name}" is faster/cleaner.
strip(), split(), join().
String Methods
Data Structures 1Lists & TuplesList: Mutable []. methods: append, pop, sort.
Tuple: Immutable (). Faster, keys for dicts.
Code: my_list = [1, 2, 3]; my_tuple = (1, 2)
Data Structures
Data Structures 2Dictionaries & SetsDict: Key-Value {k:v}. O(1) lookup speed.
Set: Unique items {1, 2}. Great for removing duplicates.
Code: data.get("key", "default_val") avoids errors.
Dictionaries

Functional and Modular Programming

TopicKey ConceptsNotesOfficial Documentation Link
FunctionsScope, Return, Argsdef keyword.
*args: Tuple of unknown args.
**kwargs: Dict of unknown keyword args.
Docstrings: """Description""" for documentation.
Code: def add(*nums): return sum(nums)
Defining Functions
Functional ToolsLambda, Map, FilterLambda: One-line anonymous function.
Map: Apply function to all items.
Filter: Select items based on condition.
Code: squares = list(map(lambda x: x**2, numbers))
Functional HOWTO
ComprehensionsList/Dict Comprehension• Pythonic way to create lists.
• More readable than for loops for simple logic.
Code: [x for x in range(10) if x % 2 == 0]
Comprehensions
Modules & PackagesImports, __name__Module: A .py file.
Package: A folder with __init__.py.
if __name__ == "__main__": ensures code runs only when executed directly, not when imported.
Modules
Virtual EnvironmentsIsolation, Dependency MgmtCrucial for every project.
• Prevents library version conflicts.
Cmds: python -m venv venv, source venv/bin/activate (Linux), pip install -r requirements.txt.
venv

Object Oriented Programming Python (OOP)

TopicKey ConceptsNotesOfficial Documentation Link
Classes & ObjectsBasics, selfClass: Blueprint. Object: Instance.
self: Reference to the current instance.
__init__: Constructor method.
Code: class Dog: def __init__(self, name): self.name = name
Classes
InheritanceParent/Child, super()• Don’t repeat code. Child inherits Parent’s methods.
super().__init__() calls parent constructor.
Polymorphism: Different classes, same method name.
Inheritance
Magic MethodsDunder Methods• Methods starting/ending with __.
__str__: User-friendly string representation.
__repr__: Developer debugging representation.
__len__, __add__.
Data Model
Advanced OOPDecorators, Properties@property: Access methods like attributes (Getters).
@staticmethod: Function inside class not using self.
@classmethod: Uses cls (affects class state).
Built-in Functions

Advanced Concepts

TopicKey ConceptsNotesOfficial Documentation Link
Error HandlingTry, Except, Finally• Never use bare except:. Catch specific errors.
finally: Runs cleanup code (closing files) always.
raise: Trigger custom errors.
Code: try: x/0 except ZeroDivisionError: print("Error")
Errors
File HandlingRead/Write, Context MgrAlways use with open(...) to auto-close files.
• Modes: 'r' (read), 'w' (write/overwrite), 'a' (append).
• Handling CSV and JSON is vital for data exchange.
Input/Output
Iterators & Generatorsyield, Memory EfficiencyGenerator: Returns an iterator, pauses execution with yield.
• Extremely memory efficient for large datasets.
Code: def gen(): yield 1; yield 2
Generators
DecoratorsWrappers, @syntax• Functions that modify other functions without changing their code.
• Used for logging, authentication, timing.
Code: @login_required before a function definition.
Decorators
ConcurrencyThreading vs AsyncIOThreading: I/O bound tasks (network calls).
Multiprocessing: CPU bound tasks (calculations).
AsyncIO: Modern async/await for high-performance I/O.
Code: async def main(): await func()
AsyncIO

Libraries and Applications

TopicKey ConceptsNotesOfficial Documentation Link
Standard Libraryos, sys, datetimeos: File paths, env variables (os.getenv).
sys: System arguments (sys.argv).
datetime: Date manipulation (datetime.now()).
Std Lib
RegexPattern Matchingre module.
• Find patterns (emails, phone numbers) in text.
\d (digit), \w (word char), + (one or more).
Regex
Web DevelopmentFlask/FastAPIFlask: Micro-framework, easy for beginners.
Django: Full-stack, “batteries included”.
FastAPI: Modern, fast, for building APIs.
Flask
Data SciencePandas, NumPyNumPy: Math & Matrix calculations.
Pandas: DataFrames (Excel for Python).
Matplotlib: Graphing & plotting.
Pandas

Professional Skills

TopicKey ConceptsNotesOfficial Documentation Link
Logginglogging vs printNEW TOPIC
print is for console; logging is for production.
• Levels: DEBUG, INFO, WARNING, ERROR, CRITICAL.
• Can save logs to file with timestamps.
Logging HOWTO
API Interactionrequests, JSONNEW TOPIC
• Interacting with REST APIs.
r = requests.get(url).
data = r.json(). handling status codes (200, 404).
Requests Lib
Database BasicsSQL, SQLiteNEW TOPIC
• Storing data permanently.
• Python has built-in sqlite3.
• Basic syntax: SELECT, INSERT, CURSOR.
SQLite3
TestingUnit Tests, TDDunittest (built-in) or pytest (popular external).
• Writing assertions to verify code works.
assert sum([1,2]) == 3.
Unittest
Security Best PracticesSafety, ValidationNEW TOPIC (For DevSecOps)
• Never use eval() or exec() on user input.
• Use secrets module instead of random for passwords.
• SQL Injection prevention (use parameterized queries).
Security Guide
Code QualityPEP8, LintingNEW TOPIC
• Style guide for Python Code.
• Tools: flake8, black (formatter), mypy (type checking).
Type Hints: def add(x: int) -> int:
PEP 8

Contents
Scroll to Top