Table of Contents

Functions in Python

Table of Contents

In Python, a function is a block of organized, reusable code that performs a specific task. Functions help break our program into smaller and modular chunks. As a result, it becomes easy to test and debug. Here is a basic example of a function in Python:

def greet(name):
"""
This function greets to the person passed in as parameter
"""
print("Hello, " + name + ". Good morning!")

#calling the function
greet('John')

In the above code, we define a function greet() that takes a parameter name. The function then prints a greeting message using the print() statement. When we call the greet() function and pass it the argument ‘John’, it outputs the message “Hello, John. Good morning!” to the console.

Defining a Function in Python

In Python, you can define a function using the def keyword, followed by the function name, a set of parentheses, and a colon. The function code is indented below the first line. Here is a basic function definition in Python:

def my_function():
    print("Hello, World!")

Calling a Function in Python

Once you have defined a function in Python, you can call it by using its name followed by parentheses. Here’s an example of how to call a function:

# define a function
def greet(name):
    print("Hello, " + name + ". Good morning!")

# call the function with an argument
greet("John")  # Output: "Hello, John. Good morning!"

In this example, we first define a function called greet() that takes a single parameter called name. Inside the function, we print a greeting message that includes the name parameter.

Passing Arguments in a Function in Python

In Python, you can pass arguments to a function by including them inside the parentheses when you define the function. The arguments can then be used within the function to perform some action or return a value. Here’s an example of a function that takes two arguments:

def add_numbers(x, y):
    result = x + y
    return result

In this example, we define a function called add_numbers() that takes two arguments, x and y. The function adds the two arguments together and stores the result in a variable called result. The function then returns the value of result using the return keyword.

To call the add_numbers() function and pass it two arguments, we simply include the arguments inside the parentheses when we call the function, like this:

sum = add_numbers(5, 10)
print(sum)  # Output: 15

In this example, we’re calling the add_numbers() function and passing it the arguments 5 and 10. The function adds the two numbers together and returns the value 15, which we then store in a variable called sum. We then print the value of sum to the console using the print() function.

Keyword Arguments Function

You can also pass arguments to a function as keyword arguments, which allows you to specify the argument names explicitly. Here’s an example:

def greet(name, greeting):
    print(greeting + ", " + name + "!")

greet(name="John", greeting="Hello")  # Output: "Hello, John!"

In this example, we define a function called greet() that takes two arguments, name and greeting. The function prints a greeting message that includes the name and greeting arguments.

To call the greet() function with keyword arguments, we specify the argument names explicitly using the name= and greeting= syntax. This allows us to pass the arguments in any order we want, as long as we specify their names. In this case, we’re passing the string “John” as the name argument and the string “Hello” as the greeting argument, so the output to the console will be “Hello, John!”.

Default Arguments Function

In Python, you can define default values for function arguments by assigning a value to the argument inside the function definition. This allows you to call the function with fewer arguments, since the default values will be used if the argument is not explicitly specified. Here’s an example:

def greet(name, greeting="Hello"):
    print(greeting + ", " + name + "!")

greet("John")          # Output: "Hello, John!"
greet("Mary", "Hi")    # Output: "Hi, Mary!"

In this example, we define a function called greet() that takes two arguments, name and greeting. The greeting argument has a default value of “Hello”, which means that if the argument is not specified when the function is called, the default value will be used instead.

We can call the greet() function with just the name argument, and the default value of “Hello” will be used

Variable Length Argument Function

In Python, you can define a function with a variable number of arguments by using the special syntax *args or **kwargs. These arguments are known as variable-length argument lists.

  • *args allows a function to accept a variable number of non-keyword arguments, while
  • **kwargs allows a function to accept a variable number of keyword arguments.

Here’s an example of a function that uses *args to accept a variable number of arguments:

def my_function(*args):
    for arg in args:
        print(arg)

my_function(1, 2, 3)    # Output: 1 2 3
my_function('a', 'b')   # Output: 'a' 'b'

In this example, we define a function called my_function() that accepts a variable number of non-keyword arguments using the *args syntax. The function then prints each argument on a separate line.

Here’s an example of a function that uses **kwargs to accept a variable number of keyword arguments:

def my_function(**kwargs):
    for key, value in kwargs.items():
        print(key + ': ' + value)

my_function(name='John', age='30')  # Output: name: John  age: 30
my_function(city='New York')        # Output: city: New York

In this example, we define a function called my_function() that accepts a variable number of keyword arguments using the **kwargs syntax. The function then prints out each key-value pair on a separate line.

Anonymous Function in Python

In Python, anonymous functions are functions that are defined without a name. They are also known as lambda functions, and they are created using the lambda keyword.

Lambda functions are useful for creating small, one-time use functions that are not needed elsewhere in your code. They are often used as arguments to higher-order functions, or as part of more complex expressions.

Here’s an example of a lambda function that squares its input:

square = lambda x: x ** 2
print(square(4))    # Output: 16

In this example, we define a lambda function called square that takes a single argument x and returns the square of that argument. We then call the square() function with an argument of 4, which returns 16.

Fruitful Functions in Python

In Python, a function that returns a value is called a “fruitful” function. Fruitful functions are useful when you need to perform a computation and return a result that can be used elsewhere in your code.

Here’s an example of a simple fruitful function that takes two numbers as arguments and returns their sum:

def add_numbers(x, y):
    result = x + y
    return result

sum = add_numbers(3, 4)
print(sum)    # Output: 7

In this example, we define a function called add_numbers() that takes two arguments x and y, adds them together, and returns the result. We then call the add_numbers() function with arguments 3 and 4, and assign the resulting sum to a variable called sum. Finally, we print out the value of sum, which is 7.

Fruitful functions can also return more complex data structures, such as lists or dictionaries.

Fruitful functions are a powerful tool in Python, and can be used to encapsulate complex computations and make them more manageable and reusable in your code.

Category
Tags

Copyright 2023-24 © Open Code