Basic Concepts in Python
**Basic Concepts in Python**
1. **Syntax and Structure**
- **Indentation**: Python uses indentation (whitespace) to define code blocks (e.g., loops, functions) instead of braces.
- **Comments**: Start with `#`. Multi-line comments use triple quotes (`'''` or `"""`).
- **Statements**: End of line terminates a statement; use `\` for line continuation or parentheses for multi-line statements.
2. **Variables and Data Types**
- **Variables**: No explicit declaration; dynamically typed (e.g., `x = 5`, then `x = "hello"`).
- **Basic Types**:
- `int` (integer), `float` (decimal), `str` (text), `bool` (`True`/`False`), `NoneType` (`None`).
- **Collections**:
- **List**: Mutable, ordered (`[1, 2, 3]`).
- **Tuple**: Immutable, ordered (`(1, 2, 3)`).
- **Dictionary**: Key-value pairs (`{"name": "Alice", "age": 30}`).
- **Set**: Unordered, unique elements (`{1, 2, 3}`).
3. **Operators**
- **Arithmetic**: `+`, `-`, `*`, `/`, `//` (floor division), `%` (modulo), `**` (exponent).
- **Comparison**: `==`, `!=`, `>`, `<`, `>=`, `<=`.
- **Logical**: `and`, `or`, `not`.
- **Identity**: `is`, `is not` (check memory location).
- **Membership**: `in`, `not in` (check presence in a collection).
4. **Control Flow**
- **Conditionals**:
```python
if condition:
# code
elif condition:
# code
else:
# code
```
- **Loops**:
- `for`: Iterate over sequences (e.g., `for item in list:`).
- `while`: Repeat while condition is `True`.
- **Loop Control**: `break` (exit loop), `continue` (skip iteration), `pass` (placeholder).
5. **Functions**
- **Definition**:
```python
def func_name(param1, param2=default_value):
# code
return result
```
- **Arguments**:
- Positional, keyword, default, variable-length (`*args`, `**kwargs`).
- **Lambda**: Anonymous functions (e.g., `lambda x: x * 2`).
- **Scope**: `local`, `global`, `nonlocal` keywords.
6. **Data Structures**
- **List Comprehensions**: Concise creation (e.g., `[x**2 for x in range(10)]`).
- **Dictionary Comprehensions**: `{k: v for k, v in iterable}`.
- **Generators**: Yield values lazily (e.g., `(x**2 for x in range(10))`).
7. **File Handling**
- **Open Files**:
```python
with open("file.txt", "r") as file:
content = file.read()
```
- **Modes**: `r` (read), `w` (write), `a` (append), `b` (binary).
8. **Exception Handling**
- **Try-Except**:
```python
try:
# code
except ValueError as e:
# handle error
finally:
# cleanup code
```
- **Raise Exceptions**: `raise ValueError("Message")`.
9. **Modules and Packages**
- **Modules**: Reusable `.py` files (e.g., `import math`).
- **Packages**: Directories with `__init__.py` and modules.
- **Install Packages**: Use `pip install package_name`.
10. **Object-Oriented Programming (OOP)**
- **Class Definition**:
```python
class MyClass:
def __init__(self, attr):
self.attr = attr
def method(self):
# code
```
- **Inheritance**: `class Child(Parent):`.
- **Special Methods**: `__str__`, `__repr__`, `__len__` (dunder methods).
11. **Input/Output**
- **Input**: `user_input = input("Prompt: ")` (returns string).
- **Print**: `print(f"Formatted: {value}")` (f-strings for formatting).
12. **Advanced Concepts**
- **Mutable vs Immutable**: Lists/dicts are mutable; strings/tuples are immutable.
- **Iterators/Generators**: Use `yield` to create generators.
- **Virtual Environments**: Isolate dependencies with `venv`.
**Key Takeaways**
- Python emphasizes readability and simplicity.
- Dynamic typing and indentation enforce clean code structure.
- Rich standard library and third-party packages expand functionality (e.g., NumPy, Django).
Comments
Post a Comment