Python: Sintaxe e Variáveis do Python

Agora é hora de começar a escrever código Python de verdade. Vamos abordar as regras mais básicas: indentação, comentários e variáveis.

1. Regras de recuo

A característica mais marcante do Python — ele usa indentação para definir blocos de código, em vez de chaves {}.

TEXT 📖 Somente leitura
# ✅ Correct: consistent indentation within a block
if 3 > 1:
    print("3 is greater than 1")
    print("This line is also inside the if block")

# ❌ Error: inconsistent indentation
if 3 > 1:
    print("3 is greater than 1")
  print("Wrong indentation!")  # IndentationError
⚠️ Regra de ouro: Sempre use 4 espaços para recuo, nunca tabulações. A maioria dos editores (VS Code, PyCharm) converte automaticamente uma tecla Tab em 4 espaços.

A indentação se aplica não apenas às instruções if, mas a todos os blocos de código — loops, funções, classes e muito mais:

PYTHON
# Indentation in a for loop
for i in range(3):
    print(i)          # This line is inside the loop
    print("---")      # This line is also inside the loop
print("Done")         # This line is NOT inside the loop

2. Comentários

Os comentários são destinados a leitores humanos — o Python os ignora completamente.

(1) Comentários de uma linha: #

PYTHON
# This is a single-line comment
print("Hello")  # Comment after code

# Multi-line comments use multiple # symbols
# This is line two
# This is line three

(2) Comentários em string de várias linhas: """ """ ou ''' '''

Tecnicamente, trata-se de strings, mas são comumente usadas como comentários de várias linhas:

PYTHON
"""
This is a multi-line comment
Useful for writing function descriptions
Or temporarily blocking out large blocks of code
"""
print("The multi-line string above won't execute")

3. Variáveis

As variáveis em Python não precisam de declarações de tipo — basta atribuir um valor e pronto:

PYTHON
name = "Alice"    # str
age = 25          # int
height = 1.75     # float
is_student = True  # bool

(1) Regras para a nomenclatura de variáveis

Regra Correto ✅ Incorreto ❌
Apenas letras, dígitos e sublinhados my_name my-name
Não pode começar com um algarismo var1 1var
Case-sensitive name and Name are different -
Não pode ser uma palavra-chave - if, for, class

(2) Convenções de nomenclatura (PEP 8)

TEXT 📖 Somente leitura
# ✅ Variables: lowercase with underscores (snake_case)
user_name = "Alice"
total_price = 99.9
max_value = 100

# ✅ Constants: ALL_CAPS with underscores
PI = 3.14159
MAX_SIZE = 1024

# ❌ Not recommended
userName = "Alice"     # CamelCase (Java style)
UserName = "Alice"     # Looks like a class name

(3) Atribuição a múltiplas variáveis

O Python permite atribuir valores a várias variáveis em uma única linha:

PYTHON
# Assign multiple values at once
a, b, c = 1, 2, 3
print(a, b, c)  # 1 2 3

# Swap two variables (other languages need a temporary variable)
x, y = 10, 20
x, y = y, x
print(x, y)  # 20 10

# Assign the same value to multiple variables
m = n = p = 0
print(m, n, p)  # 0 0 0

▶ Exemplo: Tipos de variáveis e troca de valores (Dificuldade ⭐)

PYTHON
# Define variables of different types
name = "Alice"
age = 25
height = 1.68
is_student = True

# Print variable info
print(f"{name} is {age} years old, {height}m tall")
print(f"Student status: {is_student}")

# Swap two variables
a, b = 10, 20
print(f"Before: a={a}, b={b}")
a, b = b, a
print(f"After: a={a}, b={b}")

# Check types
print(f"name type: {type(name)}")
print(f"age type: {type(age)}")
print(f"height type: {type(height)}")
▶ Experimente

Resultado:

TEXT 📖 Somente leitura
Alice is 25 years old, 1.68m tall
Student status: True
Before: a=10, b=20
After: a=20, b=10
name type: <class 'str'>
age type: <class 'int'>
height type: <class 'float'>

▶ Exemplo: Exploração de Tipos de Variáveis (Dificuldade ⭐)

