140 likes | 250 Vues
Lab #2-4 Follow-Up: Further into Python. Part 1: Functions. The Sin of Repeating Code. No No No :. motors(1, 1) motors(1, 1) motors(-1, -1) motors(-1, -1). The Sin of Repeating Code. No No No :. motors(1, 1) motors(1, 1) motors(-1, -1) motors(-1, -1) motors(-1, 1).
E N D
The Sin of Repeating Code No NoNo: motors(1, 1) motors(1, 1) motors(-1, -1) motors(-1, -1)
The Sin of Repeating Code No NoNo: motors(1, 1) motors(1, 1) motors(-1, -1) motors(-1, -1) motors(-1, 1)
Thou Shalt Not Repeat Code! Yes: def forward(pwr): motors(pwr, pwr) defbackward(pwr): motors(-pwr, -pwr) forward(1) backward(1)
def forward(pwr): motors(pwr, pwr) defbackward(pwr): forward(-pwr) Functions support code factoring
def forward(pwr): motors(pwr, pwr) defbackward(pwr): forward(-pwr) Functions support code factoring As in Algebra: ax + bx x (a + b)
r = 2.5 A = pi*r*r # Circle Vc = pi*r*r*h # Cylinder Vs = 4/3 pi*r*r*r # Sphere Factor everywhere!
r = 2.5 A = pi*r*r # Circle Vc = pi*r*r*h # Cylinder Vs = 4/3 pi*r*r*r # Sphere Factor everywhere!
r = 2.5 A = pi*r*r # Circle Vc = A*h # Cylinder Vs = 4/3 A*r # Sphere Factor everywhere!
Anatomy of Python Function Parameter(s) defforward(pwr): motors(pwr, pwr) Mandatory indent (use tab key)
Use helpful comments! # Moves the robot forward with # specified motor power def forward(pwr): motors(pwr, pwr)
Functions can return values, too defareaOfCircle(radius): return pi * radius * radius r = 3 a = areaOfCircle(r) Doesn’t have to be same name!
Functions can call other functions defareaOfCircle(radius): return pi * radius * radius def volumeOfCylinder(radius, height): return areaOfCircle(radius) * height