Functions and Conditional Statements
Functions and Conditional Statements
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 Learning: Starting a Project
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 characteristics 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 cah 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 . . .
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 . . .
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' def validate(): return True
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
Practical Learning: Returning a Value from a Function
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
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 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 Learning: Calling a Function that Returns a Value
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("================================")
================================ 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 . . .
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 an 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 Learning: Returning by Calling a Function
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("================================")
================================ 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 . . .


Previous  Copyright © 20212022, FunctionX  Thursday 30 December 2021  Next 
