Functions Fundamentals

Introduction

A function is a section of code that performs an action. You create a function by writing code in a Python module (a simple text-based document that contains code). The fundamental formula to create a function is:

def function-name(...):
    . . .

To create a function, start with the def keyword.

Practical LearningPractical Learning: Starting a Project

  1. Start Microsoft Visual Studio
  2. Create a new Python Application named LoanEvaluation2
  3. In the empty default module, type the following lines of code:
    loan_amount   = 4750
    interest_rate = 14.50  # %
    periods       = 42           # Number of months
    
    print("Loan Amount:   ", loan_amount)
    print("Interest Rate: ", interest_rate, "%")
    print("Periods:       ", periods, 'months')
    
    print("==================================")

The Name of a Function

When creating a function, the def keyword is followed by a name. The name follows the same options you would apply to the name of a variable.

The Parentheses of a Function

The name of a function is followed by parentheses. The parentheses of a function offer many options. To start, the parentheses can be empty. Most of the time, you will write the parentheses on the same line as the name of the function.

The parentheses of a function are followed by a colon (:).

The Body of a Function

The body of a function follows the line after the colon. You will write the code associated with the function starting on the line after the closing of the parentheses and the colon.

Indentation

As seen with conditional statements, indentation consists of pushing a line of code to the right. That indentation is done with regards to the previous line of code. As seen with conditional statements, the code of a function must be indented, usually four characters to the right. This can be illustrated as follows:

def function-name():
    continuation

In this case, all the lines of code that belong to the same group are indented at the same level:

def function-name():
    line-1
    line-2
    line-n

In the same way, any line of code that belongs to another dependent line of code must be indented. Here are illustrations:

def function-name():
    dependent-1-level-1
    dependent-2-level-1
        subdependent-1-level-1
        subdependent-2-level-1
    dependent-3-level-1
        sub-dependent-1-level-1
        sub-dependent-2-level-1
            sub-dependent-1-level-1
            sub-dependent-2-level-1

