Calling functions
A function call makes Python jump into the function's body, run it, and then come back to just after the call. That's why the order of the lines matters.
Define before you call
Python runs a program from top to bottom, and a def is a line like any other: until it has run, the name doesn't exist. So a call above the definition fails:
greet()
def greet():
print("Hello!")
Traceback (most recent call last):
File "main.py", line 1, in <module>
greet()
^^^^^
NameError: name 'greet' is not definedPut your definitions at the top of the program and the code that uses them below.
Functions that call functions
A function's body can call other functions, your own included. Here title calls line twice:
def line():
print("-" * 20)
def title():
line()
print(" Weekly report")
line()
title()
print("All tasks done.")
--------------------
Weekly report
--------------------
All tasks done.Follow the calls. title() jumps into the body of title. Its first line calls line(), which prints the dashes and comes back into title, exactly where it left off. Then the heading is printed, line() runs once more, and title is done, so Python comes back to the main program and prints the last line.
A function can call another function that's defined further down in the file. What matters is that the other function has been defined by the time the call actually runs: the body of title runs only when title() is called, and by then both definitions have run.
Don't forget the parentheses
The parentheses are what makes a call. The name on its own only refers to the function, and nothing happens:
def beep():
print("Beep!")
beep
print("Was there a beep?")
Was there a beep?Python doesn't even complain: a line with just a name is allowed, it simply does nothing. If a function of yours seems never to run, check that the call has its ().