120 likes | 220 Views
Simple Functions and Names. Sec 9-4 Web Design. Objectives. The student will: Know how to create a simple function in Python. Know how to call a function in Python. Know the rules for “names” in Python. Functions. input. A function is a piece of code you can use over and over again
E N D
Simple Functions and Names Sec 9-4 Web Design
Objectives The student will: • Know how to create a simple function in Python. • Know how to call a function in Python. • Know the rules for “names” in Python
Functions • input • A function is a piece of code you can use over and over again • Treat it like a black box • You pass it (optional) values, it does some work, and it (optionally) returns values • You “call it”,”invoke it”, or “use it” by using its name and parentheses • The things you pass it go inside the parentheses • output = function( input ) function output
Functions • As in any programming language Python has functions. • Functions allows you to modularize your code • Easier to read • Easier to debug • Easy to use over and over
Functions • The basic syntax for defining a Python function takes the form: def <FUNCTION NAME>(<PARAMETERS>): <SOMETHING> ... <SOMETHING>
Functions def <FUNCTION NAME>(<PARAMETERS>): <SOMETHING> ... <SOMETHING> • Note that the lines of the function are indented. • The number of spaces that make up the indentation is not that important as long as they are all the same.
Improper Functions This will not be accepted by Python: Red bar shows the point of the error This is acceptable
Python Functions in IDLE • IDLE will automatically indent lines in a function. • To end the function simple un-indent the line. • IDLE also uses colors to help the readability of a program: • Red – Comments • Blue – Function Names • Orange – Python word
Calling (Invoking) a Function • To call a function you type the function: yoyo() forward()
Rules for Python Names • Some names are reserved by the system and are already defined. Examples are things like: def, print, if, else, while, for, in, and, or, not, return. These names are built in keywords. • A name in Python must begin with either an alphabetic letter (a-z or A-Z) or the underscore (i.e. _) and can be followed by any sequence of letters, digits, or underscore letters. • For example, Vaild: Invalid: iRobot 2robots myRobot Robots-r-cool jitterBug jitterBug2 my2cents my_2_cents
Summary • Functions are defined by: def <FUNCTION NAME>(<PARAMETERS>): <SOMETHING> ... <SOMETHING> • Functions are called by FUNCTION() • Function names must begin with either an alphabetic letter (a-z or A-Z) or the underscore (i.e. _) and can be followed by any sequence of letters, digits, or underscore letters.
Rest of Today • Take the code for the octagon and put it in a function. • Call the function 4 times. • When the function is done show me the results.