A function “is a named sequence of statements that performs a desired operation” (as explained in Chapter 3 in the book, Think Like a Computer Scientist). Pay special attention to the syntax when defining functions especially the meaning of parentheses “(” and “)”
A function can be given arguments when called and they are bound to variables (called parameters) within that function. The programmer can also create other variables within that function and those are called local variables because they do not exist outside that function.
When a function is defined, it does not execute. The function only runs when it is called and the order in which functions are called gives the flow of execution of the program. Of course, a function needs to be defined before it can be called.
Exercises
Work out the first three exercises at the end of Chapter 3 in the book.
Write a program which calculates and prints the distance between two points. The first point has as coordinates (x1, y1) and the second (x2, y2). Write a function called distance which takes four arguments corresponding to the coordinates. The calculation is done using Pythagoras’ theorem which necessitates the square root function. Import that function from the Python math library using “from math import sqrt”.
Work out the fourth exercise in the book.
Leave a Reply