Chapter 16, Basic
Loops with while
Use `for` when you know what you will iterate over and `while` when you only know the stopping condition.
Code for this chapter: basico/cap16_laco_while.py
while
The while repeats while the condition is true. The condition needs to, at some point, become false; otherwise, the program never ends:
contagem = 3
while contagem > 0:
print(contagem)
contagem -= 1
print("Fogo!")
3
2
1
Fogo!
Infinite loop
If you forget to update the condition variable, the program gets stuck forever. In the terminal,
Ctrl+Cinterrupts. Before running awhile, ask: what changes with each turn and makes the condition become false?
while True with break
When you don't know how many times you will repeat, the pattern while True with a break in the output is the clearest. It is the right way to validate input:
while True:
texto = input("Digite um número positivo: ")
if texto.isdigit() and int(texto) > 0:
break
print("Valor inválido, tente de novo.")
print(f"Você digitou {int(texto)}")
Digite um número positivo: abc
Valor inválido, tente de novo.
Digite um número positivo: -3
Valor inválido, tente de novo.
Digite um número positivo: 42
Você digitou 42
Digits of a number
The combination of while with divmod(n, 10) extracts one digit at a time, from last to first. It is the basis for summing digits, reversing numbers, and testing numeric palindromes:
numero = 1234
while numero > 0:
numero, digito = divmod(numero, 10)
print(digito)
4
3
2
1
original = 12345
invertido = 0
while original > 0:
original, digito = divmod(original, 10)
invertido = invertido * 10 + digito
print(invertido)
54321
A guessing game
The module random randomly selects numbers. The randint(1, 100) includes both extremes:
import random
print(random.randint(1, 100) in range(1, 101))
True
In the game below, I fixed the secret at 63 to make the output predictable. Change to random.randint(1, 100) to play for real:
segredo = 63
tentativas = 0
while True:
palpite = int(input("Seu palpite: "))
tentativas += 1
if palpite < segredo:
print("Muito baixo")
elif palpite > segredo:
print("Muito alto")
else:
print(f"Acertou em {tentativas} tentativas")
break
Seu palpite: 50
Muito baixo
Seu palpite: 75
Muito alto
Seu palpite: 63
Acertou em 3 tentativas
Exercise 1
Sum of the digits
Write soma_digitos(n) with while. For 1234 the result is 10.
Exercise 2
Collatz Conjecture
Start from n. If it is even, divide by 2. If it is odd, multiply by 3 and add 1. Count how many steps it takes to reach 1. Write collatz(n).