Learn Python Programming functions with examples and explanations in 2024

Let us begin by going over the fundamentals of Python programming functions before advancing to more complex ideas.

Learn Python Programming functions with examples and explanations

Functions in Python:

What are Functions in Python programming?

A function is a block of organized, reusable code that performs a specific task. It takes inputs (arguments), processes them, and returns outputs. Functions provide modularity to your code, making it easier to understand, reuse, and maintain.

Why are Functions Used?

  • Modularity: Functions allow you to break down a complex problem into smaller, manageable pieces. Each function handles a specific task, promoting code reusability and maintainability.
  • Abstraction: Functions hide the implementation details of a particular task. You can use a function without needing to know how it works internally, focusing only on its inputs and outputs.
  • Code Organization: Functions help in organizing your code logically. Instead of writing a monolithic script, you can structure your code into smaller, meaningful functions, improving readability and debugging.
  • Debugging and Testing: With functions, you can isolate specific parts of your code for testing and debugging. This makes it easier to identify and fix errors.
  • Scoping: Functions introduce scope in Python, which means variables defined inside a function are only accessible within that function (unless explicitly specified otherwise). This helps prevent naming conflicts and unintended side effects.
  • Code Reusability: Once you’ve written a function to perform a certain task, you can reuse it multiple times throughout your program or even in other programs, saving time and effort.

How to Define and Use Functions in Python:


    def greet(name):
        return f"Hello, {name}!"
    message = greet("Alice")
    print(message)

# output: Hello, Alice!

In this example, greet is a function that takes one parameter (name) and returns a greeting message. When called with "Alice", it returns "Hello, Alice!".

Remember:

  • Functions are defined using the def keyword followed by the function name and parameters in parentheses.
  • The function body is indented and contains the code to perform the task.
  • You can add an optional docstring (enclosed in triple quotes) to describe what the function does.
  • Use the return statement to specify the value(s) to be returned by the function.
  • To call a function, simply use its name followed by parentheses, passing any required arguments.

Here are 30 examples that cover various aspects of Python functions, from basic usage to more advanced concepts like decorators and generators. Experiment with them to deepen your understanding!

I. Function without Parameters:

The provided code defines a function named greet that generates a greeting message, specifically “Hello Planet!”.

    def greet():
        return "Hello Planet!"

    # Calling the function
    print(greet())

# output: Hello Planet!

Here’s how it works:

  1. Function Definition:
    • def greet(): This function does not take any parameters.
  2. Greeting Generation:
    • Inside the function, it directly returns the string “Hello Planet!”.
  3. Calling the Function:
    • print(greet()): This line calls the greet function without any arguments. The function is invoked, and its return value, “Hello Planet!”, is printed to the console.
  4. Output:
    • The output of the print statement will be “Hello Planet!”, as the function greet returns this string when called.

II. Function with Parameters:

The provided code defines a function named greet that generates a greeting message for a person by their name.

    def greet(name):
        return f"Hello,  {name}!"

    # call the function
    print(greet("Alice"))

# output: Hello, Alice!

Here’s how it works:

  1. Function Definition:
    • def greet(name): This function takes one parameter name, representing the name of the person to be greeted.
  2. Greeting Generation:
    • Inside the function, it generates a greeting message using f-string formatting, where {name} is replaced by the provided name parameter.
  3. Calling the Function:
    • print(greet("Alice")): This line calls the greet function with the argument "Alice". The function then generates and prints the greeting message “Hello, Alice!”.
  4. Output:
    • The output of the print statement will be “Hello, Alice!”, as the function is called with the argument "Alice", which is used to generate the greeting message.

III. Function with the Default Parameter:

