# Приведение типов

### **1. Что такое приведение типов**

* Приведение типов (type casting) — это **явное или неявное преобразование значения из одного типа данных в другой**.
* В Python оно бывает:
  * **явным** (explicit) — с помощью функций `int()`, `str()`, `float()` и т.д.
  * **неявным** (implicit) — Python сам преобразует тип, когда это необходимо (автоматическое приведение).

***

### **2. Явное приведение типов**

```python
x = "10"
y = int(x)  # строка → целое число
print(y + 5)  # 15

a = 5
b = float(a)  # целое → число с плавающей точкой
print(b)      # 5.0

c = str(a)    # число → строка
print(c + " test")  # "5 test"
```

***

### **3. Неявное приведение типов**

* Python автоматически преобразует типы, когда это безопасно:

```python
x = 5      # int
y = 2.5    # float
z = x + y  # int + float → float
print(z)   # 7.5
```

* Обычно происходит между **числовыми типами** (`int`, `float`, `complex`).

***

### **4. Функции для приведения типов**

| Функция   | Преобразует в            |
| --------- | ------------------------ |
| `int()`   | Целое число              |
| `float()` | Число с плавающей точкой |
| `str()`   | Строка                   |
| `bool()`  | Логический тип           |
| `list()`  | Список                   |
| `tuple()` | Кортеж                   |
| `set()`   | Множество                |
| `dict()`  | Словарь                  |

#### **Примеры**

```python
print(int(3.7))       # 3
print(float("5.5"))   # 5.5
print(str(True))      # "True"
print(list((1,2,3)))  # [1,2,3]
```

***

### **5. Применение в автотестах**

* **Конвертация данных из API или CSV**:

```python
age = int(response.json()["age"])
assert age > 18
```

* **Приведение типов для параметризации тестов**:

```python
@pytest.mark.parametrize("input_str", ["1", "2", "3"])
def test_numbers(input_str):
    num = int(input_str)
    assert num > 0
```

* **Сравнение чисел и строк**:

```python
value = "100"
assert int(value) == 100
```

***

💡 **Вывод:**

* Явное приведение (`int()`, `str()`) = когда вы сами преобразуете тип.
* Неявное приведение = Python делает автоматически (например, `int + float`).
* В автотестах важно правильно приводить типы для **сравнения данных и обработки API/CSV**.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://kaze.gitbook.io/qa-theory/osnovy-programmirovaniya-na-python/privedenie-tipov.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