In some computer languages (like C-based languages (C#, Java, C++, JavaScript)), indentation of the body of a function (and of a conditional statement) is only used to make code easy to read (which is also the case for languages like Visual Basic, TypeScript, etc). In some other languages like F#, indentation is an integral part of the code. This means that, in those languages, indentation is required. In the same way, in Python, code indentation is required.

When defining a function, you can write each parenthesis on its own line. The opening parenthesis can be written on the first line. If the closing parenthesis is written on the next line, it must be indented. This would be done as follows:

def calculate(
    ):
    . . .

If you want, you can write the opening parenthesis on the line that follows the name of the function. In that case, the parenthesis must be indented. Here is an example:

def calculate
     ():
     . . .

Or like this:

def calculate
    (
    ):
    . . .

Defining or Implementing a Function

When you create a function and write its code, you are said to define or implement the function.

Practical LearningPractical Learning: Defining a Function

Calling a Function

After creating/defining/implementing a function, you can use it. Using a function is referred to as calling the function. To do this, in the section of code where you need the result of the function, type the name of the function followed by parentheses. Normally, most functions are called from outside their body (the exception is a category of functions named recursive functions: a recursive function is a function that calls itself).

Creating many Functions

A typical application uses many functions. As a result, you can create as many functions as you need. If you create functions in a document, the compiler will access them in the order they are called, which is usually different from the order the functions were created.

Practical LearningPractical Learning: Calling a Function

  1. To call the function, change the document as follows:
    def process_loan():
        loan_amount = 4750
        interest_rate = 14.50  # %
        periods = 42           # Number of months
    
        print("Loan Amount:", loan_amount)
        print("Interest Rate:", interest_rate, "%")
        print("Periods:", periods)
    
    process_loan()
    print("==================================")
  2. To execute the project and see the result, on the main menu, click Debug -> Start Without Debugging. This would produce:
    Loan Amount: 4750
    Interest Rate: 14.5
    Periods: 42
    ==================================
    Press any key to continue . . .
  3. Press Enter to close the window and return to your programming environment

The Data Type of a Local Variable

If you declare a (some) variable(s) in the body of a function, if you want, you can specify its (their) data type(s).

Practical LearningPractical Learning: Setting Data Types

  1. Change the variables in the function as follows:
    def process_loan():
        loan_amount : float = 18685
        interest_rate : float = 9.95 # %
        periods : int   = 60 # Number of months
    
        print("Loan Amount:", loan_amount)
        print("Interest Rate:", interest_rate, "%")
        print("Periods:", periods)
    
    process_loan()
    print("==================================")
  2. To execute the project and see the result, on the main menu, click Debug -> Start Without Debugging. This would produce:
    Loan Amount: 18685
    Interest Rate: 9.95 %
    Periods: 60
    ==================================
    Press any key to continue . . .
  3. Press Enter to close the window and return to your programming environment
  4. For an example of requesting values in the body of a function, change the code as follows:
    def process_loan():
        print("Watts' A Loan")
        print("============================================")
        print("Enter the information to set up the loan")
        loan_amount = float(input("Loan Amount:      "))
        interest_rate : float = float(input("Interest Rate:    "))
        periods : int = int(input("Number of months: "))
    
        iRate           : float = interest_rate / 100.00
        years           : float = periods / 12
        interest_amount : float = loan_amount * iRate * years
        future_value    : float = loan_amount + interest_amount
    
        print("============================================")
        print("\tWatts' A Loan")
        print('--------------------------------------------')
        print(f"Loan Amount:      {loan_amount}")
        print(f"Interest Rate:    {interest_rate:.2f}%")
        print(f"Periods:          {periods} Months")
        print('-------------------------------------------')
        print(f"Interest Amount:  {interest_amount:.2f}")
        print(f"Future Value:     {future_value:.2f}")
    
    process_loan()
    print("===========================================")
  5. To execute and test the application, on the main menu, click Debug -> Start Without Debugging
  6. When the loan amount is requested, type 1850 and press Enter
  7. When the interest rate is requested, type 16.85 and press Enter
  8. When the period is requested, type 32 and press Enter
    Watts' A Loan
    ============================================
    Enter the information to set up the loan
    Loan Amount:      1850
    Interest Rate:    16.85
    Number of months: 32
    ============================================
            Watts' A Loan
    --------------------------------------------
    Loan Amount:      1850.0
    Interest Rate:    16.85%
    Periods:          32 Months
    -------------------------------------------
    Interest Amount:  831.27
    Future Value:     2681.27
    ===========================================
    Press any key to continue . . .
  9. To close the window, press Enter and return to your programming environment

A Function with a Parameter

Introduction

As stated in our introduction, a function is a section of code that performs a job. In many cases, a function can use only its local values. In some cases, if you want a function to perform a job based on a certain value that doesn't depend on the function itself, you may have to provide that value to the function. To make this possible, when creating the function, type a name for the value in the parentheses of the function. Here is an example:

def display(value):
    # . . .

A Parameter

The name you write in the parentheses of a function, when defining the function, is called a parameter. After putting a name in the parentheses of a function, in the body of the function, you can use the parameter anyway you like. For example, you can display the value of that parameter by writing it in the parentheses of print(). Here is an example:

def send_message(msg):
    print(msg)

In the same way, you can involve the parameter in an expression.

Calling a Parameterized Function

When you call a function that has a parameter, type the name of the function and its parentheses. In the parentheses, type a value for the parameter. Here is an example:

def send_message(msg):
    print(msg)

send_message("Please remember to submit your time sheet."))

This would produce:

Please remember to submit your time sheet.
Press any key to continue . . .

Practical LearningPractical Learning: Creating a Function with Parameter

An Argument

A value you provide in the parentheses of a function is called an argument. When you call a function and provide a value in its parentheses, you are said to pass an argument to the function.

Practical LearningPractical Learning: Passing an Argument to a Function

  1. To call functions and pass an argument to them, change the document as follows:
    def process_loan():
        print("Watts' A Loan")
        print("============================================")
        print("Enter the informaiton to set up the loan")
        loan_amount = float(input("Loan Amount:      "))
        interest_rate : float = float(input("Interest Rate:    "))
        periods : int = int(input("Number of months: "))
    
        iRate           : float = interest_rate / 100.00
        years           : float = periods / 12
        interest_amount : float = loan_amount * iRate * years
        future_value    : float = loan_amount + interest_amount
    
        print("============================================")
        print("\tWatts' A Loan")
        print('--------------------------------------------')
        showPrincipal(loan_amount)
        showInterestRate(interest_rate)
        showPeriods(periods)
        print('-------------------------------------------')
        showAmount(interest_amount)
        showFutureValue(future_value)
    
    def showPrincipal(a):
        print(f"Loan Amount:      {a}")
    
    def showInterestRate(b):
        print(f"Interest Rate:    {b:.2f}%")
    
    def showPeriods(c):
        print(f"Periods:          {c} Months")
    
    def showAmount(d):
        print(f"Interest Amount:  {d:.2f}")
    
    def showFutureValue(e):
        print(f"Future Value:     {e:.2f}")
    
    process_loan()
    print("===========================================")
  2. To execute and test the application, on the main menu, click Debug -> Start Without Debugging
  3. When the loan amount is requested, type 4750 and press Enter
  4. When the interest rate is requested, type 18.725 and press Enter
  5. When the period is requested, type 36 and press Enter
    Watts' A Loan
    ============================================
    Enter the informaiton to set up the loan
    Loan Amount:      4750
    Interest Rate:    18.725
    Number of months: 36
    ============================================
            Watts' A Loan
    --------------------------------------------
    Loan Amount:      4750.0
    Interest Rate:    18.73%
    Periods:          36 Months
    -------------------------------------------
    Interest Amount:  2668.31
    Future Value:     7418.31
    ===========================================
    Press any key to continue . . .
  6. To close the window, press Enter and return to your programming environment

The Data Type of a Parameter

Because Python is an inferred language, you don't have to specify the data type of a parameter. Still, if you want to assist the compiler with the type of a parameter, in the parentheses of the function, after the name of a parameter, you can type a colon and the data type. Here is an example:

def show_detail(cat : str):
    print("Loan Category:")
    print(cat)

def evaluate():
    loan_amount   : float = 4750
    interest_rate : float = 14.50  # %
    periods       : int   = 42           # Number of months

    print("Loan Amount:")
    print(loan_amount)
    print("Interest Rate:")
    print(interest_rate)
    print("Periods:")
    print(periods)

show_detail("Personal Loan")
print('----------------------------------')
evaluate()
print("==================================")

Introduction to Functions with many Parameters

Introduction

Just like a function can use one parameter, a function can use more than one parameter. When creating a function, to specify its parameters, in its parentheses, write the name of each parameter and separate them with commas. Here is an example:

def add(a, b):
    . . .

In the body of the function, you can ignore all parameters and not use them, you can use one of the parameters and ignore the other parameter(s), or you can use all parameters. Here is an example:

def describe(name, price):
    print("Item Name: ")
    printname)
    print("Marked Price: ")
    print(price)

