Multiple Function Definitions

Multiple Function Definitions#

A program can contain as many function definitions as needed. Functions can call other functions.

Example: Two Birthday Songs#

def happy_birthday_emily() -> None:
    print("Happy Birthday to you!")
    print("Happy Birthday to you!")
    print("Happy Birthday, dear Emily.")
    print("Happy Birthday to you!")


def happy_birthday_andre() -> None:
    print("Happy Birthday to you!")
    print("Happy Birthday to you!")
    print("Happy Birthday, dear Andre.")
    print("Happy Birthday to you!")

Output:

Happy Birthday to you!
Happy Birthday to you!
Happy Birthday, dear Emily.
Happy Birthday to you!

Happy Birthday to you!
Happy Birthday to you!
Happy Birthday, dear Andre.
Happy Birthday to you!

This works, but notice the duplication — the two functions are nearly identical. The next section shows how to eliminate it using parameters.

Order of Definitions and Calls#

A function must be defined before it is called. In a script, definitions typically appear at the top and calls at the bottom:

def greet():
    print("Hello!")

greet()      # OK — defined above

The following would fail:

greet()      # NameError — not yet defined

def greet():
    print("Hello!")

The if __name__ == '__main__': pattern (from the Program Structure section) keeps calls cleanly separated from definitions:

# start: birthday_functions
def happy_birthday_emily() -> None:
    print("Happy Birthday to you!")
    print("Happy Birthday to you!")
    print("Happy Birthday, dear Emily.")
    print("Happy Birthday to you!")


def happy_birthday_andre() -> None:
    print("Happy Birthday to you!")
    print("Happy Birthday to you!")
    print("Happy Birthday, dear Andre.")
    print("Happy Birthday to you!")
# end: birthday_functions


if __name__ == '__main__':
    happy_birthday_emily()
    print()
    happy_birthday_andre()