Night 27: Tidy code
Você já concluiu esta noite, em Python ou pseudocódigo. Ela conta para ambos. Pratique novamente se quiser.
Tonight: tidy code
- Week 4 is about your pet's world. Before you build the final project, tidy up!
- You will learn one thing: how to write clean code that people can read.
Words for tonight
| Word | Meaning |
|---|---|
| tidy | in order; easy to find things |
| constant | a value that never changes while the program runs |
| comment | a note for people, after #; Python does not run it |
Good names
| Messy | Tidy |
|---|---|
a = 3 |
snacks_per_day = 3 |
x = input() |
pet_name = input() |
def f(n): |
def double(n): |
- A name should say what the value is. Python uses
small_words_with_underscores.
Constants in capitals
- A value that never changes goes at the top, in CAPITALS.
MAX_ENERGY = 10
energy = 4
print("Energy:", energy, "of", MAX_ENERGY)
- To change it later, you change one line.
Comments explain why
# The pet sleeps 8 hours, and each hour gives 1 energy.
SLEEP_HOURS = 8
energy = 2
energy = energy + SLEEP_HOURS # wake up rested
print(energy)
- Do not explain what each line does: good names do that. Explain why.
Do not repeat yourself
- The same lines again and again? Make a function, and use a loop.
def greet(name):
print("Good night, " + name + "!")
for name in ["Kit", "Lumi", "Bolt"]:
greet(name)
- Tidy code has fewer mistakes, because each idea is written only once.
Dificuldade 1/5 · Moedas 100 + pequeno bônus na primeira conclusão hoje
This code works, but a e b say nothing. Rename a até snacks_per_day e b até days everywhere. The output stays 12.
Clique em Executar para ver a saída aqui.
Dificuldade 2/5 · Moedas 140 + pequeno bônus na primeira conclusão hoje
Make a constant MAX_ENERGY = 10 at the top. Define energy_left(used), which returns MAX_ENERGY - used. Use the constant, not the number 10, inside the function.
Clique em Executar para ver a saída aqui.
Dificuldade 2/5 · Moedas 140 + pequeno bônus na primeira conclusão hoje
The starter repeats one line three times. Define greet(name), which prints Good night, Kit! for Kit. Then call it in a loop over names.
Clique em Executar para ver a saída aqui.
Dificuldade 3/5 · Moedas 200 + pequeno bônus na primeira conclusão hoje
Define clamp(value). It keeps energy on the scale: below 0 gives 0, above MAX_ENERGY gives MAX_ENERGY, anything else stays the same.
Clique em Executar para ver a saída aqui.