Chapter 9, Basic
Comments and variables
A variable in Python is not a box that holds a value. It is a name that points to an object, and this difference explains a lot further on.
Code for this chapter: basico/cap09_variaveis.py
Comments
Comments are notes for those reading the code. Python ignores everything that comes after a #, until the end of the line.
# Comentário de uma linha
idade = 30 # comentário no fim da linha
"""
Isto é uma string de várias linhas.
O Python a avalia e descarta, mas ela não é um comentário de verdade.
"""
print(idade)
30
Python does not have multi-line comments. What people do is use a triple-quoted string as if it were a comment. It works, but it is a loose string in the code. When this string is the first statement of a function, class, or module, it becomes a docstring, the official documentation of that object:
def area_quadrado(lado):
"""Devolve a área de um quadrado de lado dado."""
return lado * lado
print(area_quadrado.__doc__)
Devolve a área de um quadrado de lado dado.
I write comments to explain why, never what. The code already says what it does. The comment says the reason for the decision.
Variables are names
In Python, idade = 30 does not "store 30 in age". It creates the integer object 30 and makes the name idade point to it. The type belongs to the object, not to the name. That's why the same name can point to different types throughout the program:
nome = "Ana"
idade = 30
cidade = "Recife"
print(nome, idade, cidade)
valor = 10
print(type(valor))
valor = "dez"
print(type(valor))
Ana 30 Recife
<class 'int'>
<class 'str'>
This view of a label (name pointing to object) will be decisive when we get to lists and functions. Keep it in mind.
Multiple assignments and swapping values between two variables become natural:
a, b = 1, 2
a, b = b, a
print(a, b)
x = y = 0
print(x, y)
2 1
0 0
Valid names and conventions
A name starts with a letter or underscore, contains letters, numbers, and underscores, distinguishes between uppercase and lowercase, and cannot be a reserved word. The module keyword knows all the reserved words:
import keyword
print(keyword.iskeyword("class"))
print(keyword.iskeyword("nome"))
print(len(keyword.kwlist) > 30)
True
False
True
| Element | Convention (PEP 8) | Example |
|---|---|---|
| Variables and functions | snake_case | preco_total |
| Constants | MAIUSCULAS_COM_SUBLINHADO | LIMITE_DE_TENTATIVAS |
| Classes | PascalCase | ContaBancaria |
| Internal use | prefix _ | _cache |
Python does not have true constants
Writing
LIMITE = 3in uppercase is a warning to others that the value should not change. The language does not prevent the change. There istyping.Finalfor static analysis tools, and I show it in the type hints chapter.
Exercise 1
Swap two values without creating a third variable
Data a = 3 and b = 7, swap the values so that a ends up being 7 and b being 3.