# Data Types — Python Fundamentals: From Basics to Async

Source: https://www.skillbyai.com/en/python/py-data-types

> Work with Python's core types: int, float, str, bool and None, plus lists, tuples, sets and dictionaries.

## Scalars

`int` (unbounded), `float`, `complex`, `str` (immutable), `bool`, and `None`.

## The four collections

list mutable/ordered · tuple immutable · set unique/unordered · dict key→value.

```python
nums = [1, 2, 3]
nums.append(4)
point = (10, 20)
tags = {"a", "b"}
person = {"name": "Ada", "age": 36}
person["age"]        # 36
```

## Numbers and booleans

`int` has no size limit, `float` is a 64-bit decimal approximation (so `0.1 + 0.2` is not exactly `0.3`), and `bool` is a subclass of `int` where `True == 1`.

```python
big = 2 ** 100          # int never overflows
price = 19.99           # float
active = True           # bool

0.1 + 0.2               # 0.30000000000000004
True + True             # 2
7 // 2, 7 % 2, 7 / 2    # (3, 1, 3.5)
```

## Checking types: type() and isinstance()

`type(x)` tells you the exact type; `isinstance(x, T)` is the preferred check because it also accepts subclasses.

```python
type(42)                    # <class 'int'>
type("hi")                  # <class 'str'>
isinstance(3.5, float)      # True
isinstance(True, int)       # True (bool is an int)
isinstance(3, (int, float)) # True: any of several types
```

## Type conversion

Convert explicitly with `int()`, `float()`, `str()` and `bool()`. Bad input raises `ValueError`. Empty values (`0`, `""`, `[]`, `None`) are falsy.

```python
int("42")        # 42
float("3.14")    # 3.14
str(7)           # "7"
int(3.9)         # 3  (truncates, does not round)
bool("")         # False
bool("0")        # True (non-empty string)
int("abc")       # ValueError
```

**Quiz:** What does int(3.9) return?

- [ ] 4
- [x] 3
- [ ] 3.9
- [ ] ValueError

*Answer:* 3. int() truncates toward zero; use round() to round.

**Quiz:** Which collection is immutable?

- [ ] list
- [ ] dict
- [x] tuple
- [ ] set

*Answer:* tuple. A tuple can't be changed after creation.
