Python Programming Fundamentals
Comprehensive Study Notes for Beginners
1. Getting Started
Python is a high-level, interpreted, general-purpose programming language known for its readable
syntax. It is dynamically typed (variable types are determined at runtime) and supports multiple
paradigms, including procedural, object-oriented, and functional programming.
• Python code is executed by an interpreter, not compiled to machine code ahead of time.
• Indentation is syntactically significant in Python; it defines code blocks instead of braces.
• Python emphasizes readability, following the philosophy captured in "The Zen of Python."
2. Variables and Data Types
Variables in Python are created by assignment and do not require explicit type declarations. The
interpreter infers the type based on the assigned value.
Type Example Description
int x=5 Whole numbers, arbitrary precision
float x = 3.14 Decimal numbers
str x = "hello" Text, immutable sequence of characters
bool x = True Boolean, True or False
list x = [1, 2, 3] Ordered, mutable collection
tuple x = (1, 2, 3) Ordered, immutable collection
dict x = {"a": 1} Key-value pairs
set x = {1, 2, 3} Unordered collection of unique items
3. Control Flow
3.1 Conditionals
Python uses if, elif, and else keywords for conditional branching. Comparisons return boolean values,
and logical operators (and, or, not) combine conditions.
3.2 Loops
• for loops iterate over a sequence (list, string, range, etc.) - the most common loop type in Python.
• while loops repeat as long as a condition remains True.
• break exits a loop early; continue skips to the next iteration; else on a loop runs if the loop
completes without a break.
4. Functions
Functions are defined with the def keyword and can accept positional arguments, keyword
arguments, default values, and variable-length arguments (*args and **kwargs). Functions are
first-class objects in Python, meaning they can be assigned to variables, passed as arguments, and
returned from other functions.
• Positional arguments are matched to parameters by order.
• Keyword arguments are matched by explicit parameter name, allowing any order.
• Default parameter values are used when the caller omits that argument.
• *args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments
into a dictionary.
• Lambda functions are small anonymous functions defined with the lambda keyword, useful for
short, throwaway operations.
5. Data Structures in Depth
5.1 Lists
Lists are ordered, mutable, and allow duplicate elements. Common operations include append(),
remove(), sort(), and slicing with the colon operator. List comprehensions provide a concise way to
build lists, e.g. squares = [x**2 for x in range(10)].
5.2 Dictionaries
Dictionaries store key-value pairs and provide fast lookups by key. Since Python 3.7, dictionaries
maintain insertion order. Common methods include .get(), .keys(), .values(), and .items().
5.3 Sets
Sets store unique, unordered elements and support mathematical operations like union, intersection,
and difference, useful for membership testing and deduplication.
6. Object-Oriented Programming
Python supports classes and objects for structuring code around data and behavior. A class is
defined with the class keyword, and objects are instances of that class.
• __init__ is the constructor method, called automatically when a new object is created.
• self refers to the instance calling the method and must be the first parameter of instance methods.
• Inheritance allows a class to derive attributes and methods from a parent class, supporting code
reuse.
• Encapsulation is conventionally indicated with a leading underscore for "protected" attributes and
double underscore for "private" ones, though Python does not strictly enforce access control.
• Polymorphism allows different classes to implement the same method name in different ways.
• Dunder (double underscore) methods like __str__, __len__, and __eq__ let custom objects
integrate with built-in Python behavior.
7. Error Handling
Python handles runtime errors using try, except, else, and finally blocks. Code that might raise an
exception goes in the try block; the except block catches and handles specific exception types; else
runs if no exception occurred; finally always runs, useful for cleanup like closing files.
Exception Common Cause
ValueError Invalid value for an operation, e.g. int("abc")
TypeError Operation on incompatible types
KeyError Dictionary key not found
IndexError List index out of range
FileNotFoundError Attempting to open a nonexistent file
ZeroDivisionError Division by zero
8. Modules and Packages
A module is a single Python file; a package is a directory of modules containing an __init__.py file.
The import statement brings external code into scope. Python's standard library includes modules like
os, sys, math, datetime, and json, while pip installs third-party packages from the Python Package
Index (PyPI).
9. File Handling
Files are typically opened using the "with" statement, which automatically closes the file when the
block finishes, even if an error occurs. Common modes include "r" (read), "w" (write, overwrites), "a"
(append), and "rb"/"wb" for binary data.
10. Common Built-in Functions
Function Purpose
len() Returns the number of items in a sequence
range() Generates a sequence of numbers
enumerate() Pairs items with their index while iterating
zip() Combines multiple iterables element-wise
map() Applies a function to every item in an iterable
filter() Filters items based on a condition
sorted() Returns a new sorted list
isinstance() Checks an object's type
11. Key Terms Glossary
• Interpreter: a program that executes code line by line rather than compiling it beforehand.
• Mutable vs Immutable: mutable objects (lists, dicts) can be changed after creation; immutable
objects (strings, tuples) cannot.
• Iterable: any object capable of returning its members one at a time, usable in a for loop.
• Comprehension: concise syntax for building lists, dicts, or sets from an iterable.
• Virtual environment: an isolated Python environment that keeps project dependencies separate.
12. Quick Review Summary
Python is a readable, dynamically typed language supporting multiple paradigms. Core building
blocks include variables, control flow (if/for/while), and functions. Its key data structures are lists,
tuples, dictionaries, and sets, each suited to different needs. Object-oriented programming in Python
centers on classes, inheritance, and the self parameter. Robust programs use try/except blocks for
error handling and the "with" statement for safe file handling. The standard library and PyPI
ecosystem extend Python's functionality far beyond its built-in features.