Night 27: Tidy code
لقد أنهيت هذه الليلة بالفعل باستخدام Python أو الشيفرة الكاذبة. وهي تُحتسب لكلتيهما. تدرّب مرة أخرى إن شئت.
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.
الصعوبة 1/5 · 100 عملة + مكافأة صغيرة عند الإنجاز الأول اليوم
This code works, but a و b say nothing. Rename a إلى snacks_per_day و b إلى days everywhere. The output stays 12.
اضغط تشغيل لرؤية المخرجات هنا.
الصعوبة 2/5 · 140 عملة + مكافأة صغيرة عند الإنجاز الأول اليوم
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.
اضغط تشغيل لرؤية المخرجات هنا.
الصعوبة 2/5 · 140 عملة + مكافأة صغيرة عند الإنجاز الأول اليوم
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.
اضغط تشغيل لرؤية المخرجات هنا.
الصعوبة 3/5 · 200 عملة + مكافأة صغيرة عند الإنجاز الأول اليوم
Define clamp(value). It keeps energy on the scale: below 0 gives 0, above MAX_ENERGY gives MAX_ENERGY, anything else stays the same.
اضغط تشغيل لرؤية المخرجات هنا.