1.Defining functions
def builds a function object out of an indented block and binds a name to it. The block does not run, and its contents are not even checked for correctness, until the function is actually called.
Key features
- def builds a function object and binds a name to it — nothing runs yet
- The indented block is not checked for correctness until the function is called
- A string as the first line becomes __doc__, not part of what runs
- Calling the same function twice reuses one function object both times
- A default argument value is computed once, at def time, and shared by every call
What every function object carries
- def runs — builds a function object, binds a name
- the name — points at that object — nothing inside has executed
- name(...) runs — only now does the body execute, and get checked
Command
def calculate_total(cents): # def builds the object, binds calculate_total to it
"""Convert integer cents to dollars."""
return cents / 100
calculate_total(420) # only now does the body run — 4.2
calculate_total.__name__ # 'calculate_total'def only builds a function object and binds a name to it — the body runs, and its names get checked, only when the function is actually called.