Functions 1A

Abstraction is a key concept in programming and in life.

Abstraction uses a strategy of simplification, wherein formerly concrete details are left ambiguous, vague, or undefined
from wikipedia


In computer science, the mechanism and practice of abstraction reduce and factor out details so that one can focus on a few concepts at a time. en.wikipedia.org/wiki/Abstraction_(computer_science).

Programmers create an abstraction by defining a function: a named sequence of operations. Once you name a bunch of operations, you can ignore the details. Functions are sometimes called procedures or sub-programs.

Here's an example: When you brush your teeth in the morning, you
 

1) open the cabinet, 
2) grab your brush and paste, 
3) put some paste on your brush, 
4) open your mouth, 
5) push the brush across your teeth. 
 
Now when a dad tells a kid to brush his teeth, he doesn’t want to explain all these steps each time. When the dad says, “brush your teeth”, he is making a function call
 
‘Brush your teeth’ is an abstraction for all the many steps involved.
 
The top software engineers don't usually write a lot of code directly. They just design giant pieces of software, working at the structure chart level. They don't think in terms of single lines of code (single blocks in App Inventor), they think in terms of high-level procedures. Once they figure it out, they give specs of the procedures to 'grunt' programmers who then implement them.
 
Their goal is to divide and conquer, to break a problem down into parts small enough that it easy to program.

Calling Built-in Functions

Python provides a number of built-in functions. You are familiar with the built-in functions input and len:
 
    while i<len(list):

The bolded part of the statement above is a function call.

Functions in programming are like math functions: you provide the name of the function, e.g., 'len', followed by an open parenthesis, and then some parameters (e.g., list) and then a closed parenthesis.
 
The function always returns a value to the caller. In the example above, the returned value is used as part of a condition. Other times, you'll want to "catch" the return value in a variable, the do something with it, e.g.,
 
    length = len(list1)

     # use length in the code

Importing Modules

len is a function built-in to the Python language. There are also many libraries of functions that you can 'import' into your programs. You call 'import moduleName' at the top of your program, and then you can use its functions. One popular module is the math module, which has numerous mathematical functions such as sqrt:
 
    import math   # put this at top of file

    number = math.sqrt(16)
 
The import statement says you want to use math functions. But when you import a module, like 'math', you must qualify any function calls you make to functions with "math." For the above example, if you typed in just 'sqrt(16)' you'd get an error. 'math.sqrt(16)' is understandable to Python because it knows that sqrt is within the math module.
 
Other math functions include pow and cosign:

         import math
number = math.pow (x,y)
# returns x to the yth power, so pow(2,3) is 8
cos = math.acos(x) – returns cosine of x
 
A description of all the functions in the math module is at: http://docs.python.org/lib/module-math.html

Another module often used for games is the random module.

This module provides numerous functions, including randint(min,max) which returns a random number between min and max inclusive:
 
    import random # at top of program
    # ...
    number = random.randint(0,10)   # will return a random number 0 through 10
 
In this case, 'random' is the module name, and 'randint' is the function name.
 
Let's play around with randint by writing a loop that calls it and prints the result:
 
import random
i=0
while i<20:
    number = random.randint(0,5)
    print number
    i=i+1
 
What is printed?
 
Note that the randint only returns integers. If you wanted, say, to get a random choice from a set of possible colors, you have to perform some coding work on your own to convert each random integer to a corresponding color.

JES functions

The JES tool you've been using provides library functions for you to call, but it sets things up so you don't have to import a module to do it. The JES functions include getPixel, setColor, pickAFile, etc.

In-Class Assignment

1. Write a program that accepts a number and exponent from the end-user and prints numberexponent
    Use the math module to do it.
2. Write a program that generates and prints a random color from a set of six colors.


Writing Your Own Functions

A function is basically a list of commands. By assigning a name to a bunch of commands, we create an abstraction that can be used in a
larger program. Here is an example of a function in Python:
 
    def totalList(list):
       i=0
       total=0
       while i<len(list):
            total=total+lis[i]
            i=i+1
       return total

totalList is the function name. 'list' is what we call a formal parameter.
 
By defining 'totalList' we can then call it-- from any program we write-- whenever we need to total a list (instead of copy-paste).
 
The caller of the function must supply the correct number of parameters in the function call, and those parameters must be of the same type for the function to work correctly. For instance, the totalList function expects a list of numbers, so here is a valid call to it:
 
    numbers=[2,5,7]
    result = totalList(list)

The data sent to a function are called the 'actual parameters'. So the variable 'numbers' in the above code is the actual parameter sent to totalList.

If one called totalList with the wrong number or type of parameters, the program will either stop executing or behave strangely. Consider what occurs with the following calls:

    result=totalList(7)
    names=['ralph','sara']
    result=totalList(names)
    totalList([4,5])

Return values

A function can return a value to the calling code with the 'return' statement. This is often the last statement in the function. The calling code must 'catch' the return value in a variable, e.g., the variable total is 'catching' the return value of totalList:
 
list=[3,5,2]
total = totalList(list)
 
But as you saw with the 'len' function, sometimes a function is called as part of another construct like a condition:

           while (i<len(list))

Here the result is not caught by a variable, it just is used to evaluate the condition.

With functions, one can break a program into simple parts. A typical Python program will have several functions and a 'main' body of code, as below:
 
    def func1(param1,param2):
    #...
 
    def func2(param1):
    #...
 
    #... more functions
 
    # main code just starts with no indentation
    #...

In-Class Assignment 2

1. Using the IDLE environment: In a file mymath.py, write a function 'cube(x)' which returns the cube of the parameter x. The file's ‘main’ code should call 'cube(x)' a couple of times and print the results. 
 
2. Using JES: Write a program with two functions: thirdColumnBlue and fourthRowRed. Both functions should accept a parameter which is the picture to modify. The main part of your program should ask the user for a picture, loads the picture (makePicture), then call the two functions.

Recent site activity