Python logoPython BEGINNER

Python Fundamentals

Complete guide to Python programming basics and core concepts

10 min read
pythonprogrammingbasicssyntaxdata-typescontrol-flowfunctionsoop

Setup & Basics

Installation & Running Python

Setting up Python and running programs

python
💡 Use python3 explicitly on systems with both Python 2 and 3
⚡ Virtual environments isolate project dependencies
📌 Always use requirements.txt for dependency management
🔍 Python is case-sensitive and uses indentation for blocks

Variables & Data Types

Python variable declaration and basic data types

python
💡 Python uses dynamic typing - variables can change types
⚡ Use type hints for better code documentation
📌 None is Python's null value
🔍 Variables are references to objects in memory

Strings & Formatting

String Operations

String manipulation and methods

python
💡 Strings are immutable - operations return new strings
⚡ Use slicing for substring extraction
📌 Negative indices count from the end
🔍 String methods don't modify the original string

String Formatting

Modern string formatting techniques

python
💡 f-strings are fastest and most readable
⚡ Use Template for untrusted user input
📌 Format specifiers: .2f (float), :04d (padding), :, (thousands)
🔍 f-strings allow any Python expression inside {}

Data Structures

Lists

Ordered, mutable sequences

python
💡 Lists are mutable and ordered
⚡ List comprehensions are faster than loops
📌 Use copy() for shallow copies, deepcopy() for nested
🔍 Negative indices and slicing work like strings

Tuples

Ordered, immutable sequences

python
💡 Tuples are immutable - use for fixed collections
⚡ Tuple unpacking simplifies multiple assignments
📌 Single element tuple needs trailing comma: (1,)
🔍 Named tuples provide readable attribute access

Dictionaries

Key-value pairs (hash maps)

python
💡 Dictionaries are unordered until Python 3.7+
⚡ Use get() to avoid KeyError exceptions
📌 Dictionary keys must be immutable (str, int, tuple)
🔍 defaultdict and Counter simplify common patterns

Sets

Unordered collections of unique elements

python
💡 Sets automatically remove duplicates
⚡ Membership testing is O(1) - very fast
📌 Sets are unordered - no indexing
🔍 frozenset is immutable and can be a dict key

Control Flow

Conditionals

if, elif, else statements

python
💡 Python uses indentation for blocks, not braces
⚡ Ternary operator for simple if-else expressions
📌 Empty collections evaluate to False
🔍 Use "is" for None checks: if x is None

Loops

for and while loops

python
💡 for-else runs if loop completes without break
⚡ enumerate() adds index to iterations
📌 zip() stops at shortest sequence
🔍 range(start, stop, step) for custom ranges

Functions

Function Basics

Defining and calling functions

python
💡 *args for variable positional, **kwargs for keyword args
⚡ Use type hints for better code clarity
📌 Docstrings document function purpose and usage
🔍 * forces remaining arguments to be keyword-only

Lambda & Higher-Order Functions

Anonymous functions and functional programming

python
💡 Lambda for simple, one-line functions
⚡ List comprehensions often clearer than map/filter
📌 Decorators modify function behavior
🔍 Functions are first-class objects in Python

Classes & OOP

Class Basics

Object-oriented programming fundamentals

python
💡 __init__ is the constructor method
⚡ @property creates computed attributes
📌 @classmethod for alternative constructors
🔍 self refers to the instance, cls to the class

Inheritance & Polymorphism

Class inheritance and method overriding

python
💡 super() calls parent class methods
⚡ ABC enforces implementation of abstract methods
📌 Multiple inheritance creates diamond problem
🔍 MRO determines method resolution order

File I/O & Exceptions

File Operations

Reading and writing files

python
💡 Always use "with" for automatic file closing
⚡ pathlib provides modern path handling
📌 JSON for structured data, CSV for tabular
🔍 Binary mode for non-text files

Exception Handling

Handling errors gracefully

python
💡 Catch specific exceptions, not bare except
⚡ finally always runs, even with return
📌 Custom exceptions inherit from Exception
🔍 Use assert for debugging, not production

Modules & Packages

Importing & Creating Modules

Module system and package management

python
💡 Use virtual environments for project isolation
⚡ __init__.py makes a folder a Python package
📌 Avoid "from module import *" for clarity
🔍 __all__ controls what's exported with import *

Advanced Features

Generators & Iterators

Memory-efficient iteration

python
💡 Generators produce values lazily, saving memory
⚡ yield pauses function and returns value
📌 Generator expressions like list comp but with ()
🔍 Generators are one-time use, then exhausted

Decorators

Function and class decorators

python
💡 Decorators modify function behavior without changing code
⚡ @wraps preserves original function metadata
📌 Stack decorators - applied bottom to top
🔍 @lru_cache caches function results

Context Managers

Resource management with "with" statement

python
💡 Context managers ensure cleanup with __exit__
⚡ @contextmanager simplifies creation
📌 suppress() ignores specific exceptions
🔍 ExitStack manages dynamic number of contexts

Best Practices & Tips

Pythonic Code

Writing idiomatic Python

python
💡 Follow PEP 8 style guide
⚡ Use built-in functions and comprehensions
📌 EAFP over LBYL for Python style
🔍 Zen of Python: import this

Performance Tips

Optimizing Python code

python
💡 Profile first, optimize bottlenecks only
⚡ Built-in functions are implemented in C
📌 Use appropriate data structures for the task
🔍 Consider NumPy/Pandas for numerical work