A function (sometimes called a method or a procedure) is a block of reusable code that can be called (used) many times from different places in your program. Python contains many built-in functions that you already know like print(), input(), int(), str.format(), str.split(), datetime.strftime(), pdb.set_trace() and so on. But what happens if you don't have an existing function to do some task that your program needs?

In this chapter, you are going to learn how to create your own functions. Your program can rely on your own functions to produce more powerful and flexible behavior with cleaner code. Let's begin by reviewing simple function definitions and understanding where to place them in your source file.

Defining Functions
The overall format of a Python function is shown below.

def <function_name>( parameters ):
"""This optional line will explain what the function does."""
<function code statements>
return
Copy
The function always starts with the "def" keyword (short for "definition"). This is followed by the function name, a set of parentheses, and a list of optional parameters inside the parentheses. End the statement with a colon (:). We'll discuss function parameters in the next lesson, so for now, we'll define simple functions with nothing inside the parentheses.

The body of the function is then indented underneath the "def" statement. As with all blocks of code in Python, this indentation sets apart the function body from the rest of the program and visually shows where the function begins and ends. The body of the function contains statements that will run each time the function is called.

The first, optional line in the function body isn't really a statement at all. You can add a triple-quoted description of the function, if desired. Use either 3 double quotes (") or three single quotes (') around the function description. The description similar to a comment, but it might be read by tools that scan your code to build documentation about your functions.

After an optional quoted description string comes the heart of your function. The remaining code statement(s) make up the body of your function and will run each time the function is called. Your function might be very simple with a single statement, or it might be very complex with dozens of statements, loops, and other program logic.

A function should be ended with the "return" keyword. This keyword signals that the function is done and the program flow should return to the spot in the program from where the function was called.

Remember, all function description strings, body statements and the return keyword should be indented underneath the function "def" statement. Always use the same amount of indentation unless you are intending to start a new block of code with a new level of indentation. However, if you are continuing a long statement across multiple lines using "\" at the end of a line, you can indent the remaining parts of the statement any amount.
An Example Function: make_smiley()
Let's quickly define and run a small sample function. Our make_smiley() function will print out a smiley face on the screen using some character art. Run the code below to see make_smiley() in action!
Do you understand each part of this example? The first "def" line defines the function name. The parentheses after the function name can include a list of parameters, though make_smiley() doesn't need any parameters.

def make_smiley():
Copy
After the "def" statements comes the indented lines of code that make up the function body. We have skipped the optional function description string and began writing the body statements. In this example, we are simply using print() to create some artwork on the screen. Every time the make_smiley() function is called, a new smiley face is printed on the screen.

print(" *** ")
print(" ** ** ")
print(" * * ")
print(" * * * * ")
print(" * * ")
print(" * * * ")
print(" * * * * ")
print(" * ***** * ")
print(" * * ")
print(" ** ** ")
print(" *** ")
Copy
Finally, our function ends with the "return" keyword, which is the last indented line under the "def" statement.

return
Copy
Calling Functions
Calling or using functions in Python is very simple. Just write the function name, followed by a set of parentheses, as shown below. Of course, if your function requires input values, you would place those parameters inside the parentheses.

# call the make_smiley() function
make_smiley()
Copy
Every time you call a function, all of the statements inside the function body are run. In many cases, you will define a function when you want to run the same block of code multiple times from different places in your program. Can you predict what will happen when you run the code below? We've called the make_smiley() function twice, so how many smiley faces will appear on the screen? Function Location within Your Code
Functions in Python must be defined before you can call them! Notice that in all of our examples so far, the function was first defined with the "def" statement, and then later (further down in the source file) we could make use of that function by calling it. This means that generally speaking, your functions will be placed near the top of your source file. Try moving the make_smiley() function call in one of the above code boxes to the top, before the "def" statement.

make_smiley() # ERROR - make_smiley() function not yet defined
def make_smiley():
...
return

Copy
If you try to call a function before it has been defined, you will get a run-time error that tells you the function is not yet defined.

Traceback (most recent call last):
File "code1.py", line 1, in
make_smiley()
NameError: name 'make_smiley' is not defined
If you are creating more than one function, simply place them one after another near the top of your file. You can start your main program flow after all of the functions have been defined.

def function1():
<function statements here>
return

def function2():
<function statements here>
return

def function3():
<function statements here>
return

print("Here we go!")
Copy
Understanding Program Flow with Functions
You are used to programs flowing cleanly from the top of your source file all the way down to the bottom. The program flow might take some branches due to "if / else" logic, and it may even loop with "for" or "while" loops, but the overall sequence starts from line 1 and goes down from there.

