CommencerCommencer gratuitement

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.

Cet exercice fait partie du cours

Python for R Users

Afficher le cours

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de code.

# Binge status for males
____ ____(____):
    if num_drinks < 5:
        ____ 'non-binge'
    else:
        ____ 'binge'
        
# Check
print(binge_male(6))
Modifier et exécuter le code