Lesson 7 - Functions

  • Python Functions

    A function is a block of code which only runs when it is invoked. The idea is to put some commonly or repeatedly done tasks together and make a function.
    You can pass data, known as parameters, into a function. A function can return data as a result.

    Creating a Function

    In Python a function is defined using the def keyword:


    def my_function():
      print(“Hello world”)

    Calling a Function

    To call a function, use the function name followed by parenthesis:


    def my_function():
      print(“Hello world”)

    Passing  parameter to a function
    The below function print_name(x),  takes x as a parameter and uses it inside the function

    def print_name(x):

    The print_name function is called by passing “John” as a parameter.  The print function prints John


    Returning data from a function

    The add number function below adds two numbers and return 

    def add(num1, num2):
         num3 = num1 + num2
         return num3

    num1  = 4;
    num2 = 8;
    result = add(num1, num2)
    print(f”The addition of {num1} and {num2} results {result}.”)