Variables allow us to assign values, conditionals allow us to shape control flow, and loops allow us to repeat code. Functions allow us to reuse code according to specified inputs. Functions compartmentalize code so it can be used, or “called,” whenever we want. They help:
Organize code
Reuse code with different inputs
Abstract away (hide) details
def function_name(parameter):
# function bodyKey components of a function include:
The
defkeyword followed by the function nameZero or more parameters: input variables for the function
A colon at the end of the definition line followed by indented function body
To call a function (to use it), write its name followed by parentheses indicating the arguments that fill-in the parameters, such as function_name(4).
Return statements¶
return is a Python keyword that is used to output a value from a function.
def function_name(parameter):
# more function code belongs here
return value
print("Hey") # unreachable codeThe return statement ends the function call and returns control flow back to the caller. In the example above, the print statement is unreachable.
Example: Hello¶
def print_hello():
print("Hello!")
print_hello()Example: Echo¶
def print_hello():
print("Hello!")
return "Hello!"
print(print_hello())Example: Exclaim¶
def exclaim(phrase):
print(phrase + "!!!")
exclaim("Hi")
exclaim("Yayy")Practice: Divisibility¶
What would Python display?
def is_divisible(a, b):
# What is the remainder after dividing a by b?
if a % b == 0:
return True
return False
print(is_divisible(9, 3))Example: Area of a circle¶
Functions can also have default arguments. If not specified by a function call, the parameter will use the default value.
import math
def area(radius=1):
return math.pi * (radius ** 2)
print(area(2))
print(area())Documentation strings¶
A function’s docstring (documentation string) provides useful documentation about how to use the function.
def function_name(parameter):
"""
Documentation string content goes here!
"""
# function bodyPractice: Is it even?¶
Write a function is_even that returns true if and only if the given number is even (false otherwise).