Boolean Values and Functions

Introduction

As is the case with the other data types, you can declare a Boolean variable in the body of a function. Of course, to treat the variable as a Boolean one, you should initialize it with a True or a False value. After declaring and initializing the variable or giving it an appropriate value, you can use it as normally as possible. Here is an example:

def prepare():
    hourly_salary    : float = 22.27
    time_worked      : float = 44.50
    overtime_allowed : bool  = True
            
    overtime         : float = 0.00
    overtime_pay     : float = 0.00
    regular_time     : float = time_worked
    regular_pay      : float = hourly_salary * time_worked
    over_sal     = hourly_salary + (hourly_salary / 2.00)
                
    if overtime_allowed == True:
        overtime     = time_worked - 40.00
        overtime_pay = (time_worked - 40.00) * over_sal
        regular_pay  = 40.00 * hourly_salary
                    
    net_pay  : float = regular_pay + overtime_pay
            
    print(f"Hourly Salary:           {hourly_salary:8.2f}")
    print(f"Overtime Salary:         {over_sal:8.2f}")
    print('-------------------------------------')
    print(f"Overtime Pay Allowed:       {overtime_allowed}")
    print('-------------------------------------')
    print(f"Overtime:                {overtime:8.2f}")
    print(f"Overtime Pay:            {overtime_pay:8.2f}")
    print(f"Regular Time:            {regular_time:8.2f}")
    print(f"Regular Pay:             {regular_pay:8.2f}")
    print('-------------------------------------')
    print(f"Net Pay:                 {net_pay:8.2f}")
                    
print("=====================================")
print("Payroll Preparation")
prepare()
print("====================================")

This would produce:

=====================================
Payroll Preparation
Hourly Salary:              22.27
Overtime Salary:            33.41
-------------------------------------
Overtime Pay Allowed:       True
-------------------------------------
Overtime:                    4.50
Overtime Pay:              150.32
Regular Time:               44.50
Regular Pay:               890.80
-------------------------------------
Net Pay:                  1041.12
====================================
Press any key to continue . . .

Practical LearningPractical Learning: Starting a Project

  1. Start Microsoft Visual Studio
  2. Create a new Python Application named Exercise09

Boolean Parameters

A parameter of a function can be of a Boolean type. As you should know already, to specify a parameter of a function, simply provide its name. In the body of the function, ignore the parameter or treat it as a Boolean value. When calling the function, you can pass an argument that holds a Boolean value or you can pass a value of True or False. Here is an example:

def calculate(price, apply_discount, rate):
    discount_amount = 0.00
    after_discount = price

    print("Original Price: ", price)

    if apply_discount == True:
        discount_amount = price * rate / 100
        after_discount = price - discount_amount

        print(f"Discount Rate:   {rate}%")
        print("Discount Amount:", discount_amount)
    
    print("Marked Price:   ", after_discount)

a = 94.55

calculate(a, True, 20)
print("==================================")

This would produce:

Original Price:  94.55
Discount Rate:   20%
Discount Amount: 18.91
Marked Price:    75.64
==================================
Press any key to continue . . .

Here is another run of the code:

def calculate(price, apply_discount, rate):
    discount_amount = 0.00
    after_discount = price

    print("Original Price: ", price)

    if apply_discount == True:
        discount_amount = price * rate / 100
        after_discount = price - discount_amount

        print(f"Discount Rate:   {rate}%")
        print("Discount Amount:", discount_amount)
    
    print("Marked Price:   ", after_discount)

a = 94.55

calculate(a, False, 20)
print("==================================")

This would produce:

Original Price:  94.55
Marked Price:    94.55
==================================
Press any key to continue . . .

Conditional Statements

Introduction

Conditional statements allow you to perform some validations inside a function. Conditional statements are primarily used in a function the exact same way we used them in previous lessons. Here is an example:

def present(name, inventory, time, disc, amt, marked):
    print("+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+")
    print("FUN DEPARTMENT STORE")
    print("=======================================================")
    print("Store Inventory")
    print("-------------------------------------------------------")
    print(f"Item Name:       ", name)
    print(f"Original Price:  ", inventory)
    print(f"Days in Store:   ", time)
    print(f"Discount Rate:   ", disc, "%")
    print(f"Discount Amount:  {amt:5.2f}")
    print(f"Discounted Price: {marked:5.2f}")

