5.1 Functions and Calls
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.
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 the function finishes, execution returns to the original position. This can be understood through the call stack.
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, such as 0, 0: ")
x2, y2 = read_point("Enter the second point, such as 3, 4: ")
print("Distance: %.1f" % distance((x1, y1), (x2, y2)))One possible run:
Enter the first point, such as 0, 0: 0, 0
Enter the second point, such as 3, 4: 3, 4
Distance: 5.0main()
Python does not require a main() function, but using one often makes larger programs clearer.
def main():
print("Program starts")
if __name__ == "__main__":
main()