1 / 16

COMPSCI 101 Principles of Programming

COMPSCI 101 Principles of Programming. Lecture 04 – Creating Functions. Learning outcomes. At the end of this lecture, students should be able to: Define a function that accepts arguments and returns values Provide appropriate documentation for a function

opal
Download Presentation

COMPSCI 101 Principles of 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. COMPSCI 101Principles of Programming Lecture 04 – Creating Functions

  2. Learning outcomes • At the end of this lecture, students should be able to: • Define a function that accepts arguments and returns values • Provide appropriate documentation for a function • Know how to trace code that involves functions COMPSCI 101 - Principles of Programming

  3. Recap • We use the statement import <module> to gain access to the functions defined within a module • When we use a function defined in a module, we use the syntax: • <module name>.<function name> • The help() function provides the docstring for a module or function COMPSCI 101 - Principles of Programming

  4. Why do we use functions? • To reuse our code as much as possible • Take the code that solves a specific problem • Generalise the solution so it can be used for all similar problems • Calculate the area of a rectangle with width of 5 and height of 10 • Better if we could do: """Calculates the area of a rectangle with width of 5 and height of 10 """ width = 5 height = 10 area = width * height print(area) >>> rectangle_area(5, 10) 50 COMPSCI 101 - Principles of Programming

  5. Defining a function • Function to calculate the area of a rectangle: function name function arguments “def” defrectangle_area(width, height): area = width * height return area colon at end “body” of the functionis indented return value COMPSCI 101 - Principles of Programming

  6. Example • Write a function that calculates the area of a square • Arguments (input) • Return value (output) • Docstring (explain what the function does) defsquare_area(side): """Returns the area of a square Arguments: side – length of the side (float or int) Returns: The area of the square """ return side ** 2 COMPSCI 101 - Principles of Programming

  7. Lack of adequate documentation? • A NASA subcontractor developed part of the software system used to control the thrusters of the Mars Climate Orbiter. • They calculated the force in Imperial units (pound-seconds), and returned a floating point value. • Other functions expected the value returned to be calculated in metric value (Newton-seconds) • The thrusters fired at the wrong time, causing it to crash on its arrival at Mars in 1999. • Mission cost around $600 Million COMPSCI 101 - Principles of Programming

  8. Exercise • Write a function that converts a distance from miles to kilometres. Assume that 1 mile is equal to 1.60934 kilometres. COMPSCI 101 - Principles of Programming

  9. Example • Convert a weight from kilograms to pounds • Formula: 1 kilogram = 2.20462 pounds • Arguments: • kilograms (float) • Returns: • pounds (float) COMPSCI 101 - Principles of Programming

  10. Example: Convert weight from kg to lbs defpounds_from_kilo(kilograms): """Converts a weight from kilograms to pounds Arguments: kilograms - weight in kg (float) Returns: Weight in pounds (float) Note: conversion rate is 1 kg = 2.20462 lbs """ return kilograms * 2.20462 COMPSCI 101 - Principles of Programming

  11. Precision of the value displayed • Return value should be as precise as possible • Reduce precision at the last step if needed • For example, print output to 2 decimal places • Round the value after it has been returned >>> round(pounds_from_kilo(1), 2) 2.2 COMPSCI 101 - Principles of Programming

  12. Software rounding • During the 1991 Gulf War, the U.S. deployed its Patriot missile system to protect its troops, allies, and civilians from Iraqi SCUD missile attacks. • A software rounding error in the system calculated time incorrectly, causing it to ignore some incoming missiles.  • A missile battery in Saudi Arabia failed to intercept an incoming SCUD that destroyed a U.S. Army barracks, killed 28 soldiers, and injured 100 others. COMPSCI 101 - Principles of Programming

  13. Example • Write a function that takes a base cost for an item (in dollars, excluding GST) and returns the cost for an item including GST (in dollars, to the nearest cent). • Examples of output: >>> add_gst(6) 6.9 >>> add_gst(0.06) 0.07 >>> add_gst(7) 8.05 >>> add_gst(10) 11.5 >>> add_gst(100) 115.0 >>> add_gst(10.01) 11.51 COMPSCI 101 - Principles of Programming

  14. Example: Adding GST defadd_gst(before_tax): """Returns the cost with GST added Arguments: before_tax - the cost before tax (i.e. excluding GST) Returns: The cost of the item including GST. The value is rounded to the nearest cent. """ after_tax = before_tax * 1.15 #GST is 15% return round(after_tax, 2) COMPSCI 101 - Principles of Programming

  15. Tracing code within a function • Variable scope • Variables used as arguments only exist within the function • Variables created within a function only exist within the function • Tracing code • As you work through the code, when you encounter a function call, draw a box for that function and name it. • Any variables/arguments created within the function are written inside the box. When you are working through code inside a function, you can't access any variables inside another box. before_tax: 100 after_tax: 115.0 COMPSCI 101 - Principles of Programming

  16. Summary Functions are defined using the key worddef • Accept arguments (parameters) • Return values • Functions are a way to generalise tasks • Defining a function extends the tasks that are available • Design functions to be reused as much as possible • Provide documentation so other programmers know how to use the function • Code tracing with functions • A box is drawn to represent the function • Variables drawn inside the box to indicate they are not visible outside the function COMPSCI 101 - Principles of Programming

More Related