Code & Development

Python Variables: A Practical Guide for Beginners

Learn what Python variables are, how to assign values, understand data types, and follow best practices for naming in your code.

Python Variables: A Practical Guide for Beginners
TEXT
NameError: name 'nome' is not defined

This is probably the first error that appears for those starting to write Python. It doesn't appear because the code's logic is wrong — it appears because Python tried to use a name that hasn't been introduced to it yet.

Variables are exactly that introduction. This article explains how to do it correctly.

What is a variable

A variable is a name that points to a value stored in memory. When you write:

PYTHON
idade = 25

Three things happen: the value 25 is created in memory, the name idade is registered, and that name starts pointing to that value. From that point on, whenever Python encounters idade in the code, it will look for the value that the name references.

The = sign here is not mathematical equality. It is assignment. Read it as: "the name idade receives the value 25".

This explains why the line below — which would be impossible in mathematics — is perfectly valid in Python:

PYTHON
contador = 0contador = contador + 1# contador agora vale 1

Python reads the right side first: it takes the current value of contador (0), adds 1, and assigns the result (1) back to the name contador.

Basic data types

The value a variable stores has a type. Python identifies the type automatically from the value you assigned — no need to declare it.

PYTHON
nome = "Ana"          # str (texto)idade = 28            # int (número inteiro)altura = 1.65         # float (número decimal)ativo = True          # bool (verdadeiro ou falso)

Each type has its own behaviors. Adding two numbers works differently than adding two strings:

PYTHON
# soma numéricaa = 10b = 5print(a + b)   # 15# concatenação de textoprimeiro = "Ana"ultimo = "Lima"print(primeiro + " " + ultimo)   # Ana Lima

To know the type of a variable, use type():

PYTHON
print(type(nome))    # <class 'str'>print(type(idade))   # <class 'int'>print(type(altura))  # <class 'float'>print(type(ativo))   # <class 'bool'>

Python is dynamically typed

In Python, a variable can change its type throughout the code. This is possible — but rarely a good idea:

PYTHON
x = 10       # x é intx = "dez"   # x agora é str# isso funciona, mas confunde quem lê o código

Rules for naming variables

Python accepts any name that follows three rules:

  1. Starts with a letter or underscore (_)

  2. Contains only letters, numbers, and underscores

  3. Is not a reserved Python keyword

PYTHON
# ✅ nomes válidosnome = "Carlos"idade_usuario = 30_interno = Truevalor1 = 100# ❌ nomes inválidos1nome = "erro"         # começa com númeronome-usuario = "erro"  # hífen não é permitidofor = "erro"           # palavra reservada do Python

Convention: snake_case

Python uses snake_case by default: lowercase words separated by underscores. This is not mandatory by the language, but it is the community standard — and following the standard makes the code more readable for anyone accustomed to Python.

PYTHON
# ✅ padrão Pythonnome_completo = "Ana Lima"total_de_itens = 42data_de_nascimento = "1995-04-12"# ❌ foge do padrão (funciona, mas destoa)nomeCompleto = "Ana Lima"    # camelCase (comum em outras linguagens)NomeCompleto = "Ana Lima"    # PascalCase (usado para classes em Python)

Good names matter more than it seems

The computer doesn't care about a variable's name. x, dado, valor_final_calculado — to it, they are all the same. The name is for whoever reads the code.

PYTHON
# ❌ o que isso calcula?r = p * (1 + t) ** n# ✅ agora ficou claromontante = principal * (1 + taxa) ** periodo

Multiple assignment

Python allows assigning values to multiple variables at the same time:

PYTHON
# atribuir o mesmo valor a múltiplas variáveisa = b = c = 0# atribuir valores diferentes em uma linhanome, idade, cidade = "Ana", 28, "São Paulo"print(nome)    # Anaprint(idade)   # 28print(cidade)  # São Paulo

Constants: values that should not change

Python doesn't have true constants — the language doesn't prevent a value from being reassigned. The convention is to use names in UPPER_CASE to signal that the value should not be changed:

PYTHON
TAXA_DE_JUROS = 0.12LIMITE_MAXIMO = 1000PI = 3.14159

Common errors with variables

NameError — variable used before being defined:

PYTHON
print(nome)        # NameError: name 'nome' is not definednome = "Carlos"

TypeError — operation with incompatible types:

PYTHON
idade = 28mensagem = "Minha idade é " + idade# TypeError: can only concatenate str (not "int") to str
PYTHON
mensagem = "Minha idade é " + str(idade)# ou use f-string, que converte automaticamente:mensagem = f"Minha idade é {idade}"

Variable out of scope:

PYTHON
def saudacao():    texto = "Olá"print(texto)   # NameError: name 'texto' is not defined

A well-named variable is documentation. The code you write today will be read by someone tomorrow — and that someone, most of the time, is yourself.

References