Introduction to Python
Python Overview
Python is a high-level, interpreted, general-purpose programming language that emphasizes code readability and simplicity. It was created by Guido van Rossum and first released in 1991. The name "Python" comes from the British comedy series "Monty Python's Flying Circus."
Key Features
- High-Level Language: Abstracts away low-level details
- Interpreted: Code executed line by line
- Dynamically Typed: No explicit type declarations
- Garbage Collected: Automatic memory management
- Multi-Paradigm: Supports procedural, OOP, and functional programming
- Extensive Standard Library: Rich collection of modules
- Cross-Platform: Runs on Windows, macOS, Linux
- Indentation-Based Syntax: Uses whitespace for code blocks
Why Learn Python?
- Beginner-friendly with gentle learning curve
- Versatile for web development, data science, AI, automation
- High demand in job market
- Large supportive community
- Rapid development capabilities
- Extensive libraries and frameworks
Installation and Setup
- Download from python.org
- Run installer, check "Add Python to PATH"
- Verify with
python --version - Use IDEs like VS Code, PyCharm, or IDLE
- Install packages with
pip
Python Philosophy
- Beautiful is better than ugly
- Simple is better than complex
- Readability counts
- Explicit is better than implicit
- There should be one obvious way to do it
Python Basics
Variables and Data Types
Variables are created by assignment (=). Python has dynamic typing.
- int: Whole numbers (42, -10)
- float: Decimal numbers (3.14, -2.5)
- str: Text strings ("hello", 'world')
- bool: Boolean values (True, False)
Type conversion: int(), float(), str(), bool()
Operators
Arithmetic: +, -, *, /, //, %, **
Comparison: ==, !=, <, >, <=, >=
Logical: and, or, not
Assignment: =, +=, -=, *=, /=, //=, %=, **=
Control Structures
Conditional: if, elif, else with indentation
Loops: for (iterates over sequences), while (condition-based)
Loop Control: break (exit), continue (skip iteration)
range(): Generates number sequences
Functions
- Defined with
defkeyword - Can take parameters and return values
- Parameters vs Arguments distinction
- Default parameters and keyword arguments
- Variable scope: local vs global
- return statement sends values back
Variable Naming Rules
- Start with letter or underscore
- Contain letters, digits, underscores
- Case-sensitive
- No reserved keywords
- Use descriptive names
Python Intermediate
Lists
Mutable ordered sequences. Created with [].
- Access: list[index], negative indexing
- Slicing: list[start:end:step]
- Methods: append(), insert(), remove(), pop(), sort(), reverse()
- Operations: +, *, in, len()
- List comprehensions: [expr for item in iterable if condition]
Tuples
Immutable ordered sequences. Created with ().
- Cannot modify after creation
- Faster than lists for read-only
- Can be used as dictionary keys
- Methods: count(), index()
- Unpacking: x, y = tuple
Dictionaries
Mutable key-value pairs. Created with {}.
- Keys must be immutable (strings, numbers, tuples)
- Access: dict[key] or dict.get(key, default)
- Methods: keys(), values(), items(), pop(), update()
- Dict comprehensions: {key_expr: value_expr for item in iterable}
- Fast lookups: O(1) average time complexity
File Handling
Use open() function with modes: 'r', 'w', 'a', 'x', 'b', 't', '+'
- Methods: read(), readline(), readlines(), write(), writelines()
- File pointer: seek(), tell()
- Best practice: with statement for automatic closing
- Error handling: try-except for FileNotFoundError, IOError
- Encoding: specify encoding='utf-8' for text files
Modules and Packages
- Import: import module, from module import function, import as alias
- Standard library: math, random, datetime, os, sys, json, re
- Custom modules: save as .py files
- Packages: directories with __init__.py
- if __name__ == "__main__": for executable modules
Python Advanced
Object-Oriented Programming
- Class: Blueprint for objects
- Object: Instance of a class
- Constructor: __init__ method
- self: Reference to current instance
- Inheritance: Child classes inherit from parent
- Polymorphism: Same method, different behavior
- Encapsulation: Hide internal details
- Special Methods: __str__, __repr__, __len__, __add__, etc.
Exception Handling
- try-except-else-finally blocks
- Built-in exceptions: ValueError, TypeError, KeyError, IndexError, ZeroDivisionError, FileNotFoundError
- Custom exceptions: inherit from Exception
- Raising exceptions: raise Exception(message)
- Exception hierarchy: BaseException → Exception → specific exceptions
Algorithms and Complexity
- Sorting: Bubble (O(n²)), Selection (O(n²)), Insertion (O(n²)), Merge (O(n log n)), Quick (O(n log n))
- Searching: Linear (O(n)), Binary (O(log n))
- Big O Notation: Measures algorithm efficiency
- Data Structures: Stack, Queue, Linked List, Tree, Graph, Hash Table
Data Analysis Libraries
NumPy:
- N-dimensional arrays (ndarray)
- Vectorized operations
- Broadcasting
- Mathematical functions
- Linear algebra operations
- Random number generation
Pandas:
- Series (1D) and DataFrame (2D)
- Data manipulation and cleaning
- Grouping and aggregation
- Merging and joining
- Time series handling
- Import/export: CSV, Excel, SQL
Matplotlib:
- Line plots, bar charts, histograms
- Scatter plots, pie charts
- Subplots and multiple figures
- Styling and customization
- 3D plotting capabilities