Night 27: Tidy code
Ya completaste esta noche en Python o pseudocódigo. Cuenta para ambos. Vuelve a practicar si quieres.
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 //; the computer does not run it |
Good names
| Messy | Tidy |
|---|---|
A ← 3 |
SnacksPerDay ← 3 |
INPUT X |
INPUT PetName |
FUNCTION F(N : INTEGER) |
FUNCTION Double(N : INTEGER) |
- A name should say what the value is. Cambridge style joins words with capitals:
SnacksPerDay.
Constants
- A value that never changes is a
CONSTANT. In 9618 you write it with=.
CONSTANT MaxEnergy = 10
DECLARE Energy : INTEGER
Energy ← 4
OUTPUT "Energy: ", Energy, " of ", MaxEnergy
- To change it later, you change one line.
Comments explain why
// The pet sleeps 8 hours, and each hour gives 1 energy.
CONSTANT SleepHours = 8
DECLARE Energy : INTEGER
Energy ← 2
Energy ← Energy + SleepHours // wake up rested
OUTPUT Energy
- Do not explain what each line does: good names do that. Explain why.
Do not repeat yourself
- The same lines again and again? Write a procedure, and use a loop.
PROCEDURE Greet(Name : STRING)
OUTPUT "Good night, " & Name & "!"
ENDPROCEDURE
CALL Greet("Kit")
CALL Greet("Lumi")
- Tidy code has fewer mistakes, because each idea is written only once.
Dificultad 1/5 · 100 monedas + un pequeño bono en el primer intento de hoy
This code works, but A y B say nothing. Rename A hasta SnacksPerDay y B hasta Days everywhere. The output stays 12.
Haz clic en Ejecutar para ver la salida aquí.
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
Make a constant MaxEnergy with the value 10. Write EnergyLeft(Used : INTEGER) RETURNS INTEGER, which returns MaxEnergy - Used. Use the constant, not the number 10.
Haz clic en Ejecutar para ver la salida aquí.
Dificultad 2/5 · 140 monedas + un pequeño bono en el primer intento de hoy
The starter repeats one line three times. Write Greet(Name : STRING), which outputs Good night, Kit! for Kit. Then call it in a loop over the array Names.
Haz clic en Ejecutar para ver la salida aquí.
Dificultad 3/5 · 200 monedas + un pequeño bono en el primer intento de hoy
Write Clamp(Value : INTEGER) RETURNS INTEGER. It keeps energy on the scale: below 0 gives 0, above MaxEnergy gives MaxEnergy, anything else stays the same.
Haz clic en Ejecutar para ver la salida aquí.