Go to: Na-Rae Han's home page  

Python 2.7 Tutorial

With Videos by mybringback.com

#22: Defining Functions

                          << Previous Tutorial           Next Tutorial >>
On this page: defining a custom function with def.

Get Started

Video Summary

  • In the video, Ed starts with this script which uses raw_input(), which he then modifies to include a new function get_legal(). These are the shell outputs.
  • If you have a script that you want to run multiple times without having to restart your shell session, you can turn it into a custom function.
  • In this case, instead of asking for the user's input, you must type in the name of the function along with what you WOULD HAVE typed as your answer to the question.
  • These custom functions work just like any other pre-defined function (like len()), except that they aren't pre-defined - you provide the definition!
  • The name of your function will be in blue text in your script - unless you've changed it in the settings.
  • Once your function has executed, the variable(s) assigned (here, age) will no longer be accessible.

Learn More

  • NOTE! The last print command in the video script starts out with DOUBLE quotes because there is an apostrophe in "can't".
    • Remember that you can also prefix the apostrophe with the backslash "\" to keep it as normal text (a process called escaping), and not as a string delimiter. (We covered this in Tutorial 7.)
  • A function definition starts with def, followed by the function name, the parameter(s) in ( ), a colon :, and then finally an indented function body:
    def sayhello(who): 
        print 'Hello, ' + who + '!'
        print "It's a lovely day."
    
    print "La, la, la, la..."
    hello.py 
    
    Note that the 3rd print statement is outside the indented block. It therefore is not part of the sayhello() function. It executes when the script is run, not when the function is called.
  • There's so much more to functions. And functions are fun, especially when you write the "fruitful" kind, i.e, the ones that return a value rather than just printing stuff. Learn how in User-Defined Functions.

Explore