Order and composition

Lesson 12 of 54 · Python Foundations

Python executes the top level of a file in order. A function name must be bound by the time a call reaches it, though a function definition can refer to another function defined later.

def describe_trip(kilometers):
    minutes = travel_minutes(kilometers)
    return f"{minutes} minutes"

def travel_minutes(kilometers):
    return kilometers * 2

print(describe_trip(6))
12 minutes

Defining describe_trip does not execute its body. By the final call, travel_minutes has also been defined. The first function calls the second, receives 12, and formats the result. Calling describe_trip before the second definition executes would fail when its body tries to find travel_minutes.

An ordinary main function can collect starting steps, with its call after definitions:

def main():
    print(greeting())

def greeting():
    return "Welcome"

main()
Welcome

main is a convention rather than a special keyword. Calling it explicitly starts this example; importing files and guarding that call are separate topics.

Chapter index