Functions

Functions are a way to group a bunch of code lines together and call them some name. Then some other code can run the functions by using the name.

In Python, there is a word that indicates a function is being made called "def"

Functions are not very useful this way because they run exactly the same each time.

To make them useful, there is a way to pass a value to them so that they can be different each time. The order of values is used to set the values.

Notice that the value 'blue' got set into the color variable similar to the equal sign.

Names for functions are important. Names can be very descriptive like, "ThisAddsTwoNumbersAndPrintsTheResult", but this can be hard to read in a program if every name is really long especially when functions get more complex.

Notice that the "return" word can send a value back to the place where the function was run or "called from".

Notice in the following code that the "val" variable is different in every function. There are different storage locations inside functions. Also notice that the returned value is named "val" inside the function, and gets set into (like the equal sign) "returnedValue" outside of the function.

Lists and dictionaries are different and are shared between functions.

Functions can be nested. For example, a rectangle is made from 4 lines. Each line is made from many points on the line. See the fields/graphics/6-drawRectangle.py example.

So there are many advantages of functions.