def prepare():
    print("FUN DEPARTMENT STORE")
    print("=======================================================")
    print("Item Preparation")
    print("-------------------------------------------------------")
    print("Enter the following pieces of information")
    print("-------------------------------------------------------")

    discount_rate   : int   = None
    discount_amount : float = 0.00

    item_name : str = input("Item Name:        ")
    original_price : float = float(input("Original Price:   "))
    days_in_store : int    = int(input("Days in Store:    "))

    if days_in_store >= 15:
        discount_rate = 0
    if days_in_store >= 35:
        discount_rate = 15
    if days_in_store >= 45:
        discount_rate = 35
    if days_in_store >= 60:
        discount_rate = 50

    discount_amount  = original_price * discount_rate / 100
    discounted_price = original_price - discount_amount

    present(item_name, original_price, days_in_store, discount_rate, discount_amount, discounted_price)

prepare()
print("=======================================================")

Shortening Function Processing

Normally, when defining a function, to indicate the end of that function, you can simply type the return keyword. Here is an example:

def understand():
    print("Welcome to the wonderful world of Python programming.")
    return

understand();

This would produce:

Welcome to the wonderful world of Python programming.
=======================================================
Press any key to continue . . .

Here, the return keyword is mainly used to indicate the end of the function.

Exiting Early From a Function

One of the goals of a conditional statement is to check a condition in order to reach a conclusion. One of the goals of a function is to perform an action if a certain condition is met. In fact, by including a condition in a function, you can decide whether the action of a function is worth pursuing or completing. In the body of a function where you are checking a condition, once you find out that a certain condition is (or is not) met, you can stop checking the condition and get out of the function. This is done with the return keyword. To apply it, in the body of a conditional statement in a function, once you decide that the condition reaches the wrong outcome, type return. Here are examples:

def check_certification():
    print("This job requires a Python certification.")
    answer = input("Do you hold a certificate in Python programming? (y/n) ")
    print('---------------------------------------------------------------')

    if answer == 'y':
        print("Does the job applicant qualify for this job? Yes.")
        return
    if answer == 'Y':
        print("The job applicant fulfills the primary requirement of this job: True.")
        return

    if answer == 'n':
        print("This job applicant doesn't qualify for this job.")
        return
    if answer == 'N':
        print("The job applicant cannot fulfill the primary requirements of this job.")
        return

print("The application process has ended.")

print('----------------------------------------------------------------')
check_certification()
print("===================================================================")

Here is an example of running the program:

----------------------------------------------------------------
This job requires a Python certification.
Do you hold a certificate in Python programming? (y/n) y
---------------------------------------------------------------
Does the job applicant qualify for this job? Yes.
===================================================================
Press any key to continue . . .

Here is another example of running the program:

----------------------------------------------------------------
This job requires a Python certification.
Do you hold a certificate in Python programming? (y/n) Y
---------------------------------------------------------------
The job applicant fulfills the primary requirement of this job: True.
===================================================================
Press any key to continue . . .

Here is another example of running the program:

----------------------------------------------------------------
This job requires a Python certification.
Do you hold a certificate in Python programming? (y/n) n
---------------------------------------------------------------
This job applicant doesn't qualify for this job.
===================================================================
Press any key to continue . . .

Here is another example of running the program:

----------------------------------------------------------------
This job requires a Python certification.
Do you hold a certificate in Python programming? (y/n) q
---------------------------------------------------------------
The application process has ended.
===================================================================
Press any key to continue . . .

Conditional Return

Probably the most important characteristic of a function is that it can return a value. Sometimes, the value a function must return depends on some conditions. To make this happen, you can use a variable that would hold the value that must be returned. In the function, you can create a conditional statement so that, when the value to return is encountered, you can assign the value to that variable. Then, at the end of the function, you can return that variable. Here is an example:

def calculate(decision):
    result = 0
    
    if answer == '1':
       result = 365
    elif answer == '2':
        result = 52.00
    elif answer == '3':
        result = 12.00
    elif answer == '4':
        result = 4.00
    elif answer == '5':
        result = 2.00
    else: # answer == '6':
        result = 1.00

    return result

