Python Logo

Week 4: Functions

What is a function?

Functions are a set of recallable instructions, that perform and action or return a value. are an important tool in programming that greatly increase the modularity and efficiency of your program. That means that a function isĀ **a piece of code written to carry out a specified task**. Its easier to think of them as mini-programs that perform more particular actions, similar to how a factory may create a product, there is smaller machinery which helps create part of the product before its final assembly.

Creating functions

Keywords

  • def- Define function keyword
  • return- Return variable value to global scope
  • Declaring function

    Functions follow the following format:

    
           def functionName(arguments)
               *code to be executed*
           
    Remember that in python indentation determines the scope. To ensure that the code to be executed is part of the function indent with 4 spaces or tab after defining the function. Here is an example:
    
           def demoFunction():
               print("This is a function")
           
    Functions will only run when called, you call a function by using its identifier and brackets to show that it is a function, e.g.
    
           demoFunction()
           //Expected result: This is a function
           
    Functions are defined

    Return statements

    In most cases your functions will have to return a value, be it the output of a mathematical operation or e something else. However variables defined in functions exist only in the functions scope, so they can not be called outside of the function, but that is why we have the return keyword. This keyword 'return's' a value from the function to its parent scope. e.g.:
    
           def  multiply(num1,num2):
                product=num1*num2
                return product
           Using the return keyword returns the value stored in the product variable ( which in this case we expect to be a number ) as the output of the function
           
           multiply(3,4)
           // outputs 12
           

    Other functions

    Arrow function

    Now the previous function we had made is not made to return an output of a particular type, but the type is inferred to be number because we define product with an arithmetic operation. However because the type of input is not specified, a string could be entered as an argument and this could render the whole function useless. In order to get around it, we can use more explicitly define the types of variables we would want this function to return and leave less up to type inference( see variables and expressions) we could use an arrow function to ensure that we get the intended output
    
           def multiply(num1, num2)->int:
               product=num1*num2
               return product
           
    A more type strict version of the previous function would be:
    
           def multiply(num1: int, num2: int)->int:
               product=num1#num2
               return product
           
    We can see the input types are defined in the brackets, num1: int This is declaring that num1 can only hold a numerical values and any other type of input will be rejected. However what is interesting is that an arrow is used to "direct" the output to the type integer. This types the output making it easier to deal with.

    Arrow function

    Lambda function are shorthand functions, usually used as inputs to higher order functions( a more advanced topic). These cannot be recalled as they aren't intended to be recalled. e.g.
     lambda  x: x/2
    Here x is the input and will be entered into the function, this can be a useful shorthand for functions e.g.
    
            myFunct=lambda x:x/2
            myFunct(4)
            // will return 1
           
    Here is an example of a higher order function:
    
           def div_list(funct, myList)
                divList=[]
                for item in myList:
                    new_item=funct(new_item)
                    divList.append(new_item)
               return(divList)
           myList=[1, 2, 3,  4]
           
           div_by_2=  div_list(lambda x: x/2, myList)
           print(div_by_2)
           // This should output the list divided by two
           
    The aforementioned example is a bit advanced, but should open your eyes to the possibilities in python.

    Scope and applicability of functions

    Function variables exist only within the function, if the variable was initialized outside the function then the identifier is already taken, however a variable initialized in the function cannot be used outsider the function unless it is returned to the global scope. When it comes to conditional/control structures, they follow a parent child relation ship when it comes to variable inheritance.

    Practices of good measure

    Practical Lab Exercises

    Now that you have an understanding of variables and expressions, it's time to apply this knowledge in practical scenarios. The following exercises will help reinforce your learning.

    Q&A and Review

    As you complete these exercises, it's important to review and clarify any concepts that are unclear. Use this section to revisit key ideas and ask questions.

    If you're uncertain about any topics or need further explanation, don't hesitate to reach out through the discussion forum or during the Q&A sessions.