A function gives a named task its own place in your program. You define it once with def, then call it whenever you need that task. Start by deciding what information the function needs and what answer it should return.
Parameters and arguments
A parameter is a name in the definition. An argument is the value passed at the call site. In this example minutes is a parameter; 45 is an argument. The function returns a result that another part of the program can use.
def hours_studied(minutes):
return minutes / 60
today_hours = hours_studied(45)
print(today_hours) # 0.75
A function without an explicit return returns None. Printing inside a function is useful for displaying a result, while returning a value lets you calculate with it later.
Default arguments
Defaults let a caller omit a value when there is a sensible usual choice. Put parameters with defaults after required parameters. Prefer immutable defaults such as a string or number. A mutable default list can be shared between calls.
def study_message(topic, minutes=30):
return f"Study {topic} for {minutes} minutes"
print(study_message("functions"))
print(study_message("SQL joins", 45))
Worked example: daily study total
Imagine a learner records three sessions. A small function makes the conversion rule reusable and easy to check.
def total_study_hours(sessions):
total_minutes = sum(sessions)
return round(total_minutes / 60, 2)
print(total_study_hours([25, 35, 40])) # 1.67
The list is supplied by the caller. sum adds its minutes, and round formats the returned number to two decimal places. An empty list returns 0.0.
Practice before checking the answer
- Write
minutes_left(goal, done). Return zero if the goal is already met; otherwise return the remaining minutes. - Write
passed_quiz(score, pass_mark=60). ReturnTruewhen the score meets or exceeds the pass mark.
Show one possible solution
def minutes_left(goal, done):
return max(0, goal - done)
def passed_quiz(score, pass_mark=60):
return score >= pass_mark
assert minutes_left(90, 30) == 60
assert minutes_left(30, 90) == 0
assert passed_quiz(60) is True
assert passed_quiz(60, 70) is FalseQuick review
- What is the difference between a parameter and an argument?
- Why is
returnmore useful thanprintfor a result you will reuse? - What does
minutes_left(30, 50)return?
Reference: Python tutorial: defining functions.