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.

NameError: name 'nome' is not definedThis 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:
idade = 25Three 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:
contador = 0contador = contador + 1# contador agora vale 1Python 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.
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:
# soma numéricaa = 10b = 5print(a + b) # 15# concatenação de textoprimeiro = "Ana"ultimo = "Lima"print(primeiro + " " + ultimo) # Ana LimaTo know the type of a variable, use type():
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:
x = 10 # x é intx = "dez" # x agora é str# isso funciona, mas confunde quem lê o códigoRules for naming variables
Python accepts any name that follows three rules:
Starts with a letter or underscore (
_)Contains only letters, numbers, and underscores
Is not a reserved Python keyword
# ✅ 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 PythonConvention: 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.
# ✅ 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.
# ❌ o que isso calcula?r = p * (1 + t) ** n# ✅ agora ficou claromontante = principal * (1 + taxa) ** periodoMultiple assignment
Python allows assigning values to multiple variables at the same time:
# 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 PauloConstants: 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:
TAXA_DE_JUROS = 0.12LIMITE_MAXIMO = 1000PI = 3.14159Common errors with variables
NameError — variable used before being defined:
print(nome) # NameError: name 'nome' is not definednome = "Carlos"TypeError — operation with incompatible types:
idade = 28mensagem = "Minha idade é " + idade# TypeError: can only concatenate str (not "int") to strmensagem = "Minha idade é " + str(idade)# ou use f-string, que converte automaticamente:mensagem = f"Minha idade é {idade}"Variable out of scope:
def saudacao(): texto = "Olá"print(texto) # NameError: name 'texto' is not definedA 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