This code defines a function named greet that greets a person by their name, with a default greeting for “World” if no name is provided.

    def greet(name="World"):
        return f"Hello, {name}"

    # call the function
    print(greet())    # output: Hello, World
    print(greet("Alice"))   # output: Hello, Alice
  • def greet(name="World"):This line defines a function named greet with one parameter name. The parameter name has a default value of "World", meaning if no argument is passed when calling the function, "World" will be used as the value for name.
  • return f"Hello, {name}!": Inside the function, it constructs a greeting message using f-string formatting. If a value is provided for name, it will be used; otherwise, "World" (the default value) will be used. The constructed message is then returned by the function.

  • greet(): This line calls the greet function without providing any argument. Since no argument is provided, the default value "World" is used for the name parameter. The function returns "Hello, World!", which is then printed.
  • greet("Alice"): This line calls the greet function with "Alice" as the argument. The function overrides the default value of name with "Alice", and the function returns "Hello, Alice!", which is then printed.

  • The first print statement prints "Hello, World!" because no argument is provided, so the default value "World" is used.
  • The second print statement prints "Hello, Alice!" because "Alice" is provided as an argument, overriding the default value.

IV. Function with Multiple Parameters:

The provided code defines a function named add that computes the sum of two numbers a and b.

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

    # Call the function
    print(add(3,5))

Here’s how it works:

  1. Function Definition:
    • def add(a, b): This function takes two parameters a and b.
  2. Sum Calculation:
    • Inside the function, it computes the sum of a and b using the addition operator (+).
  3. Calling the Function:
    • print(add(3, 5)): This line calls the add function with a = 3 and b = 5.
    • The function adds the two numbers 3 and 5, resulting in 8.
  4. Output:
    • The output will be the result of the addition operation, which is 8 in this case.

V. Function with Multiple Return Values:

This code defines a function called square_and_cube that takes one parameter x. Inside the function, it calculates the square of x and the cube of x using the exponentiation operator (**). The function returns both the square and the cube as a tuple (x ** 2, x ** 3).

    def square_and_cube(x):
        return x ** 2, x ** 3

    # Call the fuction

    sq, cb = square_and_cube(3)
    print(sq)   # output: 9
    print(cb)   # output: 27

Then, the function is called with the argument 3, and the returned values are unpacked into variables sq and cb. Finally, it prints sq, which represents the square of 3, and cb, which represents the cube of 3. The output is 9 for the square and 27 for the cube.

VI. Function with Variable Number of Arguments (Arbitrary Arguments):

This code defines a function named average that takes a variable number of arguments (*args). Inside the function, it calculates the average of the provided arguments by summing them up (sum(args)) and dividing by the number of arguments (len(args)). If no arguments are provided (if args evaluates to False), it returns 0 to avoid division by zero.

Then, the function is called twice:

  1. average(2, 3, 4): It calculates the average of the numbers 2, 3, and 4, which is 3.0, and prints it.
  2. average(10, 20, 30): It calculates the average of the numbers 10, 20, and 30, which is 20.0, and prints it.

    def average(*args):
        return sum(args) / len(args) if args else 0

    # Call the function

    print(average(2,3,4))
    print(average(10,20,30))

Note:

In Python, the asterisk (*) before a parameter name, such as *args, is used to indicate that the function can accept a variable number of positional arguments. Here’s how it works:

  1. Variable Number of Arguments:
    • When you use *args as a parameter in a function definition, it allows the function to accept any number of positional arguments.
    • These arguments are collected into a tuple named args inside the function. This tuple contains all the positional arguments passed to the function.
  2. Flexibility:
    • Using *args provides flexibility because you can call the function with any number of arguments, including zero.
    • It allows you to define functions that can operate on a variable number of inputs without needing to specify them individually.
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
my_function()              # Output: (no output, as no arguments are passed)

Use Cases:

  • When you’re not sure how many arguments will be passed to the function.
  • When you want to create a generic function that can operate on different numbers of inputs.
  • When you want to pass a variable number of arguments to another function within your function.

VII. Function with Keyword Arguments:

Keyword arguments allow you to specify arguments by parameter name, regardless of their order.


    def person_info(name, age):
        return f"Name: {name}, Age: {age}"

    # Call the function

    print(person_info(age=30, name="Alice"))

Here’s how it works:

This code defines a function named person_info that takes two parameters: name and age. Inside the function, it constructs a string containing information about the person’s name and age using f-string formatting.

