# 1. Variáveis e Tipagem

## Introdução

No Python, as **variáveis** são nomes que apontam para objetos na memória. Ao contrário do Bash, o Python é **fortemente tipado**, o que significa que ele não realiza conversões implícitas perigosas, e **dinamicamente tipado**, pois você não precisa declarar o tipo no momento da criação.

## Definição e Atribuição

O Python usa o sinal `=` para atribuição.

```python
nome = "Pentester"  # String (str)
nivel = 10          # Inteiro (int)
altura = 1.85       # Ponto Flutuante (float)
is_admin = True     # Booleano (bool)
```

* **Nomenclatura:** Use `snake_case` (letras minúsculas e sublinhados).
* **Múltipla Atribuição:** `x, y, z = 1, 2, 3`.

## Tipos de Dados Básicos

### 1. Strings (str)

Cadeias de caracteres. Podem ser delimitadas por aspas simples `'` ou duplas `"`.

* **Acesso:** `nome[0]` (primeiro caractere).
* **Imutabilidade:** Você não pode alterar um caractere de uma string diretamente.

### 2. Inteiros (int) e Floats (float)

Python lida com números de forma muito eficiente. No Python 3, o tipo `int` não tem limite de tamanho (limitado apenas pela RAM).

```python
resultado = 10 / 3  # Saída: 3.3333333333333335 (float)
divisao_inteira = 10 // 3 # Saída: 3 (int)
potencia = 2 ** 10  # Saída: 1024
```

### 3. Booleanos (bool)

Valores `True` ou `False`. Essenciais para lógica de controle.

## Tipagem Forte vs Tipagem Dinâmica

### Tipagem Dinâmica

Você pode mudar o objeto para o qual a variável aponta:

```python
alvo = "192.168.1.1"
print(type(alvo))  # <class 'str'>

alvo = 1             # Agora aponta para um inteiro
print(type(alvo))  # <class 'int'>
```

### Tipagem Forte

Python não permite somar tipos incompatíveis sem conversão explícita (Casting):

```python
# Isto causará um TypeError no Python:
# print("Alvo: " + 1)

# Forma correta (Casting):
print("Alvo: " + str(1))
```

## Variáveis Especiais e Escopo

* **Variáveis Locais:** Definidas dentro de funções.
* **Variáveis Globais:** Definidas fora de funções. Para alterar uma global dentro de uma função, use a palavra-chave `global`.
* **Nomes Reservados:** Não use nomes como `list`, `str`, `int`, `print` como nomes de variáveis.

{% stepper %}
{% step %}

### Tipagem Flexível mas Consciente

Embora o Python permita mudar o tipo da variável, evite fazer isso indiscriminadamente para manter a clareza.
{% endstep %}

{% step %}

### Type Hinting (Sugestão de Tipo)

Em scripts maiores para pentest, use dicas de tipo para ajudar na leitura e debugging.

```python
def scan_port(host: str, port: int) -> bool:
    # lógica aqui
    return True
```

{% endstep %}

{% step %}

### Constantes

Por convenção, variáveis que não devem mudar são escritas em MAIÚSCULAS: `TIMEOUT = 5`.
{% endstep %}
{% endstepper %}

{% hint style="info" %}
Use a função `type()` para descobrir o tipo de uma variável e `dir()` para ver quais métodos estão disponíveis para aquele objeto.
{% endhint %}


---

# 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://0xmorte.gitbook.io/bibliadopentestbr/conceitos/programacao-e-linguagens/python/1.-variaveis-e-tipagem.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.
