Search this site
Embedded Files
Python Jedi
  • Chapters
    • Fork/Clone
    • 1 Version Control
    • 2 Python Console
    • 3 Input/Output
    • 4 Conditionals
    • 5 Looping
    • 6 Num. Systems
    • 7 Graphics
    • 8 Lists/Strings
    • 9 Functions
    • Prisoner's Dilemma
    • 10 Classes
    • 11 Animation
    • 12 User Control
    • 13 Libraries/Modules
    • 14 Game Design
      • 14 Sprites
      • 14 Shooting
      • 14 Explosions
      • 14 Levels
      • 14 Aiming Trig
      • 14 Walls
      • 14 View Port
      • 14 Grids
    • 15 Data Analysis
Python Jedi
  • Chapters
    • Fork/Clone
    • 1 Version Control
    • 2 Python Console
    • 3 Input/Output
    • 4 Conditionals
    • 5 Looping
    • 6 Num. Systems
    • 7 Graphics
    • 8 Lists/Strings
    • 9 Functions
    • Prisoner's Dilemma
    • 10 Classes
    • 11 Animation
    • 12 User Control
    • 13 Libraries/Modules
    • 14 Game Design
      • 14 Sprites
      • 14 Shooting
      • 14 Explosions
      • 14 Levels
      • 14 Aiming Trig
      • 14 Walls
      • 14 View Port
      • 14 Grids
    • 15 Data Analysis
  • More
    • Chapters
      • Fork/Clone
      • 1 Version Control
      • 2 Python Console
      • 3 Input/Output
      • 4 Conditionals
      • 5 Looping
      • 6 Num. Systems
      • 7 Graphics
      • 8 Lists/Strings
      • 9 Functions
      • Prisoner's Dilemma
      • 10 Classes
      • 11 Animation
      • 12 User Control
      • 13 Libraries/Modules
      • 14 Game Design
        • 14 Sprites
        • 14 Shooting
        • 14 Explosions
        • 14 Levels
        • 14 Aiming Trig
        • 14 Walls
        • 14 View Port
        • 14 Grids
      • 15 Data Analysis

Fork/Clone Ch.09 Functions Jedi Training

What are Functions?

Create a Functions.py file where you can practice creating functions during this chapter.

Functions are used for two reasons:

  • they make code easier to read and understand.

  • they allow code to be used more than once.

By defining a function we can make the program easier to read. Function definitions go below the import statements, and above the rest of the program. While you can put them somewhere else, you shouldn’t.

 To define a function, start by using the def command which stands for define. After the def command goes the function name. Function names are very important! If the function names are descriptive, even a non-programmer should be able to read a set of code and get an idea what is happening. Function names follow the same rules as variable names, and should start with a lower case letter. In this case we are calling it volume_sphere(). Following the function name will be a set of parentheses and a colon. All the commands for the function will have the 4 space indention. See the example below.

def volume_sphere(radius):

    pi = 3.141592653589

    volume = (4 / 3) * pi * radius ** 3

    print("The volume is", volume)

Functions can take parameters. These can be used to increase the flexibility of a function by altering what it does based on parameters passed to it. The data going into our volume_sphere() function will be stored in a new variable called radius. The resulting volume is printed to the screen. The radius variable does not get a value here. Frequently new programmers get confused because parameter variables aren't given a value when the function is defined, so it doesn't look legal. Parameters are given a value when the function is called!

Below is how you would call the function at any time during the rest of your program:

volume_sphere(5)


Run Output:

The volume is 392.699081699

The radius variable in the function is created and initialized with a value of 5. The function's code is run once the execution reaches the call to the function. What if we need to pass in more than one value? Multiple parameters can be passed to a function, each parameter is simply separated by a comma. Examine the function below that will calculate the volume of a cylinder.

def volume_cylinder(radius, height):

    pi = 3.141592653589

    volume = pi * radius ** 2 * height

    print("The volume is", volume)


volume_cylinder(12,3)


Run Output:

The volume is 1357.16802635

main( ) Function

