> For the complete documentation index, see [llms.txt](https://py.d19.in/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://py.d19.in/chapter-2-python-syntax-and-fundamentals/chapter-variables-and-data-types-in-python.md).

# Chapter: Variables and Data Types in Python

***

### 1. **Variables in Python**

#### 1.1 What Are Variables?

Variables are names used to store data values. Think of a variable as a container for data. You can assign, modify, and use variables throughout your program.

#### 1.2 Variable Naming Rules

Here are the official rules for naming variables:

1. Variable names can only contain letters, numbers, and underscores (`_`).
2. They **must not start with a number**.
3. Variable names are **case-sensitive** (`age` and `Age` are different variables).
4. Reserved words (like `if`, `else`, `while`, etc.) **cannot** be used as variable names.

#### 1.3 Good Practices for Naming Variables

* Use descriptive names (e.g., `user_name` instead of `x`).
* Use `snake_case` for variables (e.g., `first_name`).
* Keep names consistent.

#### 1.4 Assigning Values to Variables

You can assign values to variables using the `=` operator:

```python
x = 5      # Integer
name = "Alice"  # String
is_logged_in = True  # Boolean
```

**Multiple Assignments**

You can assign multiple variables in one line:

```python
a, b, c = 1, 2, 3  # a=1, b=2, c=3
x = y = z = 0  # x, y, z all equal 0
```

**Reassigning Variables**

Variables in Python are **dynamic**, meaning their value and type can be reassigned.

```python
x = 42
x = "Now I'm a string"
```

***

### 2. **Data Types in Python**

Python has several built-in data types. These are broadly categorized into **numeric**, **text**, **sequence**, **set**, **mapping**, and **boolean** types.

#### 2.1 Numeric Data Types

**Integer (`int`)**

* Whole numbers, positive or negative, with no decimal points.
* Unlimited precision (can store very large numbers).

Example:

```python
age = 21
negative = -99
large_number = 12345678901234567890
```

**Float (`float`)**

* Numbers with decimal points or in exponential form.

Example:

```python
pi = 3.14159
e = 2.718e3  # Scientific notation (equals 2718.0)
```

**Complex (`complex`)**

* Numbers with a real and imaginary part.

Example:

```python
z = 3 + 4j  # 3 is the real part, 4j is the imaginary part
```

| Numeric Type | Example       | Notes              |
| ------------ | ------------- | ------------------ |
| `int`        | `42, -3`      | No decimal places. |
| `float`      | `3.14, -2.71` | Has decimals.      |
| `complex`    | `3 + 4j`      | Imaginary numbers. |

***

#### 2.2 Text Data Type

**String (`str`)**

* A sequence of characters enclosed in single, double, or triple quotes.

Examples:

```python
greeting = "Hello, World!"
single_quote = 'Python is fun'
multi_line = """This is
a multiline
string."""
```

**Tricks & Precautions**:

* Strings are **immutable**. You can’t change their contents directly.
* Use escape sequences (, , etc.) to include special characters.

```python
escaped = "He said, \"Python is awesome!\""
```

Common String Operations:

| Operation     | Example              | Result          |
| ------------- | -------------------- | --------------- |
| Concatenation | `"Hello " + "World"` | `"Hello World"` |
| Repetition    | `"A" * 5`            | `"AAAAA"`       |
| Slicing       | `"Python"[0:3]`      | `"Pyt"`         |
| Length        | `len("Hello")`       | `5`             |

***

#### 2.3 Boolean Data Type

**Boolean (`bool`)**

* Represents `True` or `False`.

Example:

```python
is_active = True
has_errors = False
```

Booleans are often used in conditions:

```python
if is_active:
    print("The user is active.")
```

***

#### 2.4 Sequence Data Types

**List**

* An ordered, mutable collection.

Example:

```python
fruits = ["apple", "banana", "cherry"]
```

Key Methods:

| Method     | Example                   | Description             |
| ---------- | ------------------------- | ----------------------- |
| `append()` | `fruits.append("grape")`  | Add an item to the end. |
| `remove()` | `fruits.remove("banana")` | Remove an item.         |
| `sort()`   | `fruits.sort()`           | Sort items.             |

**Tuple**

* An ordered, immutable collection.

Example:

```python
coordinates = (10, 20)
```

**Range**

* Represents a sequence of numbers.

Example:

```python
nums = range(5)  # 0, 1, 2, 3, 4
```

***

#### 2.5 Mapping Data Type

**Dictionary (`dict`)**

* Stores key-value pairs.

Example:

```python
user = {"name": "Alice", "age": 25}
```

| Operation     | Example                  | Result              |
| ------------- | ------------------------ | ------------------- |
| Access Value  | `user["name"]`           | `"Alice"`           |
| Add Key-Value | `user["city"] = "Paris"` | Adds new key-value. |
| Delete Key    | `del user["age"]`        | Removes `"age"`.    |

***

#### 2.6 Set Data Type

**Set**

* An unordered, unique collection.

Example:

```python
numbers = {1, 2, 3, 4, 4}  # Output: {1, 2, 3, 4}
```

Key Methods:

| Method     | Example             | Description        |
| ---------- | ------------------- | ------------------ |
| `add()`    | `numbers.add(5)`    | Add an element.    |
| `remove()` | `numbers.remove(3)` | Remove an element. |

***

#### 2.7 NoneType

Represents a variable with no value.

```python
nothing = None
```

***

### 3. **Type Conversion**

Convert between data types using built-in functions:

* `int()`: Convert to integer.
* `float()`: Convert to float.
* `str()`: Convert to string.

Example:

```python
x = "123"
y = int(x)  # Converts string to int
```

***

### 4. **Tricks and Precautions**

1. **Dynamic Typing**: Be cautious with changing variable types, as it may lead to bugs.

   ```python
   x = "5"
   x = x + 2  # Error: Can't add str and int
   ```
2. **Immutable vs. Mutable**:
   * Immutable: `str`, `tuple`.
   * Mutable: `list`, `dict`, `set`.
3. **Copying Data**:

   * Use `copy()` for mutable types to avoid unintended changes.

   ```python
   original = [1, 2, 3]
   copy = original.copy()
   ```
4. **Avoid Shadowing Built-ins**: Don’t use names like `list`, `str`, or `input` as variable names.

***

### Summary Table: Data Types in Python

| Category | Type      | Examples           | Notes                         |
| -------- | --------- | ------------------ | ----------------------------- |
| Numeric  | `int`     | `1, -3, 42`        | Whole numbers.                |
|          | `float`   | `3.14, -0.01`      | Numbers with decimals.        |
|          | `complex` | `3 + 4j`           | Real + imaginary parts.       |
| Text     | `str`     | `"hello", 'world'` | Immutable sequences of chars. |
| Sequence | `list`    | `[1, 2, 3]`        | Mutable, ordered collection.  |
|          | `tuple`   | `(1, 2, 3)`        | Immutable collection.         |
|          | `range`   | `range(5)`         | Sequence of numbers.          |
| Set      | `set`     | `{1, 2, 3}`        | Unordered, unique collection. |
| Mapping  | `dict`    | `{"key": "value"}` | Key-value pairs.              |
| Boolean  | `bool`    | `True, False`      | Logical values.               |
| NoneType | `None`    | `None`             | Represents no value.          |

***
