Night 27: Tidy code
Bạn đã hoàn thành đêm này bằng Python hoặc mã giả. Kết quả được tính cho cả hai. Bạn có thể luyện tập lại nếu muốn.
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.
Độ khó 1/5 · 100 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
This code works, but a và b say nothing. Rename a đến snacks_per_day và b đến days everywhere. The output stays 12.
Nhấn Chạy để xem kết quả ở đây.
Độ khó 2/5 · 140 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
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.
Nhấn Chạy để xem kết quả ở đây.
Độ khó 2/5 · 140 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
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.
Nhấn Chạy để xem kết quả ở đây.
Độ khó 3/5 · 200 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Define clamp(value). It keeps energy on the scale: below 0 gives 0, above MAX_ENERGY gives MAX_ENERGY, anything else stays the same.
Nhấn Chạy để xem kết quả ở đây.