A function is a named block of code that you can run as many times as you want. You have already used functions without knowing it: print(), input(), len()… Now you will learn to create your own.
Why use functions
- Reuse: you write the code once and use it wherever needed.
- Organize: a big program is divided into small named pieces.
- Test: it is easier to check a small piece than a whole program.
Defining and calling a function
def greet():
print("Hello")
print("Welcome!")
greet()
greet()
# Hello
# Welcome!
# Hello
# Welcome!
def defines the function. After it come the name, parentheses, a colon and the indented body. Defining it does not run anything: the code only runs when it is called with greet().
The order matters
The function must be defined before the line that calls it:
say_goodbye() # NameError: name 'say_goodbye' is not defined
def say_goodbye():
print("Goodbye")
Functions that call functions
def greet():
print("Hello")
def farewell():
print("Goodbye")
def main():
greet()
farewell()
main()
It is the scheme of Function greeting and farewell. By convention, the main function groups the main program, and the last line of the file calls it.
Function names
They follow the rules for variables: lower case, words separated by underscores (calculate_total) and a verb that says what it does. Choose clear names: a well-named function hardly needs comments.