Lesson 32: Look before you go
A function that answers
- A procedure does a job. A function does a job and gives back an answer.
look(90)turns the robot to heading 90, measures, and gives back the distance. The answer is used where the call was.- With small functions like
look, a big program is easier to read and to fix.
Words for this lesson
| Word | Meaning |
|---|---|
| return | give a value back to the code that called the function |
| define | write the function once, with def |
| call | use the function: look(90) |
| parameter | the value given to the function: heading |
Return a value
from vexcode_vr import *
def double(n):
return n * 2
def main():
answer = double(21)
brain.print(answer)
vr_thread(main)
- The brain prints
42.double(21)is replaced by the value thatdoublereturns.
In the exam
- 0478/22/F/M/23 Q10(c): state the difference between defining and calling a function. Mark scheme: a function is defined once (set up) and can be called many times (used). In your program
lookis defined once and called four times. - 0478/21/M/J/24 Q2(c): the role of procedures and functions in a program that is easier to maintain. Mark scheme: they divide the program into smaller parts that are easier to understand and debug; meaningful names like
lookandfarthestdocument the program; they can be re-used, so there is less repeated code.
Dificuldade 3/5 · Moedas 200 + pequeno bônus na primeira conclusão hoje
The robot stands in the middle of a room. Write the function look(heading): it turns the robot to the heading and decrescentes the distance in front, as a whole number of mm. The main program already prints look(0), look(90), look(180) e look(270).
Clique em Executar para ver a saída aqui.
Dificuldade 4/5 · Moedas 280 + pequeno bônus na primeira conclusão hoje
Now write farthest(): use look for the headings 0, 90, 180 and 270, and return the heading with the most space. The main program turns to that heading and drives until the wall is 150 mm away. Reach the green square on every map.
Clique em Executar para ver a saída aqui.