Python quick start · Robot club · about 12 min
def, parameters and return: naming a piece of work so the program reads like what it does.
[1 mark]What happens when Python reads the def side(): lines?
def only gives a name to some lines. They run each time you call the name with side().[1 mark]What does this program print?
def side():
print("drive")
print("turn")
side()
side()drive turn drive turn
Each call to side() runs both lines inside it, so two calls print drive, turn, drive, turn.
[1 mark]What does this program print?
def hello():
print("hello")
print("start")start
The function is defined but never called, so its print never runs. Only print("start") does.
[1 mark]What does this program print?
def side(cm):
print("forward", cm)
def square(cm):
for i in range(4):
side(cm)
square(20)forward 20 forward 20 forward 20 forward 20
square(20) passes 20 in as cm, and the loop calls side(20) four times, one line each.
[1 mark]What does this program print?
def gap_now(reading):
return round(reading)
print("the gap is", gap_now(27.6), "cm")the gap is 28 cm
return hands a value back to where the function was called. round(27.6) is 28, so that is what gets printed.
[1 mark]In def side(cm):, what is cm called?
side(40) makes cm 40.[1 mark]Why is it worth putting a square into a square(cm) function? Choose all that apply.
Tick every answer that is true.
Write a function leg(cm) that drives that far forward and then turns right, and use it twice to walk the robot through both green squares: 40 cm, corner, 30 cm.
from bugbot import *
connect()
def leg(cm):
# drive, then turn
forward(50, distance=cm)
leg(40)
stop()The hint students can ask for: leg(cm) drives that far and then turns right. Call it with 40, then with 30.
from bugbot import *
connect()
def leg(cm):
forward(50, distance=cm)
turn_right(35, angle=90)
leg(40)
leg(30)
stop()
Any program that meets the task's checks is marked correct in the simulator; this is one way, not the only way.