Step 4
Functions
Package a calculation as a function with parameters, and return its result.
Name a piece of work
A function packages a calculation under a name, so you can run it again with different inputs:
def area(width, height):
return width * height
print(area(2, 3)) # 6
print(area(0.5, 4)) # 2.0
defstarts the definition: the function's name, its parameters in parentheses, then a colon.- The body is the indented lines underneath. Python uses the indentation (4 spaces) to tell which lines belong to the function.
returnhands a value back to whoever called the function.area(2, 3)runs the body withwidth = 2andheight = 3, and the whole call becomes6.
Defining a function doesn't run it; calling it does.
return versus print
print shows a value to you. return gives it back to the program, which can store it or use it in more maths:
total = area(2, 3) + area(1, 1) # 7
A function that only prints gives back None, Python's "nothing" value. The grader calls your functions and checks what they return, so always return the answer.
Every robot lesson is built this way: you'll write functions like forward_kinematics(q) that turn joint angles into a position.
Your task
- Write
deg_to_rad(deg)so it returnsdegconverted to radians. - Write
reach(l1, l2)so it returns the reach of a two-link arm: the two lengths added together.
The starter calls both so you can see what they return. The grader tries each one on several inputs.