COP 3223H meeting -*- Outline -*- * Making Problem Solutions General: Defining Functions We've seen how to make calculations, but each time we have to write out the same calculation... It would be better if we could write down the function that we are computing once and just reuse it, hence we have our first and most important abstraction mechanism: ------------------------------------------ FUNCTION DEFINTIONS IN PYTHON Syntax: ::= def ( ) : ::= | , | ... ::= return ------------------------------------------ In this (BNF) notation, ::= means "may be" or "can produce", | means "or" are in angle brackets, and terminals are written without angle brackets ------------------------------------------ FUNCTION DEFINITION EXAMPLES >>> def roomarea(width, length): return width * length >>> roomarea(6,7) 42 # in a file circlearea.py import math # calculate the area of a circle with the # given radius def circlearea(radius): return math.pi * radius**2 # back to the interpreter... >>> from circlearea import circlearea >>> circlearea(1) 3.141592653589793 >>> circlearea(2) 12.566370614359172 ------------------------------------------ Note that in the interpreter you need an extra blank line to end a function definition The import of math allows us to use math.pi from the math module. A module is a collection of named variables and functions that can be referred to with the . syntax after importing it. ------------------------------------------ FUNCTION DEFINITIONS IN C /* in roomarea.c file */ /* Return the area of a room. */ double roomarea(double width, double length) { return width * length; } /* in circlearea.c file */ #include double circlearea(double radius) { return M_PI * radius * radius; } ------------------------------------------ ------------------------------------------ C FUNCTION SYNTAX ::= ::= | ::= ::= | int | short | long | float | double | void | .. ::= ( ) ::= | ::= | , ::= { } ------------------------------------------ This is not the whole truth for C... ** testing in Python You can use the pytest script from the shell pytest test_circlearea.py > circlearea_output.txt or use pytest from within Python's interpreter: ------------------------------------------ TESTING WITH PYTEST IN PYTHON >>> import pytest >>> pytest.main(["test_circlearea.py", "--capture=sys"]) ------------------------------------------