140 likes | 259 Vues
Dive into the essential concepts of Python functions and their importance in coding efficiency. In this follow-up to Lab #2-4, discover how to create modular code that avoids repetition, represented by the "sin of repeating code." Explore practical examples of motor control functions, learning techniques for effective code factoring. Understand how functions can simplify mathematical operations, such as calculating the area of a circle and the volume of a cylinder. Master the anatomy of Python functions, including parameters and return values, to enhance your programming skills.
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