Python Functions

What is a Function?

Functions allow you to reuse code

  • Performs a specific task
  • Begins with the keyword def followed by the function name and parentheses ( )
  • Any parameters or arguments will be placed in the parentheses ( )
  • Docstrings (optional statements) which describes what the function does
  • The return keyword exits a function

The Structure of a Function

  • Keyword def is the function definition
  • say_hi is the function name
  • everything inside the function is the code block
  • "Print 'Aloha!' greeting" is the docstring
  • print('Aloha!') is the output
  • say_hi( ) is calling (invoking) the function (executing the function, the code block)

Parameters or Arguments

Information that the function needs

  • A parameter is a piece of information (a placeholder) that the function needs 
  • An argument is a piece of information that is passed from a function call to a function

Return Values

The value that the function returns

Scope

Access to your variables based on location

  • Global variables can be accessed throughout your entire program
  • Local variables can be used only inside the function in which they are declared

practice!

Made with Slides.com