Then, the function is called with named arguments:

  • age=30: This assigns the value 30 to the age parameter.
  • name="Alice": This assigns the value "Alice" to the name parameter.

Even though the order of the arguments is different from the function definition, the function is called using named arguments, so the order doesn’t matter.

This demonstrates how named arguments can be used to call a function in Python, allowing for more readable and flexible function calls.

VIII. Function with Default and Arbitrary Arguments:

The provided code defines a function named describe_person that generates a description of a person with their name, age, and additional optional attributes provided as keyword arguments (kwargs).


    def describe_person(name, age=25, **kwargs):
        info = f"Name: {name}, Age: {age}"
        for key, value in kwargs.items():
            info += f", {key}: {value}"
        return info

    # Call the function
    print(describe_person("Bob",job="Engineer"))
  1. Function Definition:
    • def describe_person(name, age=25, **kwargs): This function takes three parameters: name (mandatory), age (optional with a default value of 25), and **kwargs (arbitrary keyword arguments).
  2. Description Generation:
    • Inside the function, a string variable info is initialized with the person’s name and age.
    • Then, a loop iterates over the arbitrary keyword arguments (kwargs) provided to the function.
    • For each keyword argument, the key-value pair is appended to the info string, separated by a comma and space.
  3. Returning the Description:
    • The function returns the info string, which contains the person’s name, age, and any additional attributes provided as keyword arguments.
  4. Calling the Function:
    • print(describe_person("Bob", job="Engineer")): This line calls the describe_person function with the name "Bob" and the additional keyword argument job="Engineer".
    • The function generates a description of the person with the provided information and any additional attributes.
    • The resulting description is then printed to the console.
  5. Output:
    • The output will be the description of the person, including their name, age, and job (if provided as a keyword argument).
    • For example, "Name: Bob, Age: 25, job: Engineer".