Other than that, in the body of the function, you can involve a parameter in any appropriate operation you want.

Practical LearningPractical Learning: Creating a Function With Parameters

Calling a Function of many Parameters

After defining a function that uses more than one parameter, you can use it. When calling such a function, write its name and parentheses. In the parentheses, type a value for each parameter, exactly in the order the parameters appear in the function.

Practical LearningPractical Learning: Calling a Function of many Parameters

  1. To call a function of many parameters, change the document as follows:
    def present(a, b, c, d, e):
        print("============================================")
        print("\tWatts' A Loan")
        print('--------------------------------------------')
        print(f"Loan Amount:      {a}")
        print(f"Interest Rate:    {b:.2f}%")
        print(f"Periods:          {c} Months")
        print('-------------------------------------------')
        print(f"Interest Amount:  {d:.2f}")
        print(f"Future Value:     {e:.2f}")
    
    def process_loan():
        print("Watts' A Loan")
        print("============================================")
        print("Enter the informaiton to set up the loan")
        loan_amount = float(input("Loan Amount:      "))
        interest_rate : float = float(input("Interest Rate:    "))
        periods : int = int(input("Number of months: "))
    
        iRate           : float = interest_rate / 100.00
        years           : float = periods / 12
        interest_amount : float = loan_amount * iRate * years
        future_value    : float = loan_amount + interest_amount
    
        present(loan_amount, interest_rate, periods, interest_amount, future_value)
    
    process_loan()
    print("===========================================")
  2. To execute, press Ctrl + F5
  3. When the loan amount is requested, type 7450 and press Enter
  4. When the interest rate is requested, type 14.645 and press Enter
  5. When the period is requested, type 38 and press Enter
    Watts' A Loan
    ============================================
    Enter the informaiton to set up the loan
    Loan Amount:      7450
    Interest Rate:    14.645
    Number of months: 38
    ============================================
            Watts' A Loan
    --------------------------------------------
    Loan Amount:      7450.0
    Interest Rate:    14.64%
    Periods:          38 Months
    -------------------------------------------
    Interest Amount:  3455.00
    Future Value:     10905.00
    ===========================================
    Press any key to continue . . .
  6. To close the window and return to your programming environment, press Enter

