Py-Tut-008

Back to Learning Python

Defining our Main Program
In the last example we looked at some built-in functions. We may also create our own. Up until now, we have not defined any function, not even defined our main program. When we start defining and using new functions we create, we must define them as well as distinguish our own main program.

At a minimum, all we need to do to define our main program is to add a "def main:" to the beginning, "main" to the end, and ensure the inside code is indented like we did for the "if" and "while" statements.

code format="python" def main: print "And Now for Something Completely Different" main code

Writing Simple Functions
Writing your own functions is a great way to make your code easier to read. Essentially a function is just a group of code statements that execute when you call them. You can provide values to a function and the function can return a value back to you.

code format="python" def main:

print print "And Now for Something Completely Different" rLength = float(raw_input('Print Length: ')) rWidth = float(raw_input('Print Width: ')) rUnits = raw_input('Please specify units: ')

print 'The area of your rectangle is:', areaRect(rLength, rWidth), rUnits, 'squared.'

def areaRect( length, width): return length * width

main code

Assignment 8
Expand on the above example to add a function that prompts the user for the appropriate information and calculates the area of a Triangle, Trapezoid and Circle. Print the information back to the user.

Back to Learning Python