Go to: Na-Rae Han's home page  

Python 3 Notes

        [ HOME | LING 1330/2330 ]

Tutorial 19: Defining Functions

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

Video Tutorial

Python 3 Changes

print(x,y) instead of print x, y

input() instead of raw_input()

Video Summary

  • 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 6.)
  • 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...")
    Note that the 3rd print function 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.


Write a function that prints out how many vowels are in a given word. Try in IDLE shell.

Write a function that takes two words and prints out the longer word. Try it in IDLE shell.

Write a function that tests a given word for whether or not it includes all of the five vowel characters. If it does, it should print out "Yay! All 5 vowels in the word."; otherwise it prints out "x is missing" for every missing vowel x. Note 'a' in 'bat' is how you test for substringhood. Try it in IDLE shell.