Returning a Value from a Function

Introduction

So far, we used the result of each function only in its body. In most cases, you want to use the result of a function outside of that function. In that case, the function must produce a value that other sections of a program can use. When a function produces a result that can be used outside that function, the function is said to return a value.

Returning a Value

After performing one or more calculations in a function, to indicate the value that the function returns, type the return keyword followed by the value you want the function to return. At a minimum, a function can return a constant value, such as a string, a number, or a Boolean value. Here are examples:

def produce_number():
    return 0

def get_name():
    return 'William Jefferson Clinton'

Practical LearningPractical Learning: Returning a Value from a Function

Calling a Function that Returns a Value

You can call a function that returns a value by simply writing its name and parentheses. Here is an example:

def produce():
    print("This is the interior of the function.")
    return 0;

produce()

This would produce:

This is the interior of the function.
Press any key to continue . . .

In reality, the reason you are returning something from a function is that you want the result of a function to be used, and to be useful, outside the function. As one way to do that, you can declare a variable and assign the function call to it. Here is an example:

def produce():
    return 0;

a = produce()

print(a)

This would produce:

0
Press any key to continue . . .

Normally, the reason you declare a variable and assign the function call to it is if you plan to use the returned value more than once. Here is an example:

def produce():
    return 68;

a = produce()
b = a * 12
c = a + 2804

print(a)
print("---------")
print(c)
print("---------")
print(b)

If you are planning to use the returned value of a function once, you don't need to store the function call in a variable. You can just call the function where its value is needed. Here is an example:

def produce():
    return 395;

print(produce())
print("---------")

In the same way, you can involve the function call to an expression directly where the function call is needed. Here is an example:

def produce():
    return 395;

print(produce() + 9574)
print("---------")

This would produce:

9969
---------
Press any key to continue . . .

Even if you are planning to use the returned value of a function many times, you can still call it only where its value is needed. Here are examples:

def produce():
    return 395;

print("Value:", produce() + 9574)
print("------------------")
print(produce(), "times 3 =", produce() * 3)
print("------------------")
print("Value:", produce() + produce() - 552 + produce() * 2)
print("==================================")

This would produce:

Value: 9969
------------------
395 times 3 = 1185
------------------
Value: 1028
==================================
Press any key to continue . . .

Practical LearningPractical Learning: Calling a Function that Returns a Value

  1. To call functions that return some values, change the document as follows:
    def show_applicant(fn, ln):
        return fn + ' ' + ln
        
    def calculate_interest_amount(amt, rate, per):
        iRate = rate / 100.00
        loan_in_years = per / 12
        interest_amount = amt * iRate * loan_in_years
        
        return interest_amount
        
    def calculate_future_value(amt, rate, per):
        iRate = rate / 100.00
        loan_in_years = per / 12
        interest_amount = calculate_interest_amount(amt, rate, per)
        future_value = amt + interest_amount
        
        return future_value
        
    current_value = 3625
    interest_rate = 15.85
    periods       = 38
            
    iAmt          = calculate_interest_amount(current_value, interest_rate, periods)
    loan_total    = calculate_future_value(current_value, interest_rate, periods)
            
    print("================================")
    print("Watts' A Loan")
    print("Loan Applicant")
    show_applicant("Lynda", "Gibbs")
    print('--------------------------------')
    print("Loan Details")
    print(f"Principal:       {current_value:.2f}")
    print(f"Interest Rate:   {interest_rate:.2f}")
    print(f"Periods:         {periods}", )
    print('--------------------------------')
    print(f"Interest Amount: {iAmt:.2f}")
    print(f"Future Value:    {loan_total:.2f}")
    print("================================")
  2. To execute, on the main menu, click Debug -> Start Without Debugging:
    ================================
    Watts' A Loan
    Loan Applicant
    --------------------------------
    Loan Details
    Principal:       3625.00
    Interest Rate:   15.85
    Periods:         38
    --------------------------------
    Interest Amount: 1819.45
    Future Value:    5444.45
    ================================
    Press any key to continue . . .
  3. To close the window and return to your programming environment, press z

