2024
2023
- Basic Data Structures in Python
- Other Python Notes
- Basic Python Functions
- Python Data Types and Operators ### Data Types Python has several built-in data types, categorized as follows: 1. **Numeric Types** - `int`: Integer (e.g., `5`, `-3`, `0`) - `float`: Floating-point number (e.g., `3.14`, `-0.001`, `2.0`) - `complex`: Complex number (e.g., `1 + 2j`, `3 - 4j`) 2. **Sequence Types** - `str`: String (e.g., `"hello"`, `'Python'`) - `list`: Mutable sequence (e.g., `[1, 2, 3]`, `['a', 'b', 'c']`) - `tuple`: Immutable sequence (e.g., `(1, 2, 3)`, `('x', 'y', 'z')`) 3. **Mapping Type** - `dict`: Key-value pairs (e.g., `{'name': 'Alice', 'age': 25}`) 4. **Set Types** - `set`: Unordered, unique elements (e.g., `{1, 2, 3}`) - `frozenset`: Immutable set (e.g., `frozenset({1, 2, 3})`) 5. **Boolean Type** - `bool`: Logical values (`True` or `False`) 6. **Binary Types** - `bytes`: Immutable byte sequence (e.g., `b'hello'`) - `bytearray`: Mutable byte sequence - `memoryview`: Memory view of objects ### Operators Python supports various operators for performing operations on data: 1. **Arithmetic Operators** - `+` (Addition) - `-` (Subtraction) - `*` (Multiplication) - `/` (Division) - `%` (Modulus) - `**` (Exponentiation) - `//` (Floor Division) 2. **Comparison Operators** - `==` (Equal) - `!=` (Not Equal) - `>` (Greater Than) - `<` (Less Than) - `>=` (Greater Than or Equal) - `<=` (Less Than or Equal) 3. **Logical Operators** - `and` (Logical AND) - `or` (Logical OR) - `not` (Logical NOT) 4. **Assignment Operators** - `=` (Assignment) - `+=`, `-=`, `*=`, `/=`, etc. (Compound Assignment) 5. **Bitwise Operators** - `&` (AND) - `|` (OR) - `^` (XOR) - `~` (NOT) - `<<` (Left Shift) - `>>` (Right Shift) 6. **Membership Operators** - `in` (Checks if a value exists in a sequence) - `not in` (Checks if a value does not exist in a sequence) 7. **Identity Operators** - `is` (Checks if two variables refer to the same object) - `is not` (Checks if two variables refer to different objects) ### Example Code ```python # Numeric operations a = 10 b = 3 print(a + b) # Output: 13 print(a // b) # Output: 3 # String operations name = "Python" print(name * 2) # Output: "PythonPython" # List operations numbers = [1, 2, 3] numbers.append(4) print(numbers) # Output: [1, 2, 3, 4] # Dictionary operations person = {'name': 'Alice', 'age': 25} print(person['name']) # Output: "Alice" ``` This covers the fundamental data types and operators in Python. Let me know if you need further clarification!
