Previous Lecture Lecture 3 Next Lecture

Lecture 3, Mon 10/09

Python functions, testing with pytest

Resources from lecture


Python Functions

Defining functions

f(x) = x2

The same function in Python would be DEFINED as follows - beware of details related to syntax

def f(x):
    return x**2

The above function definition demonstrates the following important rules related to writing any function:

Calling functions

Once we have defined the function f(x), we can CALL it as many times as we like to compute the square of any number. To do that type the following at the Python shell:

>>f("CS8") # Error "CS8" is a string because the ** operator is not defined on strings
>> times(4,5)
>> times(8.7*2.3)
>> times("CS8",3)

Main points from coding exercise:

Example worded problem

Given two points p1 and p2 in 2D Cartesian coordinates, find the Euclidean distance between them

Designing functions using Test Driven Development

Its usually too messy to test your functions by repeatedly calling them in the python shell. We will use the pytest framework to automate this process (just like professional programmars)

Lab01 Warmup–experiencing floating point inaccuracy

python3 -m pytest

Good coding style tips

Add a desription of what the function does:

def f(x):
    Returns the square of the input x
    return x**2