Functions

Functions are like machines

  • Learning to write your own functions will greatly increase the complexity of the programs that you can write

  • A function is a black box-it takes some input,does something with it, and spits out some output

  • Functions hide details away, allowing you to solve problems at a higher level without getting bogged down

Examples

  • A typical function looks like this:

  • A function example: sum

  • Anatomy of sum function

  • Writing your own function

  • Importing a function from a file (module)

    • Once we import MyMathFunctions module we just wrote, we can use the mysum function and myproduct function just like the built-in function

    • The way to call a function is to give the function name followed by parenthesis with values for the number of arguments expected

  • Function arguments

    • We can define functions with more than one arguments

  • Arguments with default values do not need to be supplied when calling a function. But if provided, will overwrite the default values

  • Some existing Python modules

    • The os module provides a platform independent way to work with the operating system, make or remove files and directories

    • The csv module provides readers and writers for comma separated value data

    • The sys module contains many objects and functions for dealing with how python was complied or called when executed

    • The glob module proves the glob function to perform file globbing similar to what the unix shell provides

    • The math module provides common algebra and trigonometric function along with several math constants

    • The re module provides access to powerful regular expression

    • The datetime module provides time and datetime objects. allowing easy comparison of times and dates

    • The time module provides simple estimates for how long a command takes

    • The pickle module provides a way to save python objects to a file that you can unpickle later in a different program

    • The pypi module helps package installation

    • The numpy module is the de facto standard for numerical computing

    • The pandas module is useful for tabular data managing

    • The matplotlib module is the most frequently used plotting package in Python

    • The seaborn module is a module based on matplotlib. It provides a high-level interface for drawing attractive graphics.

Last updated

Was this helpful?