def my_function(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

my_function(name="Alice", age=30, city="New York")

Arbitrary keyword arguments:
Arbitrary keyword arguments in Python functions refer to the ability to accept an arbitrary number of keyword arguments in a function call. This is achieved by using the double asterisk (**) before a parameter in the function definition.

Syntax:

def my_function(**kwargs):
    # Function body

Here’s a breakdown:

  • The parameter **kwargs stands for “keyword arguments” and collects all the keyword arguments passed to the function into a dictionary.
  • Each keyword argument consists of a key-value pair, where the key is the parameter name and the value is the argument value.
  • Inside the function, you can access these keyword arguments using dictionary syntax (kwargs[key]).

IX. Function with Docstring:

This code defines a function named greet that takes one parameter name. The function returns a greeting message using the provided name.

    def greet(name):
        """Function to greet a person by name"""
        return f"Hello, {name}"

    # Access the docstring 
    print(greet.__doc__)

Here’s a breakdown:

  1. Function Definition:
    • def greet(name): This function takes a single parameter name, representing the name of the person to greet.
  2. Docstring:
    • """Function to greet a person by name""": This is a docstring, enclosed within triple quotes ("""). It provides a brief description of the function’s purpose, which is to greet a person by name.
  3. Return Statement:
    • return f"Hello, {name}": This line returns a formatted string that greets the person by interpolating their name into the greeting message.
  4. Accessing the Docstring:
    • print(greet.__doc__): This line accesses the docstring of the greet function using the special attribute __doc__.
    • The __doc__ attribute contains the docstring associated with the function, and it is printed to the console.
  5. Output:
    • The output will be the docstring text: "Function to greet a person by name", as it describes the purpose of the greet function.

X. Recursive Function:

This code defines a recursive function named factorial to compute the factorial of a non-negative integer n.

    def factorial(n):
        return 1 if n == 0 else n * factorial(n-1)

    # Call the function
    print(factorial(5))

Here’s how it works:

  1. Function Definition:
    • def factorial(n): This function takes an integer n as input.
  2. Base Case and Recursion:
    • The function uses recursion to compute the factorial of n.
    • The base case of the recursion is when n equals 0. In this case, the function returns 1, as the factorial of 0 is 1.
    • If n is not 0, the function recursively calls itself with the argument n-1 and multiplies the result by n.
  3. Calling the Function:
    • print(factorial(5)): This line calls the factorial function with 5 as the argument.
    • The function recursively computes the factorial of 5, which is 5 * 4 * 3 * 2 * 1, and returns the result.
  4. Output:
    • The output will be the factorial of 5, which is 120.

XI. Anonymous Function (Lambda Function):

This code demonstrates the use of lambda functions in Python to create an anonymous function that doubles its input.This code demonstrates the use of lambda functions in Python to create an anonymous function that doubles its input.

    double = lambda x: x * 2

    # Call the function
    print(double(5))

Here’s a breakdown of the code:

  1. Lambda Function Definition:
    • double = lambda x: x * 2: This line defines a lambda function that takes a single parameter x and returns x * 2, effectively doubling the value of x.
    • Lambda functions are anonymous functions defined using the lambda keyword, allowing for quick creation of simple functions without the need for a formal def statement.
  2. Calling the Lambda Function:
    • print(double(5)): This line calls the lambda function stored in the variable double with the argument 5.
    • The lambda function doubles the input value 5, resulting in 10.
    • The result, 10, is then printed to the console.

XII. Function as a Parameter:

This code demonstrates the use of higher-order functions in Python, specifically by defining two functions: square and apply.

    def square(x):
        return x ** 2

    def apply(func, n):
        return func(n)

    # Call the function
    print(apply(square, 3))

Here’s a breakdown of the code:

  1. square Function:
    • def square(x): This function takes a single parameter x and returns the square of x using the exponentiation operator (**).
  2. apply Function:
    • def apply(func, n): This function takes two parameters: func, which represents another function, and n, which is a value to be passed to the function func.
    • Inside the apply function, it calls the function func with the argument n and returns the result.
  3. Calling the apply Function:
    • print(apply(square, 3)): This line calls the apply function with square as the function argument and 3 as the value to be squared.
    • The apply function calls the square function with 3 as the argument, which computes the square of 3.
    • The result, which is 9 (the square of 3), is then printed to the console.

XIII. Function Returning Function:

This function returns another function.

    def get_multiplies(n):
        def multiplier(x):
            return x * n
        return multiplier

    # Call the function
    times3 = get_multiplies(3)
    print(times3(5))

Here’s how it works:

This code defines a function called get_multiplies that takes a parameter n. Inside get_multiplies, another nested function multiplier is defined, which takes a parameter x and returns the result of x * n.

When get_multiplies is called with an argument, say 3, it returns the nested multiplier function with n set to 3. This returned function is assigned to the variable times3.

Finally, times3 is called with an argument 5, which applies the nested multiplier function with n=3 to x=5, resulting in 5 * 3 = 15. The result, 15, is printed to the console.

In essence, get_multiplies returns a function that can multiply its argument by the value of n passed to get_multiplies, allowing for the creation of customized multiplication functions.

XIV. Decorator Function:

Decorators are functions that modify the behavior of another function.

    def decoder(func):
        def wrapper():
            print("Before function execution")
            func()
            print("After function execution")
        return wrapper


    def greet():
        print("Hello!")

    # Call the function
    greet()

Here’s how it works:

  1. decoder(func): This function takes another function func as an argument. Inside decoder, a nested function wrapper is defined. wrapper prints “Before function execution”, then calls the original function func, and finally prints “After function execution”. wrapper is then returned by decoder.
  2. greet(): This is a simple function that prints “Hello!”.

When greet() is called directly, it prints “Hello!” to the console.

The decoder function allows us to modify the behavior of greet() by wrapping it inside another function. However, in the provided code, the decoder function is defined but not used to modify the behavior of greet(). Thus, when greet() is called directly, it simply prints “Hello!” without any additional behavior before or after its execution.

XV. Generator Function:

Generator functions allow you to generate a sequence of values over time.

    def countdown(n):
        while n > 0:
            yield n
            n -= 1

    # Call the function 
    for i in countdown(5):
        print(i)

Here’s how it works:

  1. Function Definition:
    • def countdown(n):: This line defines the countdown function that takes one parameter n.
  2. Generator Logic:
    • while n > 0:: This while loop continues as long as n is greater than 0.
    • yield n: Inside the loop, the current value of n is yielded (returned) by the generator, allowing the caller to access it without terminating the function’s execution.
    • n -= 1: The value of n is decremented by 1 in each iteration of the loop.
  3. Function Call:
    • for i in countdown(5):: This line calls the countdown function with 5 as the starting point.
    • for loop iterates over the values yielded by the countdown generator, assigning each value to i.
    • Inside the loop, each yielded value (n) is printed.
  4. Output:
    • The loop prints the numbers generated by countdown(5) in reverse order, starting from 5 and counting down to 1.

XVI. Function with Annotations:

Annotations provide metadata about the types of function parameters and return value.

This code defines a function named add that takes two parameters a and b, both of which are annotated as int (integer types), and specifies that the return type of the function is also int.

Annotations in Python are used to provide additional information about the types of parameters and return values of functions, but they do not enforce type checking at runtime. They serve as documentation and can be accessed using the __annotations__ attribute of the function.

The print(add.__annotations__) statement accesses the annotations of the add function and prints them to the console.

    def add(a: int, b: int) -> int:
        return a+b

    # Access the annotations
    print(add.__annotations__)

output:

{'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}

XVII. Function to Filter Odd Numbers:

This function filters out the odd numbers from a list.

This code defines a function named filter_odd that takes a list of numbers as input. Inside the function, it creates a new list using a list comprehension that includes only the numbers from the input list that are odd (i.e., have a remainder of 1 when divided by 2).

Then, it calls the filter_odd function with the list [1, 2, 3, 4, 5, 6, 7]. The function filters out the odd numbers from the input list and returns a new list containing only the odd numbers.

Finally, the resulting list [1, 3, 5, 7] is printed to the console.

In summary, the function filter_odd filters out the odd numbers from a given list and returns a new list containing only those odd numbers.


    def filter_odd(numbers):
        return[num for num in numbers if num % 2 != 0]

    # Call the function
    print(filter_odd([1,2,3,4,5,6,7]))

# output: [1, 3, 5, 7]

XVIII. Function to Map Square of Numbers:

This function maps the square of numbers in a list.

This code defines a function named square_numbers that takes a list of numbers as input. Inside the function, it creates a new list using a list comprehension. For each number num in the input list, it calculates its square (num ** 2) and adds it to the new list.

Then, it calls the square_numbers function with the list [1, 2, 3, 4, 5, 6]. The function calculates the square of each number in the input list and returns a new list containing the squared numbers.

Finally, the resulting list [1, 4, 9, 16, 25, 36] is printed to the console.

    def square_numbers(numbers):
        return [num ** 2 for num in numbers]

    # Call the function
    print(square_numbers([1,2,3,4,5,6]))

# output: [1, 4, 9, 16, 25, 36]

XIX. Function to Reduce a List to a Single Value:

This function reduces a list of numbers to a single value by multiplying them together.


    from functools import reduce

    def multiply(numbers):
        return reduce(lambda x,y: x*y, numbers)

    # Call the function
    print(multiply([1,2,3,4,5]))

Here’s how it works:

  1. Importing the reduce Function:
    • from functools import reduce: This line imports the reduce function from the functools module.
  2. Defining the multiply Function:
    • def multiply(numbers): This function takes a list of numbers as input.
    • Inside the function, the reduce function is used with a lambda function to multiply all the numbers together.
    • The lambda function takes two arguments x and y and returns their product (x * y).
    • The reduce function then applies this lambda function cumulatively to the elements of the input list, resulting in the product of all the numbers.
  3. Calling the Function:
    • print(multiply([1,2,3,4,5])): This line calls the multiply function with the list [1, 2, 3, 4, 5].
    • The function calculates the product of all the numbers in the list and prints the result.
  4. Output:
    • The output will be the product of all the numbers in the list, which is 120 in this case (1 * 2 * 3 * 4 * 5).

XX. Function to Find the Maximum Element:

This function finds the maximum element in a list.

This code defines a function named find_max that takes a list of numbers as input. Inside the function, it uses the built-in max() function to find the maximum value among the numbers in the input list.


def find_max(numbers):
    return max(numbers)

# Call the function 
print(find_max([2,1,55,44,8,56,45,54]))

Here’s how it works:

  1. Defining the find_max Function:
    • def find_max(numbers): This function takes a list of numbers as input.
  2. Finding the Maximum Value:
    • Inside the function, the max() function is used with the input list numbers as its argument.
    • The max() function returns the largest value from the list.
  3. Calling the Function:
    • print(find_max([2,1,55,44,8,56,45,54])): This line calls the find_max function with the list [2,1,55,44,8,56,45,54].
    • The function finds the maximum value from the list and prints it.
  4. Output:
    • The output will be the maximum value from the list, which is 56 in this case.

XXI. Function to Find Minimum Element:

This function finds the minimum element in a list.

This code defines a function named find_min that takes a list of numbers as input. Inside the function, it uses the built-in min() function to find the minimum value among the numbers in the input list.


    def find_min(numbers):
        return min(numbers)

    # Call the function 
    print(find_min([2,1,55,44,8,56,45,54]))

Here’s how it works:

  1. Defining the find_min Function:
    • def find_min(numbers): This function takes a list of numbers as input.
  2. Finding the Minimum Value:
    • Inside the function, the min() function is used with the input list numbers as its argument.
    • The min() function returns the smallest value from the list.
  3. Calling the Function:
    • print(find_min([2,1,55,44,8,56,45,54])): This line calls the find_min function with the list [2,1,55,44,8,56,45,54].
    • The function finds the minimum value from the list and prints it.
  4. Output:
    • The output will be the minimum value from the list, which is 1 in this case.

XXII. Function to Check if a Number is Prime:

This code defines a function named is_prime that checks whether a given number n is prime or not. Here’s a brief explanation of how it works:


def is_prime(n):
    if n <= 1:
        return False
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False
    return True

# Call the function
print(is_prime(11))

Here’s how it works:

  1. Function Definition:
    • def is_prime(n): This function takes an integer n as input.
  2. Checking for Non-Prime Conditions:
    • The function first checks if the input number n is less than or equal to 1. If it is, it returns False, as numbers less than or equal to 1 are not considered prime.
  3. Iterating for Prime Check:
    • If n is greater than 1, the function iterates over a range starting from 2 up to the square root of n (inclusive).
    • For each number i in this range, it checks if n is divisible evenly by i. If it is, n is not prime, so the function returns False.
    • If no divisors are found in the loop, the function returns True, indicating that n is prime.
  4. Calling the Function:
    • print(is_prime(11)): This line calls the is_prime function with the number 11.
    • The function checks whether 11 is prime or not and prints the result.
  5. Output:
    • Since 11 is a prime number, the function returns True, and the output will be True.

XXIII. Function to Check if a String is Palindrome:

This function checks if a string is a palindrome.


    def is_palindrome(s):
        return s == s[::-1]

    # Call the function
    print(is_palindrome("radar"))

Here’s how it works:

  • The word “radar” is a palindrome because it reads the same forwards and backwards.
  • The phrase “A man, a plan, a canal, Panama” is a palindrome because, after removing spaces and punctuation, it reads the same forwards and backwards.
  • The number “12321” is a palindrome because its digits read the same forwards and backwards.

Palindrome: A palindrome is a word, phrase, number, or other sequence of characters that reads the same forwards and backwards. In other words, if you reverse the characters of a palindrome, you get the same sequence of characters. Palindromes are commonly used in various contexts, including words (e.g., “radar”, “level”), and numbers (e.g., “12321”, “9009”).

XXIV. Function to Convert Fahrenheit to Celsius:

This code defines a function named fahrenheit_celsius that converts a temperature value from Fahrenheit to Celsius.


    def fahrenheit_celsius(fahrenheit):
        return (fahrenheit - 32) * 5/9

    # Call the function
    print(fahrenheit_celsius(32))

Here’s how it works:

  1. Function Definition:
    • def fahrenheit_celsius(fahrenheit): This function takes a temperature value in Fahrenheit as input.
  2. Conversion Formula:
    • Inside the function, it applies the conversion formula (fahrenheit - 32) * 5/9 to convert the temperature from Fahrenheit to Celsius.
    • The formula subtracts 32 from the Fahrenheit value to get the temperature difference in Fahrenheit degrees, then multiplies by 5/9 to convert to Celsius.
  3. Calling the Function:
    • print(fahrenheit_celsius(32)): This line calls the fahrenheit_celsius function with the Fahrenheit temperature value 32.
    • The function computes the equivalent Celsius temperature and prints the result.
  4. Output:
    • The output will be the equivalent Celsius temperature of 32 degrees Fahrenheit, which is 0 degrees Celsius.

XXV. Function to Calculate Simple Interest:

This code defines a function named simple_interest that calculates the simple interest for a given principal amount, interest rate, and time period.


    def simple_interest(principal, rate,time):
        return (principal * rate * time) / 100

    # Call the function
    print(simple_interest(1000,5,2))

Here’s how it works:

  1. Function Definition:
    • def simple_interest(principal, rate, time): This function takes three parameters: principal (the initial amount of money), rate (the interest rate per period), and time (the number of periods).
  2. Interest Calculation:
    • Inside the function, it calculates the simple interest using the formula: (principal * rate * time) / 100.
    • It multiplies the principal amount (principal) by the interest rate (rate) and the time period (time), and then divides the result by 100 to get the simple interest.
  3. Calling the Function:
    • print(simple_interest(1000, 5, 2)): This line calls the simple_interest function with a principal amount of 1000, an interest rate of 5%, and a time period of 2 years.
    • The function computes the simple interest using these parameters and prints the result.
  4. Output:
    • The output will be the calculated simple interest based on the provided principal, interest rate, and time period.

XXVI. Function to Calculate Compound Interest:

This code defines a function named compound_interest that calculates the compound interest for a given principal amount, interest rate, and time period.

    def compound_interest(principal, rate, time):
        return principal * ((1 + rate / 100) ** time - 1)

    # Call the function
    print(compound_interest(1000, 5, 2)) 

Here’s how it works:

  1. Function Definition:
    • def compound_interest(principal, rate, time): This function takes three parameters: principal (the initial amount of money), rate (the interest rate per period), and time (the number of periods).
  2. Interest Calculation:
    • Inside the function, it calculates the compound interest using the formula: principal * ((1 + rate / 100) ** time - 1).
    • It first divides the interest rate (rate) by 100 to convert it to a decimal percentage.
    • It then calculates the compound interest using the formula for compound interest: principal * ((1 + rate / 100) ** time - 1).
  3. Calling the Function:
    • print(compound_interest(1000, 5, 2)): This line calls the compound_interest function with a principal amount of 1000, an interest rate of 5%, and a time period of 2 years.
    • The function computes the compound interest using these parameters and prints the result.
  4. Output:
    • The output will be the calculated compound interest based on the provided principal, interest rate, and time period.

XXVII. Function to Reverse a List:

This code defines a function named reverse_list that reverses the order of elements in a given list.

    def reverse_list(lst):
        return lst[::-1]

    # Call the function
    print(reverse_list([1,2,3,4,5,6]))

Here’s how it works:

  1. Function Definition:
    • def reverse_list(lst): This function takes a list lst as input.
  2. Reversing the List:
    • Inside the function, it returns the input list lst with slicing notation lst[::-1].
    • This slicing notation creates a reversed copy of the list by starting from the end (-1) and going backwards to the beginning of the list (::-1).
  3. Calling the Function:
    • print(reverse_list([1,2,3,4,5,6])): This line calls the reverse_list function with the list [1,2,3,4,5,6].
    • The function reverses the order of elements in the list and prints the result.
  4. Output:
    • The output will be the reversed list, which in this case will be [6, 5, 4, 3, 2, 1].

XXVIII. Function to Count Occurrences of an Element in a List:

This code defines a function named count_occurrences that counts the number of occurrences of a specific target element in a given list.


    def count_occurrences(lst, target):
        return lst.count(target)

    # Call the function
    print(count_occurrences([1,2,2,3,4,2], 2))

Here’s how it works:

  1. Function Definition:
    • def count_occurrences(lst, target): This function takes two parameters: lst (the list in which occurrences are counted) and target (the element whose occurrences are counted).
  2. Counting Occurrences:
    • Inside the function, it uses the count() method of lists to count the occurrences of the target element in the list lst.
    • The count() method returns the number of occurrences of the specified element in the list.
  3. Calling the Function:
    • print(count_occurrences([1,2,2,3,4,2], 2)): This line calls the count_occurrences function with the list [1,2,2,3,4,2] and the target element 2.
    • The function counts the occurrences of 2 in the list and prints the result.
  4. Output:
    • The output will be the number of occurrences of the target element 2 in the list [1,2,2,3,4,2], which is 3 in this case.

XXIX. Function to Flatten a Nested List:

This code defines a function named is_leap_year that determines whether a given year is a leap year or not based on the rules of the Gregorian calendar.

    def is_leap_year(year):
        return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)

    # Call the function
    print(is_leap_year(2024))

Here’s how it works:

  1. Function Definition:
    • def is_leap_year(year): This function takes a single parameter, year, representing the year to be checked.
  2. Leap Year Logic:
    • The function uses a boolean expression to determine whether the given year is a leap year or not.
    • It checks two conditions:
      • (year % 4 == 0 and year % 100 != 0): This condition checks if the year is divisible by 4 but not by 100. If this condition is true, it indicates a leap year.
      • or (year % 400 == 0): This condition checks if the year is divisible by 400. If true, it overrides the previous condition and also indicates a leap year.
    • If either of these conditions is true, the function returns True, indicating that the year is a leap year. Otherwise, it returns False.
  3. Calling the Function:
    • print(is_leap_year(2024)): This line calls the is_leap_year function with the year 2024.
    • The function evaluates whether 2024 meets the criteria for a leap year and prints the result.
  4. Output:
    • The output will be True if the given year is a leap year, and False otherwise.
    • In this case, 2024 is a leap year, so the output will be True.

XXX. Function to Calculate the Fibonacci Series:

This code defines a function named fibonacci that generates a Fibonacci sequence up to the nth term specified by the input parameter n.

    def fibonacci(n):
        fib_series = [0,1]
        while len(fib_series) < n:
            fib_series.append(fib_series[-1] + fib_series[-2])
        return fib_series
    # Call the function 
    print(fibonacci(8))

Here’s how it works:

  1. Function Definition:
    • def fibonacci(n): This function takes a single parameter, n, representing the number of terms in the Fibonacci sequence to generate.
  2. Fibonacci Series Initialization:
    • Inside the function, a list named fib_series is initialized with the first two terms of the Fibonacci sequence, [0, 1].
  3. Generating Fibonacci Sequence:
    • A while loop is used to generate additional terms of the Fibonacci sequence until the length of fib_series reaches n.
    • Within each iteration of the loop, the next term is calculated by adding the last two terms of the sequence (fib_series[-1] and fib_series[-2]), and the result is appended to fib_series.
  4. Returning the Fibonacci Sequence:
    • Once the loop completes and the desired number of terms is reached, the function returns the fib_series list containing the Fibonacci sequence up to the nth term.
  5. Calling the Function:
    • print(fibonacci(8)): This line calls the fibonacci function with n = 8, indicating that the Fibonacci sequence up to the 8th term should be generated.
    • The function calculates the Fibonacci sequence and prints the resulting list.
  6. Output:
    • The output will be the Fibonacci sequence [0, 1, 1, 2, 3, 5, 8, 13], which consists of eight terms.

Leave a Reply