> ## Documentation Index
> Fetch the complete documentation index at: https://fastapi2day.codewithsiva.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Python Basics: Syntax, Variables, Types & Control Flow

> Master Python's core syntax, variable model, data types, operators, and control-flow constructs to confidently write your first programs.

Python is a **high-level, interpreted, object-oriented** programming language celebrated for its clean syntax and remarkable readability. Before you write your first FastAPI endpoint or train your first AI model, you need a firm grip on Python's fundamentals — how variables work, how data is typed, how operators behave, and how execution flows through your programs. This page walks you through every building block you need, with concrete examples and the nuances that trip up beginners.

## Python Fundamentals

A few key characteristics distinguish Python from other languages:

* Python is **dynamically typed** — you never declare a variable's type explicitly.
* Python uses **indentation** instead of curly braces `{}` to define code blocks.
* Everything in Python is an **object**, including functions and classes.
* Variables store **references** to objects, not the objects themselves.
* Python follows the **PEP 8** style guide for consistent, readable code.

## Variables

Variables store references to objects in memory. You create them simply by assigning a value.

```python theme={null}
name = "Alice"
age = 20
price = 99.99
is_active = True
```

### Multiple Assignment

Python lets you assign several variables in one line:

```python theme={null}
x, y, z = 10, 20, 30
```

### Variable Swapping

Swapping two values requires no temporary variable in Python:

```python theme={null}
a, b = 10, 20
a, b = b, a
print(a, b)  # 20 10
```

### Object Identity

Two variables can reference the same underlying object:

```python theme={null}
a = [1, 2]
b = a

print(a == b)   # True  — same value
print(a is b)   # True  — same object in memory
```

<Note>
  Use `==` to compare **values** and `is` to compare **object identity**. Never use `is` to compare numbers or strings in regular code.
</Note>

### Everything is an Object

In Python, every value — number, string, list, function, class — is a first-class object with a type and a unique identity:

```python theme={null}
x = 10
print(type(x))   # <class 'int'>
print(id(x))     # Memory address of the object
```

### Small Integer Caching

CPython caches integers in the range **-5 to 256** as a performance optimisation. This means two variables assigned the same small integer may point to the identical object:

```python theme={null}
a = 100
b = 100
print(a is b)   # True  (cached)

x = 1000
y = 1000
print(x is y)   # May be False (not cached)
```

### Floating-Point Precision

Floats are stored in binary, so some decimal values cannot be represented exactly:

```python theme={null}
print(0.1 + 0.2)           # 0.30000000000000004
print(0.1 + 0.2 == 0.3)    # False
```

<Tip>
  Use `round()` or `math.isclose()` when comparing floating-point numbers to avoid precision surprises.
</Tip>

## Data Types

Python provides a rich set of built-in types:

| Category | Types                     |
| -------- | ------------------------- |
| Numeric  | `int`, `float`, `complex` |
| Boolean  | `bool`                    |
| Text     | `str`                     |
| Sequence | `list`, `tuple`, `range`  |
| Mapping  | `dict`                    |
| Set      | `set`, `frozenset`        |
| Binary   | `bytes`, `bytearray`      |
| Special  | `None`                    |

```python theme={null}
print(type(10))            # <class 'int'>
print(type(3.14))          # <class 'float'>
print(type("Hello"))       # <class 'str'>
print(type([1, 2, 3]))     # <class 'list'>
print(type({"name": "Alice"}))  # <class 'dict'>
```

### Type Conversion

Convert between types using built-in functions:

```python theme={null}
int("10")          # 10
float("3.14")      # 3.14
str(100)           # '100'
list("Python")     # ['P', 'y', 't', 'h', 'o', 'n']
```

## Operators

### Arithmetic Operators

| Operator | Description      | Example             |
| -------- | ---------------- | ------------------- |
| `+`      | Addition         | `10 + 3` → `13`     |
| `-`      | Subtraction      | `10 - 3` → `7`      |
| `*`      | Multiplication   | `10 * 3` → `30`     |
| `/`      | Division (float) | `10 / 3` → `3.333…` |
| `//`     | Floor Division   | `10 // 3` → `3`     |
| `%`      | Modulus          | `10 % 3` → `1`      |
| `**`     | Exponent         | `2 ** 3` → `8`      |

```python theme={null}
a, b = 10, 3
print(a + b)    # 13
print(a // b)   # 3
print(a % b)    # 1
print(a ** b)   # 1000
```