Actually, almost all code should go in a function. It is a good practice to put the main starting point of your program in a function called main and call it.

def print_hello():

    print("Hello!")


def print_goodbye():

    print("Bye!")


def main():

    print_hello()

    print_goodbye()


# Run the main program

main()

An even better way of writing this is with a check to make sure we are trying to run this file, rather than importing it. The statement for this looks a little weird. We will discuss what this is about when we discuss Importing Libraries/Modules.

def print_hello():

    print("Hello!")


def print_goodbye():

    print("Bye!")


def main():

    print_hello()

    print_goodbye()


# Only run the main function if we are running this file.

if __name__ == "__main__":

    main()

Printing versus Returning

Unfortunately, the example functions above are limited. Why? If a person wanted to use the volume_cylinder function to calculate the volume in a six-pack of Mt. Dew, it wouldn't work. It only prints out the volume of one cylinder. It doesn't actually return the value to the program. It is not possible to use the function's print result for one cylinder's volume in an equation and multiply it by six to get a six-pack volume.

This can be solved by using a return statement. For example:

def volume_cylinder(radius, height):

    pi = 3.141592653589

    volume = pi * radius ** 2 * height

    return volume

Return is not a function, and does not use parentheses. Don't do return(volume). Because of the return, this function could be used later on as part of an equation to calculate the volume of a six-pack or Mt. Dew and then print that result as follows:

six_pack_volume = volume_cylinder(2.5, 5) * 6

print(six_pack_volume)


Run Output:

589.048622548

The value returned from volume_cylinder goes into the equation and is multiplied by six.

There is a big difference between a function that prints a value and a function that returns a value. Look at the code below and try them out.

# Function that prints the result

def sum_print(a, b):

    result = a + b

    print(result)


# Function that returns the results

def sum_return(a, b):

    result = a + b

    return result


# This prints the sum of 4+4

sum_print(4, 4)


# This does not

sum_return(4, 4)


# This will not set x1 to the sum

# It actually gets a value of 'None'

x1 = sum_print(4, 4)


# This will

x2 = sum_return(4, 4)

Documenting Functions

Functions in Python typically have a comment as the first statement of the function. This comment is delimited using three single quotes ('''), and is called a docstring. A function may look like:

def volume_cylinder(radius, height):

    '''Returns volume of a cylinder given radius, height.'''

    pi = 3.141592653589

    volume = pi * radius ** 2 * height

    return volume

The great thing about using docstrings in functions is that the comment can be pulled out and put into a website documenting your code. You can also easily use a help function to call the docstring from a function as seen below:

help(volume_cylinder)


Run Output:

Help on function volume_cylinder in module __main__:


volume_cylinder(radius, height)

    Returns volume of a cylinder

    given radius, height.

Variable Scope

The use of functions introduces the concept of variable scope. Scope is where in the code a variable is "alive" and can be accessed. Variable scope is one of the most difficult concepts for beginning programmers. Take notes in your notebook over the following YouTube video by Prof. Paul Craven from Simpson College.

Three Functions Practice

Before moving on to the "crazy difficult" functions that you will find in the repository, try the following three simple functions. Test your functions to make sure they are "functioning" correctly. Start by creating a new file called "Three_Functions.py".

Function #1: Hypotenuse

Define a function hyp(leg1, leg2) that prints the length of the hypotenuse of a right triangle.

Function #2: Mean

Define a function mean(a, b, c) that prints the mean of three numbers. Divide by 3.0 to get a float.

Function #3: Perimeter

Define a function perimeter(base, height) that prints the perimeter of a rectangle with side lengths: base and height.

BB8 Program

     We can use functions to make multiple instances of a drawing. One of the Jedi Tasks requires you to easily draw a BB8 robot of any size at any location using functions. Your resulting program should output something very similar to the following:

Quick Lookup:How to download and turn in Jedi Tasks
Syllabus
Marc C. Hermon - Python Jedi InstructorUrbandale High School, Urbandale, Iowahermonm@urbandaleschools.comWebsite: EngineeringU.com
Google Sites
Report abuse
Google Sites
Report abuse