1 / 14

Python Functions and Code Efficiency: Avoiding Repetition in Programming

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.

len-lynn
Télécharger la présentation

Python Functions and Code Efficiency: Avoiding Repetition in Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Lab #2-4 Follow-Up:Further into Python

  2. Part 1: Functions

  3. The Sin of Repeating Code No NoNo: motors(1, 1) motors(1, 1) motors(-1, -1) motors(-1, -1)

  4. The Sin of Repeating Code No NoNo: motors(1, 1) motors(1, 1) motors(-1, -1) motors(-1, -1) motors(-1, 1)

  5. Thou Shalt Not Repeat Code! Yes: def forward(pwr): motors(pwr, pwr) defbackward(pwr): motors(-pwr, -pwr) forward(1) backward(1)

  6. def forward(pwr): motors(pwr, pwr) defbackward(pwr): forward(-pwr) Functions support code factoring

  7. def forward(pwr): motors(pwr, pwr) defbackward(pwr): forward(-pwr) Functions support code factoring As in Algebra: ax + bx x (a + b)

  8. r = 2.5 A = pi*r*r # Circle Vc = pi*r*r*h # Cylinder Vs = 4/3 pi*r*r*r # Sphere Factor everywhere!

  9. r = 2.5 A = pi*r*r # Circle Vc = pi*r*r*h # Cylinder Vs = 4/3 pi*r*r*r # Sphere Factor everywhere!

  10. r = 2.5 A = pi*r*r # Circle Vc = A*h # Cylinder Vs = 4/3 A*r # Sphere Factor everywhere!

  11. Anatomy of Python Function Parameter(s) defforward(pwr): motors(pwr, pwr) Mandatory indent (use tab key)

  12. Use helpful comments! # Moves the robot forward with # specified motor power def forward(pwr): motors(pwr, pwr)

  13. Functions can return values, too defareaOfCircle(radius): return pi * radius * radius r = 3 a = areaOfCircle(r) Doesn’t have to be same name!

  14. Functions can call other functions defareaOfCircle(radius): return pi * radius * radius def volumeOfCylinder(radius, height): return areaOfCircle(radius) * height

More Related