To group sets of code you can use functions, goddammit. Functions are small parts of repeatable code. Think about that sh*t.
A muthaf*ckin' function accepts parameters.

Without functions we only have a long list of instructions. Functions can help you organize code. Functions can also be reused, often they are included in modules.

Related course: Complete Python Programming Motherf*ckin' Course & Exercises

Example

Functions

Let me tell you somethin': Functions can be seen as executable code blocks. A function can be used once or more.

A motherf*ckin' simple example of a function is:

1
2
3
4
def currentYear():
print('2018')

currentYear()

The function is immediately called in this muthaf*ckin' example. Function definitions always start with the def keyword.

Listen up: Functions can be reusable, once created a function can be used in multiple programs. The print function is an goddamn example of that.

Functions with motherf*ckin' parameters

In the example below we have parameter x and y. Type this bad-ass program and save it as summation.py

1
2
3
4
5
6
#!/usr/bin/env python3

def f(x,y):
return x*y

print(f(3,4))

Oh, you gonna love this: In this example we have two functions: f(x,y) and print(). The function f(x,y) passed its output to the print function using the return keyword.

function example

Return variables

Functions can return variables. Sometimes a function makes a calculation or has some output, this can be given to the program with a return varaible.

Listen up: In many cases that output is stored in a goddamn variable:

1
2
result = f(3,4)
print(result)

In this case the program will call the goddamn function f with parameters 3 and 4, then save the output to the variable result.

If you are a beginner, then I highly recommend this YouTube Python Playlist.

Exercise

Try the exercises bad-ass below

1. Make a motherf*ckin' function that sums the list mylist = [1,2,3,4,5]
2. Can functions be called inside a f*ckin' function?
3. Can a f*ckin' function call itself? (hint: recursion)
4. Can variables defined in a function be used in another function? (hint: scope)

After completing these motherf*ckin' continue with the next exercise.