PYTHON
# Explorar diferentes tipos e conversões
x = 42
y = 3.14
z = "Hello"
w = True

print(f"x = {x}, tipo = {type(x).__name__}")
print(f"y = {y}, tipo = {type(y).__name__}")
print(f"z = {z}, tipo = {type(z).__name__}")
print(f"w = {w}, tipo = {type(w).__name__}")

# Conversão de tipo
print(f"\nint(y) = {int(y)}")
print(f"float(x) = {float(x)}")
print(f"str(x) = {str(x)}")
print(f"bool(0) = {bool(0)}, bool(1) = {bool(1)}")

# Tipagem dinâmica: variável pode mudar de tipo
var = 100
print(f"\nvar = {var}, tipo = {type(var).__name__}")
var = "agora é uma string"
print(f"var = {var}, tipo = {type(var).__name__}")
▶ Experimente

Saída:

TEXT 📖 Somente leitura
x = 42, tipo = int
y = 3.14, tipo = float
z = Hello, tipo = str
w = True, tipo = bool

int(y) = 3
float(x) = 42.0
str(x) = 42
bool(0) = False, bool(1) = True

var = 100, tipo = int
var = agora é uma string, tipo = str

▶ Exemplo: Truques de Atribuição de Variáveis (Dificuldade ⭐)

PYTHON
# Atribuição múltipla
a, b, c = 10, 20, 30
print(f"a={a}, b={b}, c={c}")

# Troca sem variável temporária
x, y = 100, 200
print(f"Antes da troca: x={x}, y={y}")
x, y = y, x
print(f"Depois da troca: x={x}, y={y}")

# Mesmo valor para múltiplas variáveis
p = q = r = 0
print(f"p={p}, q={q}, r={r}")

# Desempacotamento de lista
colors = ["vermelho", "verde", "azul"]
first, second, third = colors
print(f"Primeiro: {first}, Segundo: {second}, Terceiro: {third}")
▶ Experimente

Saída:

TEXT 📖 Somente leitura
a=10, b=20, c=30
Antes da troca: x=100, y=200
Depois da troca: x=200, y=100
p=0, q=0, r=0
Primeiro: vermelho, Segundo: verde, Terceiro: azul

4. A função type()

Use type() para verificar o tipo de uma variável:

PYTHON
print(type(10))       # <class 'int'>
print(type(3.14))     # <class 'float'>
print(type("Hello"))  # <class 'str'>
print(type(True))     # <class 'bool'>

# Variables can change type when reassigned (dynamic typing)
x = 10
print(type(x))  # <class 'int'>
x = "Hello"
print(type(x))  # <class 'str'>  ← type changed

5. Erros comuns

TEXT 📖 Somente leitura
# IndentationError: wrong indentation
print("Too much indentation")
  print("This line has an extra space")  # ❌

# NameError: variable not defined
print(z)  # ❌ z was never assigned

# SyntaxError: invalid syntax
print("Hello)  # ❌ quotes not closed

❓ Perguntas Frequentes

P I keep getting NameError: name 'xxx' is not defined. How do I fix this?
R NameError means Python can't find a variable with that name. Common causes: ① Typo in the variable name (Python is case-sensitive — Namename); ② Using a variable before assigning it; ③ Variable was defined inside a function or loop but you're trying to access it outside. Quick fix: add print() before the error line to check what variables actually exist at that point.

📖 Resumo

📝 Exercícios

  1. Escreva um código que defina três variáveis: city (nome da cidade), year (ano), score (nota 88,5) e as exiba usando print()
  2. Troque duas variáveis, a = 5 e b = 10, de modo que a passe a ser 10 e b passe a ser 5
  3. Use type() para verificar os tipos de True, "123" e 3.0
  4. Escreva propositalmente um código com um erro de indentação, veja qual erro o Python exibe e faça uma captura de tela da mensagem de erro
Web-Tutorial.com

Equipe Técnica Web-Tutorial

Uma plataforma de tutoriais mantida por diversos desenvolvedores. Cada tutorial é escrito e revisado por profissionais da área correspondente. Trabalhamos para manter nosso conteúdo preciso e confiável — se encontrar algum problema, avise-nos.

100%