Python Variables: A Practical Guide for BeginnersCode & Development

Code & Development · 24 Jun 2026

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.

Genildo Souza24 Jun 2026Read: 6 min

Practical Guide to Python Variables

  • Variables act as names that point to values in memory, using the equals sign for assignment.

  • Python automatically identifies the data type, such as str, int, float, or bool, without the need for explicit declaration.

  • The Python community convention is to use snake_case for variable names and UPPER_CASE to indicate constants.

  • Choose descriptive names for your variables, as code should be readable for humans and not just for the machine.

  • Avoid common errors like NameError by ensuring the variable is defined before it is used in the code.

  • Use f-strings to automatically convert types when combining text with numbers, avoiding TypeError errors.

Code
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.

nome: idade variável aponta para 25 valor na memória idade = 25 int
Diagram — How a variable points to a value in memory

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 = 0
contador = 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)
str "Ana", "Python" int 28, -5, 0 float 1.65, 3.14 bool True, False
Diagram — The 4 basic Python types

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

python
# soma numérica
a = 10
b = 5
print(a + b)   # 15

# concatenação de texto
primeiro = "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 é int
x = "dez"   # x agora é str

# isso funciona, mas confunde quem lê o código

A variable's type should reflect what it represents. If a name changes its type in the middle of the code, it is probably doing too much.

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álidos
nome = "Carlos"
idade_usuario = 30
_interno = True
valor1 = 100

# ❌ nomes inválidos
1nome = "erro"         # começa com número
nome-usuario = "erro"  # hífen não é permitido
for = "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 Python
nome_completo = "Ana Lima"
total_de_itens = 42
data_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 claro
montante = principal * (1 + taxa) ** periodo

A good name describes what the variable contains, not how it was calculated. total is better than resultado_da_soma. Prefer the content.

Multiple assignment

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

python
# atribuir o mesmo valor a múltiplas variáveis
a = b = c = 0

# atribuir valores diferentes em uma linha
nome, idade, cidade = "Ana", 28, "São Paulo"

print(nome)    # Ana
print(idade)   # 28
print(cidade)  # São Paulo

Unpacking requires the number of variables to equal the number of values. If they don't match, Python raises a ValueError.

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.12
LIMITE_MAXIMO = 1000
PI = 3.14159

Any dev who sees an uppercase name understands that the value is a configuration constant — and that changing it in the middle of the code would be a mistake.

Common errors with variables

NameError variável usada antes de ser criada TypeError operação entre tipos incompatíveis Escopo variável criada dentro da função não existe fora
Diagram — The 3 most common errors with variables

NameError — variable used before being defined:

python
print(nome)        # NameError: name 'nome' is not defined
nome = "Carlos"

Python executes line by line. nome must exist before being used — without exception.

TypeError — operation with incompatible types:

python
idade = 28
mensagem = "Minha idade é " + idade
# TypeError: can only concatenate str (not "int") to str

To concatenate a number with text, convert it with str() — or use an f-string, which converts automatically: f"Minha idade é {idade}".

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

Variables created inside functions exist only within them. This concept is scope — and it is the next natural step after mastering variables.

Key takeaways

  • A variable is a name that points to a value. = is assignment, not mathematical equality.

  • Python identifies the type automatically: str, int, float, bool.

  • Use type() to check the type of any value.

  • Names in snake_case, descriptive and without obscure abbreviations.

  • UPPER_CASE signals a constant by convention — it is not enforced by the language.

  • NameError: variable used before being created. TypeError: incompatible operation between types.

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