Python Functions

Functions let you clump one or more lines of code under a single name, and then reuse those lines multiple times by just saying that name. They can save a lot of time and typing, as well as keep your code a lot more organized.

Pretty much anything can be turned into a function, but you never really *have* to have anything be a function (though it would be a lot of work to write a large game without them).

To write a function in python, you first need to define it with the word def. Then say its name, followed by parenthesis. If the function needs information to run, put those variables inside the parenthesis. These are called parameters.

Then, tab over and write the code that the function actually does- it might be some math, or a series of if statements, or even just printing information- this part will be really different from function to function, since it depends on what the function's purpose is. Some functions need a return statement. This is information passed back to the part of the program that called it. To include a return statement in a function definition, write the word "return", followed by whatever variable you're passing back to the program.

To use a function in python you need to call it by saying the name of the function, plus its parenthesis with any required variables inside. Functions that return values can be called inside print statements.

Here are a few examples.

In this first example, you have a function named "multBy4" that takes one parameter and returns the number passed to it multiplied by 4. Notice that this function is called inside a print statement, which is ok because it does return a value: