blense.
HomeFrontendCodeAINewsGuidesCheatsheetsAbout

Technology decoded, always.

A curated read on AI, product, and the culture behind the code. No noise, no hype.

blense.

Technology with focus. Stories about what innovation really changes.

Sections

FrontendArtificial IntelligenceCode & DevTech News

Blense

AboutRSSPrivacy policyTermsCookies
© 2026 Blense · blense.fun
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.

Gby Genildo SouzaJun 246 min read
Python Variables: A Practical Guide for Beginners
Practical Guide to Python Variables
  • 1Variables act as names that point to values in memory, using the equals sign for assignment.
  • 2Python automatically identifies the data type, such as str, int, float, or bool, without the need for explicit declaration.
  • 3The Python community convention is to use snake_case for variable names and UPPER_CASE to indicate constants.
  • 4Choose descriptive names for your variables, as code should be readable for humans and not just for the machine.
  • 5Avoid common errors like NameError by ensuring the variable is defined before it is used in the code.
  • 6Use f-strings to automatically convert types when combining text with numbers, avoiding TypeError errors.
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.

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 = 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)
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é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
💡

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:

The elite dev's arsenal.
Python Decorators: Understanding @property, @classmethod, and @staticmethod6 minFramework vs SDK: Who Calls Whom8 minDebugging CSS: The Forgotten Margin and Frontend Lessons8 minCopilot CLI Becomes an Agent: Writes Code, Runs Tests, and Fixes Bugs Without Prompting3 min
  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
💡

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á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
ℹ️

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.12LIMITE_MAXIMO = 1000PI = 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 definednome = "Carlos"
🚫

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

TypeError — operation with incompatible types:

PYTHON
idade = 28mensagem = "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
  • 1A variable is a name that points to a value. = is assignment, not mathematical equality.
  • 2Python identifies the type automatically: str, int, float, bool.
  • 3Use type() to check the type of any value.
  • 4Names in snake_case, descriptive and without obscure abbreviations.
  • 5UPPER_CASE signals a constant by convention — it is not enforced by the language.
  • 6NameError: 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

  • Official Python Documentation — Data Types

  • Python Tutorial — Variables and Types

Keep exploring
Want more content like this?

Check out other articles in the same vein and keep the momentum.

See more articles
#Python#Django

The elite dev's arsenal.

Framework vs SDK: Who Calls Whom
Code & Development

Framework vs SDK: Who Calls Whom

You don't call the framework — it calls you. The distinction that changes how you read documentation, with examples in JavaScript and Python.

Genildo Souza · Aug 23 · 8 min
Microfrontends with Angular and Nx: what nobody tells you
Code & Development

Microfrontends with Angular and Nx: what nobody tells you

Every tutorial teaches how to set up microfrontends in minutes, but few reveal the architectural chaos that emerges after months of production deploys.

Genildo Souza · Aug 3 · 15 min
Astro: Island Architecture, Performance, and Where the Framework Truly Fits
Code & Development

Astro: Island Architecture, Performance, and Where the Framework Truly Fits

Astro challenges the modern web status quo by prioritizing static HTML and isolating interactivity into independent, lightweight code islands.

Genildo Souza · Aug 3 · 38 min
In this article
  • What is a variable
  • Basic data types
  • Python is dynamically typed
  • Rules for naming variables
  • Convention: snake_case
  • Good names matter more than it seems
  • Multiple assignment
  • Constants: values that should not change
  • Common errors with variables