Returning an Expression

Most functions are made to perform calculations or some type of processing. If you want a function to return an expression, you can first create the expression, store it in a variable, and then return that variable. Here is an example:

def getFullName():
    first = "James"
    last  = "Naughton"
    full  = first + " " + last

    return full

name = getFullName()

print("Full Name:", name)
print("==================================")

This would produce:

Full Name: James Naughton
==================================
Press any key to continue . . .

Otherwise, you can directly return an expression. To do that, create an expression on the right side of return. Here is an example:

def getFullName():
    first = "James"
    last  = "Naughton"

    return first + " " + last

name = getFullName()

print("Full Name:", name)

Returning the Result of a Function

You can call a function in the body of another function. Here is an example:

def getFullName():
    first = "James"
    last  = "Naughton"

    return first + " " + last

def display():
    name = getFullName()

    print("Full Name:", name)

display()
print("==================================")

You can also return the value of one function in the body of another function. To do this, you can declare a variable in a function, assign the function call to the variable, and then return that variable from the function. Here is an example:

def getFullName():
    first = "James"
    last  = "Naughton"

    return first + " " + last

def process():
    name = getFullName()
    #. . .
    return name

result = process()
print("Full Name:", result)
print("==================================")

Remember that, usually, the reason you first declare a variable is because you are planning to use that value many times and the reason you are storing the returned value of a function call in a variable is because you are planning to use the returned value many times. If you are planning to use the returned value of the called function once, you can call the function directly where you are returning its value, in which case you call the function on the right side of return. Here is an example:

def getFullName():
    first = "James"
    last  = "Naughton"

    return first + " " + last

def process():
    return getFullName()

print("Full Name:", process())
print("==================================")

Practical LearningPractical Learning: Returning by Calling a Function

  1. Change the document as follows:
    def show_applicant(fn, ln):
        return fn + ' ' + ln
        
    def calculate_interest_amount(amt, rate, per):
        iRate = rate / 100.00
        loan_in_years = per / 12
        interest_amount = amt * iRate * loan_in_years
        
        return interest_amount
        
    def calculate_future_value(amt, rate, per):
        iRate = rate / 100.00
        loan_in_years = per / 12
        interest_amount = calculate_interest_amount(amt, rate, per)
        future_value = amt + interest_amount
        
        return future_value
        
    current_value = 24886
    interest_rate = 11.625
    periods       = 60
        
    print("================================")
    print("Watts' A Loan")
    print("Loan Applicant")
    show_applicant("Lynda", "Gibbs")
    print('--------------------------------')
    print("Loan Details")
    print(f"Principal:       {current_value:.2f}")
    print(f"Interest Rate:   {interest_rate:.2f}")
    print(f"Periods:         {periods}", )
    print('--------------------------------')
    print(f"Interest Amount: {calculate_interest_amount(current_value, interest_rate, periods):.2f}")
    print(f"Future Value:    {calculate_future_value(current_value, interest_rate, periods):.2f}")
    print("================================")
  2. To execute, on the main menu, click Debug -> Start Without Debugging:
    ================================
    Watts' A Loan
    Loan Applicant
    --------------------------------
    Loan Details
    Principal:       24886.00
    Interest Rate:   11.62
    Periods:         60
    --------------------------------
    Interest Amount: 14464.99
    Future Value:    39350.99
    ================================
    Press any key to continue . . .
  3. To close the window and return to your programming environment, press w

Previous Copyright © 2021-2024, FunctionX Tuesday 06 August 2024, 10:47 Next