Chapter 13, Basic
Input, output and operators
With `print`, `input`, and the operators you already write programs that talk to the person and do calculations.
Code for this chapter: basico/cap13_entrada_operadores.py
The print accepts several values and two parameters that I use a lot: sep (separator) and end (what comes at the end, the newline by default):
print("a", "b", "c", sep="-")
print("sem quebra", end=" ")
print("de linha")
a-b-c
sem quebra de linha
input
The input shows a question, waits for the person to type, and returns always a string. If you need a number, convert:
nome = input("Qual é o seu nome? ")
idade = int(input("Quantos anos você tem? "))
print(f"Olá, {nome}. Em 5 anos você terá {idade + 5} anos.")
Qual é o seu nome? Ana
Quantos anos você tem? 30
Olá, Ana. Em 5 anos você terá 35 anos.
Never trust what the person types
If someone types
trinta, theint()raisesValueErrorand the program crashes. In the exceptions chapter, I show how to validate the input without crashing the program.
Arithmetic operators
| Operator | Operation | Example | Result |
|---|---|---|---|
+ - * | Addition, subtraction, multiplication | 10 - 3 | 7 |
/ | Division (always float) | 10 / 4 | 2.5 |
// | Integer division (rounds down) | 10 // 4 | 2 |
% | Remainder | 10 % 4 | 2 |
** | Power | 2 ** 8 | 256 |
print(10 / 3)
print(10 // 3)
print(-7 // 2)
print(10 % 3)
print(2 ** 8)
print(divmod(17, 5))
3.3333333333333335
3
-4
1
256
(3, 2)
Be careful with -7 // 2: integer division rounds down, so the result is -4, and not -3. The divmod returns quotient and remainder at once.
Comparison and logical operators
Comparisons can be chained, just like in mathematics:
x = 7
print(1 < x < 10)
print(x == 7.0)
print("a" < "b")
True
True
True
The operators and, or and not have two characteristics that most courses do not mention. First, and and or return one of the operands, not necessarily True or False. Second, they perform short-circuiting: they stop as soon as the result is determined.
nome = "" or "anônimo"
print(nome)
print(0 and 5)
print(3 and 5)
print(not [])
anônimo
0
5
True
The language valor or padrao is common to define a default value. Use with caution: it also swaps 0 and "", which can be valid values.
Membership and identity
The operators in and not in ask if an item is in a collection. The operators is and is not ask if two names point to the same object. Use is only with None, True and False:
print("py" in "python", 3 not in [1, 2])
valor = None
print(valor is None, valor is not None)
True True
True False
Compound assignment and the walrus operator
The operators +=, -=, *=, //= and friends modify and assign at once. The operator := (called the walrus, available since Python 3.8) assigns within an expression:
total = 10
total += 5
total *= 2
total //= 4
print(total)
if (n := len("python")) > 5:
print(f"{n} caracteres")
7
6 caracteres
When an expression mixes operators, precedence decides the order: first **, then * / // %, then + -, then comparisons, then not, and and or. I never memorize the entire table: I use parentheses whenever the order is not obvious at first glance.
Exercise 1
Convert seconds into hours, minutes, and seconds
Write decompor(segundos) that returns a tuple (horas, minutos, segundos). For example, 3725 seconds are (1, 2, 5).