World 4: Functions
Patterns with names
- Some move patterns come back again and again: a hop over a tree, a set of stairs.
- Give the pattern a name once. Then use the name.
Words for this world
| Word | Meaning |
|---|---|
| function | a named block of code you can use many times |
| parameter | a value you give to the function |
| call | run the function by its name |
Name a pattern
def hop():
print("up")
print("right")
print("down")
hop()
hop()
Độ khó 3/5 · 200 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Write a function go(direction, steps) that prints direction steps times. Then call it: go("right", 3), go("down", 2), go("left", 3).
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
Trees stand on the road. Write a function hop() that jumps over one tree: up, right, right, down. Use it to reach home.
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
Write visit(): step right, go up to the star, and come back down. Visit three times, then walk home.
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
Write stairs(n): n times right then down. Call stairs(3), then walk the last 2 squares right.
Nhấn Chạy để xem kết quả ở đây.
Độ khó 4/5 · 280 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Write a function opposite(move) that returns the opposite move (right gives left, down gives up, …). Walk the path, dig, then walk the path backwards with opposite, and take one more step left home.
Nhấn Chạy để xem kết quả ở đây.
Độ khó 4/5 · 280 xu + phần thưởng nhỏ khi hoàn thành lần đầu tiên hôm nay
Write zig(): right, right, down. Call it in a loop to collect all 3 stars and reach home.
Nhấn Chạy để xem kết quả ở đây.