Functions are a fundamental building block in Python and all programming languages.
They allow you to encapsulate code into reusable blocks, which makes your programs more organized and readable. This also ties into one key programming practice, DRY, which stands for “don’t repeat yourself.”
Basic function syntax:
python# Declare function def function_name(parameters): return result function_name() # Call function
Example:
pythondef multiply(x, y): return x * y print(multiply(4, 3)) # Output: 12 print(multiply(2, 5)) # Output: 10
Function Parameters And Arguments
Functions can accept parameters, which are placeholders for the values that can be passed to the function.
The values that get passed are called arguments.
There are multiple types of arguments with functions, including: position, keyword, default, arbitrary, and arbitrary keyword arguments.
Position arguments are the most common, and are passed to the function in the same order in which they’re defined.
pythondef add(a, b): return a + b print(add(2, 3)) # Output: 5
Keyword arguments are passed by explicitly naming each parameters, which allows you to specify arguments in any order.
pythondef introduce(first_name, last_name): return f"My name is {first_name} {last_name}" print(introduce(last_name="Smith", first_name="John")) # Output: My name is John Smith
Default arguments are used when a value can be optional when the function is called.
pythondef greet(name="stranger") return f"Hello, {name}" print(greet()) # Output: Hello, stranger print(greet("Jackie")) # Output: Hello, Jackie
In the above example, when no argument is used, the default argument gets called.
Arbitrary arguments are used when you are unsure how many arguments will be passed to the function in advance. They use the *args
parameter as a placeholder for the function, and return args
.
pythondef summarize(*args): return sum(args) print(summarize(1, 2, 3)) # Output: 6 print(summarize(1, 2)) # Output: 3
Keyword arbitrary arguments are used similarly to arbitrary arguments, but they accept a variable number of keyword arguments. They use the *kwargs
parameter as a placeholder for the function, and return kwargs
.
pythondef build_profile(**kwards): return kwargs print(build_profile(name="Andrew", age="22")) Output: {'name': 'Andrew', 'age': 22}
The Return Statement
The return
statement in a function is used to exit the function and send back a value to the caller. if no return
statement is used, the function returns None
by default.
A function can also return multiple values as a tuple.
pythondef get_min_max(numbers): return min(numbers), max(numbers) min_val, max_val = get_min_max([1, 2, 3, 4, 5]) print(min_val) # Output: 1 print(max_val) # Output: 5
Lambda Functions
Lambda functions are defined using the lambda
keyword. They can have any number of parameters, but only one expression.
Lambda functions are commonly used for short and simple operations and passed as arguments to higher-order functions like map()
, filter()
, and sorted()
.
Lamba syntax:
pythonlambda arguments: expression
Example:
pythonadd = lambda a, b: a + b print(add(2, 3)) # Output: 5
In the above example:
add
is the function namea
andb
are the parametersa + b
is the functionality of the lambda function
Using lambda
with map()
:
pythonnumbers = [1, 2, 3, 4, 5] squared = list(map(lambda x: x * x, numbers)) print(squared) # Output: [1, 4, 9, 16, 25]
Function Scope
The scope of a variable refers to the region in which it is recognized. A variable can either have a global or local scope.
A global scope is when a variable is declared outside any function and can be accessed from anywhere in the program.
pythonx = 10 # Global Variable def example(): print(x) example() # Output: 10
A local scope is when a variable is declared insdie of a function, and can only be accessed from within that function.
pythondef example(): x = 10 # Local Variable print(x) example() # Output: 10
If you need to modify a global variable inside a function, use the global
keyword:
pythonx = 10 def example(): global x x = 20 print(x) # Output: 10 example() print(x) # Output: 20
Recursion
Recursion is a technique in programming where a function calls itself to solve a smaller instance of the problem. It is most commonly used for calculating the factorial of a number, or traversing a tree structure.
pythondef factorial(n): if n == 1: return 1 else: return n * factorial(n - 1) print(factorial(5)) # Output: 120
The factorial of a number n is the product of all positive integers less than or equal to n. So, in the above example, factorial 5 = 5 * 4 * 3 * 2 * 1 = 120.
Learn more about how recursion works in detail here.
Docstrings
In Python, docstrings are a special type of comment placed inside the function to describe what the function does. They are written as the first statement in the function body, and enclosed in triple quotes """
.
Docstrings can be accessed via the functions __doc__
attribute.
pythondef add(x, y): """Returns the sum of two numbers""" return x + y print(add.__doc__) # Output: Returns the sum of two numbers
Conclusion
Functions are a fundamental concept in Python as they provide a way to organize and reuse code throughout a program. Mastering functions is crucial for writing efficient and maintainable code as a programmer.