print("============================================")
print("\tWatts' A Loan")
print("============================================")

frequency    : int
strFrequency : str = 'Annually'

print("Enter the information to set up the loan")
loan_amount   : float = float(input("Loan Amount:      "))
interest_rate : float = float(input("Interest Rate:    "))
periods       : int   =   int(input("Number of months: "))
print('-----------------------------------------------')
print('Compound Frequency')
print('\t1. Daily')
print('\t2. Weekly')
print('\t3. Monthly')
print('\t4. Quarterly')
print('\t5. Semiannually')
print('\t6. Annually')
answer : str = input("Enter the Compound Frequency: ")

frequency = calculate(answer)

years            : float = periods / 12.00
payments_periods : float = frequency * years
iRate            : float = interest_rate / 100.00 / frequency
periodic         : float = (1 + iRate) ** payments_periods

future_value     : float = loan_amount * periodic
interest_amount  : float = future_value - loan_amount

print("============================================")
print("\tWatts' A Loan")
print("============================================")
print("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}")
print("===========================================")

Usually, the reason you use a variable is if you are planning to use a value many times. When it comes to returning a value based on various conditions, if you are not planning to process anything else other than returning the value, whenever you encounter the value to be returned, you can simply type return followed by the value to be returned. Here are examples:

def calculate(decision):
    if answer == '1':
        return 365
    elif answer == '2':
        return 52.00
    elif answer == '3':
        return 12.00
    elif answer == '4':
        return 4.00
    elif answer == '5':
        return 2.00
    else: # answer == '6':
        return 1.00

Returning From a Function

Normally, when defining a function, to indicate the end of that function, you can simply type the return keyword. Here is an example:

def understand():
    print("Welcome to the wonderful world of Python programming.")
    return
    
understand();

This would produce:

Welcome to the wonderful world of Python programming.
=======================================================
Press any key to continue . . .

Here, the return keyword is mainly used to indicate the end of the function.

Returning a Boolean Value

You can create a function that returns a Boolean value. There is no special formula. In the body of the function, you can perform all types of calculations. At the end of the body of the function, type return followed by a Boolean value (True or False). Here is an example:

def logicalize():
    return True;
    
validation = logicalize()
    
print("Validation:", validation)

This would produce:

Validation: True
Press any key to continue . . .

Of course, you can add other lines of code in the function. The most important thing to know is that the last line must have return followed by the desired value. Here is an example:

def validate():
    print('Your time sheet has been validated.')
    return True

You can also return a variable that holds a Boolean value. Here is an example:

def decide():
    decision = False
    
    answer = input("Is today independence day? (y=Yes/n=No) ")
    
    if answer == 'y':
        decision = True
    
    if answer == 'Y':
        decision = True
    
    if answer == 'Yes':
        decision = True
    
    return decision;
    
day_off = decide()
    
print("Is today a holiday?", day_off)
print("=============================================")

Here is an example of running the program:

Is today independence day? (y=Yes/n=No) y
Is today a holiday? True
=============================================
Press any key to continue . . .

Here is another example of running the program:

Is today independence day? (y=Yes/n=No) Nooooo!
Is today a holiday? False
=============================================
Press any key to continue . . .

You can also return an expression that can produce a Boolean value. Here is an example:

def hire():
    print("This job requires a Python certification.")
    degree = input("Do you hold a certificate in Python programming? (1=Yes/0=No) ")
    
    return degree == '1';
    
qualifies = hire()
    
print('----------------------------------------------------------------')
print("Does the current qualify for this job?", qualifies)
print("================================================================")

Here is an example of running the program:

This job requires a Python certification.
Do you hold a certificate in Python programming? (1=Yes/0=No) 1
----------------------------------------------------------------
Does the current qualify for this job? True
================================================================
Press any key to continue . . .

Here is another example of running the program:

This job requires a Python certification.
Do you hold a certificate in Python programming? (1=Yes/0=No) 8
----------------------------------------------------------------
Does the current qualify for this job? False
================================================================
Press any key to continue . . .

Previous Copyright © 2021-2024, FunctionX Thursday 30 December 2021 Next