Python Rules - From Basic to Advanced (One-Liners)
1. Basic Rules and Syntax
- Python uses indentation (not braces) to define code blocks.
- Statements end with a newline, not a semicolon (though semicolons are allowed).
- Comments start with # and run until the end of the line.
- print() is used to output to the console.
- Variable names are case-sensitive.
- Keywords like if, for, class, etc., can't be used as identifiers.
- Python files use .py extension and execute top to bottom.
2. Data Types and Variables
- Python has dynamic typing - no need to declare variable types.
- All values are objects in Python.
- Integers, floats, strings, and booleans are primitive types.
- type() returns the type of an object.
- id() returns the unique identity of an object.
- None represents the absence of a value.
- Strings are immutable.
- Lists are mutable and ordered.
- Tuples are immutable and ordered.
- Sets are unordered collections of unique elements.
- Dictionaries are key-value pairs (insertion ordered in Python 3.7+).
- Use is for identity, == for equality.
- int(True) is 1, and bool(0) is False.
3. Operators and Expressions
- +, -, *, /, //, %, ** are arithmetic operators.
- ==, !=, <, >, <=, >= are comparison operators.
- and, or, not are logical operators.
- in and not in test membership.
- is and is not test identity.
- Assignment is =, not ==.
- Augmented assignments like +=, -=, *= modify variables in-place.
4. Control Flow
- if, elif, and else control conditional execution.
- Indentation determines block scope.
- All conditions in if are truth-tested.
- for loops iterate over any iterable.
- while loops repeat as long as the condition is true.
- break exits the nearest loop.
- continue skips to the next iteration.
- pass is a no-operation statement.
- else on a loop runs only if no break occurred.
5. Functions
- Functions are defined using def keyword.
- return ends the function and optionally returns a value.
- All arguments are passed by assignment (object reference).
- Default arguments are evaluated once.
- *args collects extra positional arguments.
- **kwargs collects extra keyword arguments.
- Functions are first-class objects (can be passed/stored).
- lambda defines anonymous functions.
- docstrings are triple-quoted strings placed at the start of a function.
6. Scope and Namespace
- Variables have local, enclosing, global, or built-in scope (LEGB rule).
- global declares a variable in the global scope.
- nonlocal declares a variable in the nearest enclosing non-global scope.
- Name resolution follows LEGB hierarchy.
7. Classes and OOP
- Classes are defined with class keyword.
- __init__() is the constructor.
- self refers to the instance itself.
- Instance variables are tied to self.
- Class variables are shared across instances.
- Methods must take self as the first parameter.
- @classmethod takes cls instead of self.
- @staticmethod has no automatic first argument.
- Inheritance uses parentheses: class Child(Parent):
- super() is used to call the parent class.
- Double underscores (dunder methods) like __str__, __len__ define object behavior.
- Operator overloading is done via magic methods like __add__, __eq__.
8. Modules and Imports
- Use import module to bring in a module.
- from module import name imports specific members.
- as renames modules or members during import.
- __name__ == '__main__' lets code run only when executed directly.
- The sys module gives access to interpreter arguments and behavior.
9. File Handling
- open() is used to read/write files.
- Always use with open(...) to handle files safely.
- read(), readline(), and readlines() fetch file contents.
- write() and writelines() output to files.
- Files opened with w overwrite, a appends, x creates.
10. Exception Handling
- Use try-except to catch exceptions.
- Use else to run code if no exception occurred.
- Use finally to always execute cleanup code.
- Catch specific exceptions to avoid masking bugs.
- Raise errors using raise Exception('message').
11. Advanced Features
- yield makes a function a generator.
- Generators are iterators that maintain state.
- next() retrieves the next value from an iterator.
- @decorator modifies a function-s behavior.
- Decorators are functions that return functions.
- List comprehensions are concise ways to build lists.
- Dictionary and set comprehensions also exist.
- zip() combines iterables element-wise.
- enumerate() gives index and value during iteration.
- map(), filter(), reduce() apply functional programming style.
12. Miscellaneous and Best Practices
- Use isinstance() instead of type() for type checking.
- Avoid mutable default arguments.
- Use __repr__() for debug representation.
- Use __str__() for user-friendly representation.
- Follow PEP8 style guidelines.
- Avoid wildcard imports (from module import *).
- Use virtual environments to isolate projects.
- Prefer f-strings for string formatting (Python 3.6+).
- Use set() for removing duplicates from a list.
- Python uses garbage collection and reference counting.