Functions

Python Mastery: From Beginner to Expert - Sykalo Eugene 2023

Functions
Functions and modules

Introduction to Functions

Functions are a set of instructions that are grouped together to perform a specific task. They are used to break down complex problems into smaller, more manageable tasks. By doing so, it is easier to debug and maintain the code.

Functions make code more modular, allowing you to reuse code instead of duplicating it. This makes your code shorter and easier to read, as well as reducing the potential for errors.

Functions can take inputs, called arguments, which allow the function to work with different data each time it is called. They can also return a value or multiple values using the return statement.

In Python, functions are defined using the def keyword followed by the name of the function and a set of parentheses. The parentheses can optionally contain parameters, which are used to pass data to the function. The body of the function is defined using a colon and proper indentation.

To use a function, you call it by its name followed by a set of parentheses. If the function takes parameters, you provide them inside the parentheses. When the function is called, it executes the set of instructions defined in the function body and may optionally return a value.

Defining a Function

Defining a function in Python involves using the def keyword, followed by the function name and a set of parentheses. Within the parentheses, you can declare parameters that will be used by the function. The body of the function is defined using a colon and indentation.

Here is the basic syntax for defining a function:

def function_name(parameter1, parameter2, ...):
 # Function body goes here

The function name should be descriptive of what the function does. It is important to choose a name that is easy to understand and remember.

The parameters are optional and can be used to pass data to the function. They are defined within the parentheses and separated by commas. If there are no parameters, you still need to include the empty parentheses.

The body of the function is indented and contains the set of instructions that the function will perform. It can include any valid Python code, including conditional statements, loops, and other function calls.

Here is an example of a simple function that takes two parameters and returns their sum:

def add_numbers(a, b):
 sum = a + b
 return sum

In this example, the function is called add_numbers and has two parameters, a and b. The body of the function adds the two parameters together and assigns the result to a variable called sum. The return statement then returns the value of sum to the caller.

Once you have defined a function, you can call it from anywhere in your code. Calling a function is done by writing the function name followed by parentheses, optionally containing any required arguments.

result = add_numbers(3, 5)
print(result) # Output: 8

In this example, the add_numbers function is called with arguments 3 and 5. The return value of the function (which is 8) is assigned to the variable result, which is then printed to the console.

Defining functions is an essential part of Python programming, and mastering this concept will allow you to write more modular and reusable code.

Calling a Function

Once you have defined a function, you can call it from anywhere in your code. Calling a function is done by writing the function name followed by parentheses, optionally containing any required arguments.

Here is the basic syntax for calling a function:

function_name(argument1, argument2, ...)

The function_name is the name of the function you want to call. The parentheses are required, even if there are no arguments. If the function requires arguments, you pass them inside the parentheses, separated by commas.

Here is an example of calling a function that takes two arguments:

def add_numbers(a, b):
 sum = a + b
 return sum

result = add_numbers(3, 5)
print(result) # Output: 8

In this example, the add_numbers function is called with arguments 3 and 5. The return value of the function (which is 8) is assigned to the variable result, which is then printed to the console.

When calling a function that returns a value, you can use the return value directly or assign it to a variable for later use.

def square(x):
 return x ** 2

print(square(5)) # Output: 25

y = square(3)
print(y)  # Output: 9

In this example, the square function takes one argument x and returns its square. The function is called twice, once with argument 5 and once with argument 3. The return values are either printed directly to the console or assigned to a variable for later use.

Function Arguments

Function arguments are the inputs that are passed to the function when it is called. They allow you to pass data into the function so that it can be used in the function's logic. Arguments can be of different types, including positional arguments, keyword arguments, and default arguments.

Positional Arguments

Positional arguments are the most common type of argument. They are passed to the function in the order that they are defined. For example, if a function takes two arguments, a and b, you would pass them in the order a first, followed by b.

def add_numbers(a, b):
 return a + b

result = add_numbers(3, 5)
print(result) # Output: 8

In this example, 3 is assigned to a and 5 is assigned to b. The function then returns the sum of a and b, which is 8.

Keyword Arguments

Keyword arguments are arguments that are passed to the function using their names, rather than their position. This allows you to pass the arguments in any order you choose, as long as you specify the name of the argument.

def add_numbers(a, b):
 return a + b

result = add_numbers(b=5, a=3)
print(result) # Output: 8

In this example, b=5 and a=3 are passed as keyword arguments. The order of the arguments does not matter, since they are specified by name.

Keyword arguments are particularly useful when a function has a large number of arguments, or when you want to make the code more readable by clearly indicating the purpose of each argument.

Default Arguments

Default arguments are arguments that have a default value assigned to them. If the argument is not passed to the function, the default value is used instead.

def add_numbers(a, b=5):
 return a + b

result1 = add_numbers(3)
result2 = add_numbers(3, 2)

print(result1) # Output: 8
print(result2) # Output: 5

In this example, b=5 is a default argument. When the function is called with only one argument, a is assigned the value 3, and b is assigned the default value of 5. When the function is called with two arguments, both a and b are assigned values based on the arguments passed.

Default arguments can be very useful when you have a function that is commonly used with a particular value for one of its arguments, but still needs to be flexible enough to allow the user to provide a different value if needed.

Return Statement

The return statement is used to return a value from the function. When the function is called, the return value is assigned to a variable or used directly.

Here is the basic syntax for using the return statement:

def function_name(parameters):
 # Function body goes here
 return value

The return statement is followed by the value that you want to return. This value can be of any type, including integers, floats, strings, and even other objects.

Here is an example of a function that uses the return statement to return the sum of two numbers:

def add_numbers(a, b):
 sum = a + b
 return sum

In this example, the add_numbers function takes two arguments, a and b, and returns their sum using the return statement.

When calling a function that uses the return statement, you can assign the returned value to a variable, or you can use the returned value directly.

result = add_numbers(3, 5)
print(result) # Output: 8

print(add_numbers(2, 4)) # Output: 6

In this example, the add_numbers function is called with arguments 3 and 5. The returned value, which is 8, is assigned to the variable result, which is then printed to the console. In the second line, the returned value is used directly in the print statement.

The return statement is an important tool for any Python developer, as it allows you to write functions that can be used to perform specific tasks and return useful values that can be used elsewhere in your code.

Lambda Functions

Lambda functions, also known as anonymous functions, are functions that are not defined with a name. They are used to create small, one-time use functions that are not needed elsewhere in the code.

Lambda functions are defined using the lambda keyword, followed by the function's parameters and a colon. The body of the function is then defined after the colon, and the result is automatically returned by the function. Here is the basic syntax for a lambda function:

lambda arguments: expression

Here is an example of a lambda function that takes two arguments and returns their sum:

sum = lambda a, b: a + b
print(sum(3, 5)) # Output: 8

In this example, the lambda function takes two arguments, a and b, and returns their sum using the + operator.

Lambda functions are particularly useful when you need to define a small function for a specific task, such as sorting a list or filtering elements. Here is an example of using a lambda function to sort a list of dictionaries by a specific key:

students = [
 {'name': 'John', 'grade': 80},
 {'name': 'Jane', 'grade': 90},
 {'name': 'Bob', 'grade': 75},
]

students.sort(key=lambda x: x['grade'])
print(students)

In this example, the sort method is called on the students list, with a key function specified as a lambda function. The lambda function takes one argument, x, which represents each dictionary in the list. The function returns the value associated with the 'grade' key in the dictionary, which is used to sort the list in ascending order.

Overall, lambda functions are a powerful tool for creating small, reusable functions in Python, and can be particularly useful when working with higher-order functions like map, filter, and reduce.