Online-Academy
Look, Read, Understand, Apply

Functions-ii

Functions

A function is a block of reusable code that performs a specific task. It helps in code reusability, readability, and modularity.

    Syntax for function:
    def function_name():
        # code

    
    # Function without arguments:
    def show():
        print("This function does not take anything!")    

    # Function with arguments: a function can take one or more arguments
    def add(a,b,c,d):
        sum:int = a + b + c+ d
        print("Sum: ",sum)

    # Function can return a value
    def multiply(a, b):
        return a * b

    result = multiply(4, 5)
    print(result)

    # Function with default argument: If function is called without argument default value, here "Everest", will be used for 
    # argument name
    def mount(name="Everest"):
        print("Hello", name)

    mount()
    mount("Lhoste")

    Function with Keyword arguments:
        
    def student(name, age):
        print(name, age)

    student(age=20, name="Ram")
    
    Function  with variable-length arguments: Any number of arguments can be supplied. 
    def total(*numbers):
        sum = 0
        for n in numbers:
            sum += n
        return sum

    print(total(1, 2, 3, 4))

    **kwargs (Keyword arguments):
    def details(**info):
        for key, value in info.items():
            print(key, ":", value)

    details(name="Sita", age=22, city="Kathmandu")

    # Calling function from another function:
    def square(x):
        return x * x

    def cube(x):
        return square(x) * x

    print(cube(3))

    In Python a function can return more than one value :
    def calculate(a, b):
        return a + b, a - b, a * b

    s, d, m = calculate(10, 5)
    print(s, d, m)
    
    Lambda function: one liner for simple tasks:
    square = lambda x: x * x
    print(square(6))

     Recursive function: A function calling itself:
    def factorial(n):
        if n == 1:
            return 1
        return n * factorial(n - 1)

    print(factorial(5))

    Providing list (data structure: collection of elements) as arguments
    def average(numbers):
        return sum(numbers) / len(numbers)

    print(average([10, 20, 30]))
    
    Function as parameter: In Python function can be passed as parameter to another function    
    def operate(a, b, func):
        return func(a, b)

    def add(x, y):
        return x + y

    print(operate(3, 4, add))

    Function to check if a number of even or odd
    def even_odd(n):
        if n % 2 == 0:
            return "Even"
        return "Odd"

    print(even_odd(7))

    Function to check if a number is prime
    
    def is_prime(n):
        if n <= 1:
            return False
        for i in range(2, n):
            if n % i == 0:
                return False
        return True

    print(is_prime(11))