### Comparison Operators

Comparison operators return `True` or `False`:

```python theme={null}
a, b = 10, 3
print(a == b)   # False
print(a != b)   # True
print(a > b)    # True
print(a <= b)   # False
```

### Logical Operators

| Operator | Behaviour                                 |
| -------- | ----------------------------------------- |
| `and`    | Returns first falsy value, or last value  |
| `or`     | Returns first truthy value, or last value |
| `not`    | Reverses the truth value                  |

```python theme={null}
age = 20
has_id = True

print(age >= 18 and has_id)   # True
print(age < 18 or has_id)     # True
print(not has_id)             # False
```

#### Truthy and Falsy Values

Every Python object has a truth value. **Falsy** values include `False`, `None`, `0`, `0.0`, `""`, `[]`, `()`, `{}`, `set()`. Everything else is **truthy**.

```python theme={null}
print(bool(0))       # False
print(bool(""))      # False
print(bool([]))      # False

print(bool(10))      # True
print(bool("Hi"))    # True
print(bool([1, 2]))  # True
```

Because `and` and `or` return operands rather than booleans, you can use them for concise default values:

```python theme={null}
name = "" or "Guest"
print(name)   # Guest
```

### Assignment Operators

```python theme={null}
x = 10
x += 5     # 15
x -= 3     # 12
x *= 2     # 24
x /= 4     # 6.0
x %= 4     # 2.0
x **= 3    # 8.0
```

### Identity and Membership Operators

```python theme={null}
a = []
b = []
print(a == b)       # True  (same value)
print(a is b)       # False (different objects)

print("a" in "apple")       # True
print(3 in [1, 2, 3])       # True
print("Java" not in "Python")  # True
```

### Bitwise Operators

Bitwise operators work on the binary representation of integers:

| Operator | Description | Example         |
| -------- | ----------- | --------------- |
| `&`      | AND         | `5 & 3` → `1`   |
| `\|`     | OR          | `5 \| 3` → `7`  |
| `^`      | XOR         | `5 ^ 3` → `6`   |
| `~`      | NOT         | `~5` → `-6`     |
| `<<`     | Left Shift  | `5 << 1` → `10` |
| `>>`     | Right Shift | `5 >> 1` → `2`  |

```python theme={null}
a, b = 5, 3          # 0101 and 0011 in binary
print(a & b)   # 1
print(a | b)   # 7
print(a ^ b)   # 6
print(a << 1)  # 10
print(a >> 1)  # 2
```

## Control Flow

### if / elif / else

```python theme={null}
marks = 82

if marks >= 90:
    print("A")
elif marks >= 75:
    print("B")
else:
    print("C")
# Output: B
```

### match…case (Python 3.10+)

Python's structural pattern matching is a powerful alternative to long `elif` chains:

```python theme={null}
day = 2

match day:
    case 1:
        print("Monday")
    case 2:
        print("Tuesday")
    case _:
        print("Invalid Day")
# Output: Tuesday
```

### for Loop

```python theme={null}
for i in range(5):
    print(i)           # 0 1 2 3 4

for name in ["Alice", "Bob"]:
    print(name)
```

### while Loop

```python theme={null}
count = 1
while count <= 5:
    print(count)
    count += 1
```

### break, continue, and pass

```python theme={null}
# break — exit the loop immediately
for i in range(10):
    if i == 5:
        break
    print(i)   # 0 1 2 3 4

# continue — skip the current iteration
for i in range(5):
    if i == 2:
        continue
    print(i)   # 0 1 3 4

# pass — placeholder when no action is needed
if True:
    pass
```

### for…else and while…else

The `else` block runs only when the loop completes **without** hitting a `break`:

```python theme={null}
for i in range(5):
    print(i)
else:
    print("Loop completed")   # Always prints here
```

## Python Nuances

<Accordion title="Key things every beginner should know">
  * Everything in Python is an object — including functions and classes.
  * Variables store **references**, not values directly.
  * Use `==` for value comparison; use `is` only for identity checks (e.g., `x is None`).
  * Small integers (`-5` to `256`) are cached by CPython.
  * Floating-point arithmetic is not always exact — use `math.isclose()` for comparisons.
  * Indentation defines code blocks — use 4 spaces consistently.
  * Lists are mutable; tuples are immutable.
  * `and` and `or` return operands, not only `True`/`False`.
  * Truthy/falsy values let you write concise conditionals.
</Accordion>
