A function is reusable code that performs a clear task. You have already used built-in functions such as print(), len(), and input(). Now we define our own functions.
Defining functions
Use def to define a function. A function can receive input and return output.
def larger(num1, num2):
if num1 > num2:
return num1
else:
return num2
print(larger(4, 12))
print(larger(54, 33))Output:
12
54return gives a result back to the caller and ends the current function call.
KNOWLEDGE QUIZ
Functions without return values
Some functions perform an action without returning a useful result.
def print_board():
for i in range(3):
for j in range(2):
print(" |", end='')
print()
if i < 2:
print("---+---+---")
print_board()If a function does not explicitly return a value, Python returns None.
Function calls
When a function is called, the program temporarily jumps into that function. When it finishes, execution returns to the original position. This can be understood through the call stack.
Caller → function → return
Unlock the complete interactive lab, deeper explanations, and curated reference answers.
import math
def square(x):
return x ** 2
def distance(point1, point2):
x1, y1 = point1
x2, y2 = point2
return math.sqrt(square(x1 - x2) + square(y1 - y2))
def read_point(message):
raw = input(message)
x_text, y_text = raw.split(",")
return float(x_text), float(y_text)
x1, y1 = read_point("Enter the first point: ")
x2, y2 = read_point("Enter the second point: ")
print("Distance: %.1f" % distance((x1,y1),(x2,y2)))One possible run:
Enter the first point: 0, 0
Enter the second point: 3, 4
Distance: 5.0Nested calls: distance() asks square() twice
Unlock the complete interactive lab, deeper explanations, and curated reference answers.
KNOWLEDGE QUIZ
main()
Python does not require a main() function, but using one often makes larger programs clearer.
def main():
print("Program starts")
if __name__ == "__main__":
main()Write a function that returns an absolute difference
Write absolute_difference(num1, num2) and return the absolute difference.
- Define the function.
- Use if/else to return the non-negative difference.
- Print at least two calls.
Write a prime-checking function
Wrap prime checking in reusable is_prime(n).
- Return False for n <= 1.
- Check factors through sqrt(n).
- Read and report from main().
Calculate the day number within a year
Split the work into is_leap, days_in_month, and day_of_year.
- Implement leap-year logic.
- Return each month length.
- Call helpers from day_of_year and main.