Aan de slagGa gratis aan de slag

Individual binge drinking function

You can create a function using the def keyword, followed by the name of the function. If your function has parameters, you place them within the round brackets, and end the line with a colon. Multiple parameters are separated by a comma. Everything in the body of the function will be indented, just like the if-elif-else statements and for loops. The return statement of the function determines what the function returns. In Python, the return statement is mandatory, unlike R.

An example function looks like this:

def square(x):
    return(x**2)

Let's turn our binge drinking status control-flow statements into a function. Remember, 'binge' drinking happens when men consume 5 or more drinks or women consume 4 or more drinks in about 2 hours.

Deze oefening maakt deel uit van de cursus

Python for R Users

Cursus bekijken

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

# Binge status for males
____ ____(____):
    if num_drinks < 5:
        ____ 'non-binge'
    else:
        ____ 'binge'
        
# Check
print(binge_male(6))
Code bewerken en uitvoeren