In Python, a function is a block of code that performs a specific task and returns a result. Functions allow you to reuse and modularisation your code, making it easier to write and maintain.
Here is an example of a simple function in Python:
1 2 3 4 | def greet(name): print(f"Hello, {name}!") greet("John") # prints "Hello, John!" |
In this example, the function
greet
takes a single parameter
name
and prints a greeting to the screen. To call the function, you simply need to use its name followed by a set of parentheses and any required parameters.
Return values
In addition to performing a task, functions can also return a value to the caller. To return a value from a function, you can use the
return
statement. For example:
1 2 3 4 5 6 | def add(a, b): """This function adds two numbers and returns the result""" result = a + b return result sum = add(3, 4) # sum is now 7 |
In this example, the function
add
takes two parameters
a
and
b
, adds them together, and returns the result to the caller. The return value can then be assigned to a variable, as shown in the example.
Optional parameters
You can also define function parameters as optional, which means that they do not have to be passed when the function is called. To define an optional parameter, you can give it a default value in the function definition. For example:
1 2 3 4 5 6 | def greet(name, greeting="Hello"): """This function greets the person passed in as a parameter""" print(f"{greeting}, {name}!") greet("John") # prints "Hello, John!" greet("John", "Hi") # prints "Hi, John!" |
In this example, the parameter
greeting
is optional and has a default value of “Hello”. When the function is called without the
greeting
parameter, it will use the default value. If the
greeting
parameter is passed, it will use the value provided.
Variable number of parameters
In Python, you can define a function to accept a variable number of parameters using the
*args
and
**kwargs
syntax.
-
*args
allows you to pass a variable number of positional arguments to a function. The arguments are passed as a tuple. For example:
123456789def sum_numbers(*args):"""This function sums a variable number of numbers and returns the result"""result = 0for num in args:result += numreturn resultprint(sum_numbers(1, 2, 3)) # prints 6print(sum_numbers(1, 2, 3, 4, 5)) # prints 15
In this example, the functionsum_numbers
takes a variable number of positional arguments and sums them up. The arguments are passed as a tuple and can be accessed inside the function using a loop or by indexing the tuple.-
**kwargs
allows you to pass a variable number of keyword arguments to a function. The arguments are passed as a dictionary. For example:
123456def greet(**kwargs):"""This function greets the person passed in as a keyword argument"""print(f"Hello, {kwargs['name']}!")greet(name="John") # prints "Hello, John!"greet(name="Jane", greeting="Hi") # prints "Hello, Jane!"
In this example, the functiongreet
takes a variable number of keyword arguments and prints a greeting to the screen. The arguments are passed as a dictionary and can be accessed inside the function using the dictionary syntax.Anonymous functions (lambda functions)
In Python, you can also create anonymous functions (also known as lambda functions) using the
lambda
keyword. Lambda functions are small, single-line functions that are usually used as arguments to other functions. Here is an example:123456# This function returns the square of a numberdef square(x):return x**2# This is the same function defined as a lambda functionsquare = lambda x: x**2In this example, the function
square
is defined both as a regular function and as a lambda function. The lambda function version is a single line of code and does not have a name.Lambda functions are useful when you need to pass a simple function as an argument to another function. For example:
12345678numbers = [1, 2, 3, 4, 5]# This function squares each number in a list and returns the resultdef square_list(numbers):return [square(x) for x in numbers]# This is the same function defined using a lambda functionsquare_list = lambda numbers: [square(x) for x in numbers]In this example, the function
square_list
is defined both as a regular function and as a lambda function. The lambda function version is a single line of code and does not have a name. -