Functions interrupt that normal program flow in two ways. First, when a function is defined with "def", program flow will initially skip that entire block of code. The function body statements will never run unless the function is specifically called somewhere later in the code. So, instead of starting at line 1, your program flow will actually start on the first line of code that is not inside a function definition! The illustration below shows the different starting points with and without a function defined at the top of the source file.

Starting point without and with function defs

Second, when you actually call a function, the program flow is transferred to the first statement inside that function. After the function completes with the return keyword, the program flow will go back to the first statement after the one that called the function. This transfer of program flow into a function and then back out happens each time you call the function.

Illustration of program flow into function calls

The diagram above shows how the program flow (in green) starts at the first line outside of a function and - overall - still flows from top to bottom in normal order. However, each time a function is called, the program flow moves inside that function until the return keyword is found. The flow from the first function call is shown in orange and the second function call in blue. Notice that each time the function returns, the flow continues with the next statement after the one that made the function call.

Can you follow the arrows to trace the expected program flow in the above example? You should predict that the illustrated code produces messages in the following order.

The Beginning
Doing useful work
Doing useful work
The End
Note that it is perfectly fine to call other functions from within a function body. So, if you are writing a function and want to make use of any other function - yours or defined by Python - from within your function body, go ahead! When the other function completes, the program flow will always return to the next statement after the one that called it.

Function Naming Rules
You have plenty of flexibility when choosing your variable names, and the same is true when defining function names. Your function names must follow these rules:

The function’s name must consist only of lowercase or capital letters, numbers, and underscores (_). Spaces and other special characters are not allowed.
The first symbol in your function name must always be either a letter or an underscore; you can't start with a number.
Function names are case-sensitive. Therefore, functions named make_smiley(), Make_Smiley() and MAKE_SMILEY() are all different functions. When calling functions, you must write the function name exactly as it is defined, matching the case of all letters.
Here are some examples of valid and invalid function names.

def make_smiley():
def makeSmiley():
def MakeSmiley():
def _makeSmiley():
def make_smiley1000():
def 1MakeSmiley(): # ERROR - numbers cannot be first
def make smiley(): # ERROR - spaces not allowed
Copy
It is best practice to pick one naming style and stick with it throughout your program. If you decide to capitalize the first letter of every word in your function name (MakeSmiley), do this for all your functions. If you decide to capitalize the first letter of every word except the first (makeSmiley), do this for all your functions. You could also decide to use all lowercase letters and separate any words with underscores (make_smiley). If you are consistent, other programmers who have to look at your code later will thank you!

Python's general style recommendations suggest using all lower case letters and underscores for function names, as in "make_smiley". You can see this style yourself in some built-in library functions like pdb.set_trace(). However, Python itself is not consistent - think about datetime.strftime().

Many programmers have a strong preference for their own personal styles. We will tend to use Python recommendations like "make_smiley" or mixed case like "makeSmiley". The mixed case styles (also called "Camel Case") are popular across many programming languages.

1. Why are functions useful in programs?
2. What is the syntax for creating a function in Python?
3. How would you add a description string to your function definition? Is this visible to the user?
4. How are statements identified as belonging to a function?
5. What keyword is used to end a function definition?
6. Where should your functions be located in your code?
7. Where does the main program flow start if functions are present at the top?
8. How do you call (or use) a function from your main code?
9. What are the rules for naming functions in Python?
10. What are two common naming patterns that are recommended or in wide use?

1. Functions are useful in programs because they allow you to reuse code, make your code more organized and modular, and improve readability by breaking down complex tasks into smaller, manageable parts.

2. The syntax for creating a function in Python is:
```python
def function_name(parameters):
"""Optional function description"""
# Function body statements
return
```

3. To add a description string to your function definition, you can include a triple-quoted string at the beginning of the function. This description is not visible to the users of the function directly but can be accessed through documentation tools or your code editor's tooltips.

4. Statements belonging to a function are identified by being indented under the function definition. All statements with the same level of indentation under the `def` statement are part of the function.

5. The `return` keyword is used to end a function definition. It signifies the end of the function's execution and returns a value (if specified) to the caller.

6. Functions should be located near the top of your code file so that they are defined before they are called in the main program flow.

7. If functions are present at the top of your code, the main program flow will start from the first line of code after the function definitions, skipping the function definition blocks.

8. To call a function from your main code, simply write the function name followed by parentheses. If the function requires parameters, you would pass them inside the parentheses.

9. The rules for naming functions in Python are:
- Function names can consist of lowercase or uppercase letters, numbers, and underscores.
- The first character in a function name must be a letter or an underscore.
- Function names are case-sensitive.
- Spaces and special characters are not allowed in function names.

10. Two common naming patterns recommended or in wide use for functions are:
- All lowercase letters with underscores between words (e.g., `make_smiley`)
- CamelCase, where the first letter of each word is capitalized (e.g., `makeSmiley`)