Functions and Parameters: BEHIND THE SCENES!


FUNCTIONS AND PARAMETERS


Hi! Welcome to this section. We will discuss FUNCTIONS AND PARAMETERS. This topic is vital for your programming future and you will use them very frequently in problem sets! :-)
Let’s get started!


  • You can think of functions as “compartments” inside your code that can interact with the world that surrounds them, but that have special properties of their own, like their own scope (they can have their own set of variables that can’t be used outside the body of the function)



    Accessing docstrings

    In the lecture video you can see that you can also add something called a docstring (the green text in ''' '''' at the top of the function body). You can access them by using:
    functionName.__doc__
    They are extremely helpful for maintaining your code. They help you remember the type of your parameters, the logic used inside the function and the value returned by the function.

    Parameters

    Now, let's discuss parameters, very important elements of functions. You will use them extremely frequently, so it's very important that you understand how they work.




    Actual Parameters


    When you call a function, you must provide what are called “Actual parameters” or “Arguments” by giving values for each of the formal parameters defined in the function definition.
    By just giving values and separating them by commas, you are assigning each one of those values to their corresponding parameter position. The first argument is assigned to the first parameter; the second argument is assigned to the second parameter, and so on…


    Here you can see this function defined on Python's Shell and called using the actual parameters (or arguments) shown in the slides. You can see that it prints the statement inside the function, but replaces the variables param1 and param2 with the values we passed as input.


    How many formal parameters can I define?

    You can set as many parameters as you need, and they can be any data type, even functions! (This is called Higher Order programming; we will discuss it later in the course)

    (Or you can also use default values, in which case, you don't need to specify a value for that formal parameter, this will be discussed later in the lecture.)

    Hope it helps!
    If you have any questions, your classmates and Community TAs will always be there to help you.
    Estefania.

    Comments