Topics on Conditional Statements
Topics on Conditional Statements
What Else to Consider?
Introduction
In the previous lessons, we were introduced to logical operators and how they can be used with the if keyword. To consider other possibilities of logical operations, other keywords are available.
Practical Learning: Introducing Else Conditions
print('Quatro Gas Company') print('======================================================') print('To prepare an invoice, enter the following information') counter_reading_start = float(input('Counter Reading Start: ')) counter_reading_end = float(input('Counter Reading End: ')) first_50_therms : float = 0.00 over_50_therms : float = 0.00 transportation_charge = 10.55 ccf_total : float = counter_reading_end - counter_reading_start total_therms : float = ccf_total * 1.0367 distribution_adjustment = total_therms * 0.13086 delivery_total = transportation_charge + distribution_adjustment + first_50_therms + over_50_therms environmental_charges = delivery_total * 0.0045 local_taxes = delivery_total * 0.05 state_taxes = delivery_total * 0.10 amount_due = delivery_total + environmental_charges + local_taxes + state_taxes print('======================================================') print('Quatro Gas Company - Customer Invoice') print('======================================================') print('Meter Reading') print('-----------------------------------------------------') print('Counter Reading Start: ', counter_reading_start) print('Counter Reading End: ', counter_reading_end) print(f'CCF Total: {ccf_total:5.2f}') print(f'Total Therms (* 1.0367): {total_therms:.2f}') print('======================================================') print('Bill Values') print('-----------------------------------------------------') print('Transportation Charge: ', transportation_charge) print(f'Distribution Adjustment (* 0.13086): {distribution_adjustment:5.2f}') print(f'First 50 Therms (* 0.5269): {first_50_therms:5.2f}') print(f'Over 50 Therms (* 0.4995): {over_50_therms:5.2f}') print(f'Delivery Total: {delivery_total:5.2f}') print(f'Environmental Charges: {environmental_charges:5.2f}') print(f'Local Taxes: {local_taxes:5.2f}') print(f'State Taxes: {state_taxes:5.2f}') print('-----------------------------------------------------') print(f'Amount Due: {amount_due:6.2f}') print('======================================================')
Quatro Gas Company ====================================================== To prepare an invoice, enter the following information Counter Reading Start: 6249.27 Counter Reading End: 6412.46 ====================================================== Quatro Gas Company - Customer Invoice ====================================================== Meter Reading ----------------------------------------------------- Counter Reading Start: 6249.27 Counter Reading End: 6412.46 CCF Total: 163.19 Total Therms (* 1.0367): 169.18 ====================================================== Bill Values ----------------------------------------------------- Distribution Adjustment (* 0.13086): 22.14 First 50 Therms (* 0.5269): 0.00 Over 50 Therms (* 0.4995): 0.00 Delivery Total: 32.69 Environmental Charges: 0.15 Local Taxes: 1.63 State Taxes: 3.27 ----------------------------------------------------- Amount Due: 37.74 ====================================================== Press any key to continue . . .
Introduction to if...else Conditions
If you use an if condition to perform an operation and if the result is true, we saw that you can execute the statement. Any other result would be ignored. To address an alternative to an if condition, you can use a keyword named else. The formula to use it is:
if condition: statement1 else: statement2
The condition can be a Boolean operation. If the condition is True, then the statement1 would execute. If the condition is False, then the compiler would execute statement2 in the else section. The else keyword must be followed by a colon. The section (of code) under else: is the body of the else condition. That body must be indented. Here is an example:
molecule = "H2O" if molecule == "H2O": print("That's right, the molecule of water is H2O.") else: print("Not really! It's time you refresh your knowledge of chemistry.") print("================================================================")
Here is an example of executing the program:
That's right, the molecule of water is H2O. ================================================================ Press any key to continue . . .
Practical Learning: Applying an Else Condition
print('Quatro Gas Company')
print('======================================================')
print('To prepare an invoice, enter the following information')
counter_reading_start = float(input('Counter Reading Start: '))
counter_reading_end = float(input('Counter Reading End: '))
first_50_therms : float = 0.00
over_50_therms : float = 0.00
transportation_charge = 10.55
ccf_total : float = counter_reading_end - counter_reading_start
total_therms : float = ccf_total * 1.0367
distribution_adjustment = total_therms * 0.13086
if total_therms < 50:
first_50_therms = total_therms * 0.5269
over_50_therms = 0.00
else:
first_50_therms = 50 * 0.5269
over_50_therms = (total_therms - 50) * 0.4995
delivery_total = transportation_charge + distribution_adjustment + first_50_therms + over_50_therms
environmental_charges = delivery_total * 0.0045
local_taxes = delivery_total * 0.05
state_taxes = delivery_total * 0.10
amount_due = delivery_total + environmental_charges + local_taxes + state_taxes
print('======================================================')
print('Quatro Gas Company - Customer Invoice')
print('======================================================')
print('Meter Reading')
print('-----------------------------------------------------')
print('Counter Reading Start: ', counter_reading_start)
print('Counter Reading End: ', counter_reading_end)
print(f'CCF Total: {ccf_total:5.2f}')
print(f'Total Therms (* 1.0367): {total_therms:.2f}')
print('======================================================')
print('Bill Values')
print('-----------------------------------------------------')
print('Transportation Charge: ', transportation_charge)
print(f'Distribution Adjustment (* 0.13086): {distribution_adjustment:5.2f}')
print(f'First 50 Therms (* 0.5269): {first_50_therms:5.2f}')
print(f'Over 50 Therms (* 0.4995): {over_50_therms:5.2f}')
print(f'Delivery Total: {delivery_total:5.2f}')
print(f'Environmental Charges: {environmental_charges:5.2f}')
print(f'Local Taxes: {local_taxes:5.2f}')
print(f'State Taxes: {state_taxes:5.2f}')
print('-----------------------------------------------------')
print(f'Amount Due: {amount_due:6.2f}')
print('======================================================')
Quatro Gas Company ====================================================== To prepare an invoice, enter the following information Counter Reading Start: 6249.27 Counter Reading End: 6412.46 ====================================================== Quatro Gas Company - Customer Invoice ====================================================== Meter Reading ----------------------------------------------------- Counter Reading Start: 6249.27 Counter Reading End: 6412.46 CCF Total: 163.19 Total Therms (* 1.0367): 169.18 ====================================================== Bill Values ----------------------------------------------------- Transportation Charge: 10.55 Distribution Adjustment (* 0.13086): 22.14 First 50 Therms (* 0.5269): 26.35 Over 50 Therms (* 0.4995): 59.53 Delivery Total: 118.56 Environmental Charges: 0.53 Local Taxes: 5.93 State Taxes: 11.86 ----------------------------------------------------- Amount Due: 136.88 ====================================================== Press any key to continue . . .
print("============================================") print("\t - Mississippi - State Income Tax -") print("============================================") tax_rate : float = 0.00 gross_salary : float = 0.00 print("Enter the information for tax preparation") gross_salary : float = float(input("Gross Salary: ")) tax_amount = gross_salary * tax_rate / 100.00 net_pay = gross_salary - tax_amount print("==============================================") print("\t- Mississippi - State Income Tax -") print("----------------------------------------------") print(f"Gross Salary: {gross_salary:.2f}") print(f"Tax Rate: {tax_rate:.2f}%") print(f"Tax Amount: {tax_amount:.2f}") print(f"Net Pay: {net_pay:.2f}") print("==============================================")
============================================ - Mississippi - State Income Tax - ============================================ Enter the information for tax preparation Gross Salary: 578.68 ============================================== - Mississippi - State Income Tax - ---------------------------------------------- Gross Salary: 578.68 Tax Rate: 0.00% Tax Amount: 0.00 Net Pay: 578.68 ============================================== Press any key to continue . . .
============================================ - Mississippi - State Income Tax - Enter the information for tax preparation Gross Salary: 1578.68 ============================================== - Mississippi - State Income Tax - ---------------------------------------------- Gross Salary: 1578.68 Tax Rate: 0.00% Tax Amount: 0.00 Net Pay: 1578.68 ============================================== Press any key to continue . . .
If, What Else If...?
If you use an if...else situation, you can process only two statements. In some cases, you may deal with more than two conditions. In this case, you can use a keyword named elif. This keyword and its condition can be used only after an if condition. The combination would be if...elif. The formula to follow is:
if condition1: statement(s) elif condition2: statement(s)
The first condition, condition1, would be checked. If condition1 is True, then statement1 would execute. If condition1 is False, the second condition is lead by the elif keyword. In case it is reached, condition2 would be checked. That condition2 is followed by a colon. If condition2 is True, then statement2 would execute. Any other result would be ignored. Here is an example:
print("This job requires a Python certification.")
answer = input("Do you hold a certificate in Python programming? (y/n) ")
qualifies = False
if answer == 'y':
qualifies = True
elif answer == 'Y':
qualifies = True
print('----------------------------------------------------------------')
print("The job applicant qualifies for this job:", qualifies)
print("================================================================")
Here is an example of running the programming:
This job requires a Python certification. Do you hold a certificate in Python programming? (y/n) y ---------------------------------------------------------------- The job applicant qualifies for this job: True ================================================================ Press any key to continue . . .
Here is another example of running the programming:
This job requires a Python certification. Do you hold a certificate in Python programming? (y/n) q ---------------------------------------------------------------- The job applicant qualifies for this job: False ================================================================ Press any key to continue . . .
Here is one more example of running the programming:
This job requires a Python certification. Do you hold a certificate in Python programming? (y/n) Y ---------------------------------------------------------------- The job applicant qualifies for this job: True ================================================================ Press any key to continue . . .
Because there can be other alternatives, you can add an alternate else condition as the last resort. Its formula is:
if condition1: statement1 elif condition2: statement2 else: statement-n
The elif conditional statement allows you to process many conditions. The formula to follow is:
if condition1: statement1 elif condition2: statement2 . . . elif condition_n: statement_n
Practical Learning: Using Else If...Else
print("============================================")
print("\t - Mississippi - State Income Tax -")
print("============================================")
tax_rate : float = 0.00
gross_salary : float = 0.00
print("Enter the information for tax preparation")
gross_salary : float = float(input("Gross Salary: "))
# Mississippi
if gross_salary >= 10_000:
tax_rate = 5.00
elif gross_salary >= 5_000:
tax_rate = 4.00
elif gross_salary >= 1_000:
tax_rate = 3.00
tax_amount = gross_salary * tax_rate / 100.00
net_pay = gross_salary - tax_amount
print("==============================================")
print("\t- Mississippi - State Income Tax -")
print("----------------------------------------------")
print(f"Gross Salary: {gross_salary:.2f}")
print(f"Tax Rate: {tax_rate:.2f}%")
print(f"Tax Amount: {tax_amount:.2f}")
print(f"Net Pay: {net_pay:.2f}")
print("==============================================")
============================================ - Mississippi - State Income Tax - ============================================ Enter the information for tax preparation Gross Salary: 1578.68 ============================================== - Mississippi - State Income Tax - ---------------------------------------------- Gross Salary: 1578.68 Tax Rate: 3.00% Tax Amount: 47.36 Net Pay: 1531.32 ============================================== Press any key to continue . . .
============================================ - Mississippi - State Income Tax - ============================================ Enter the information for tax preparation Gross Salary: 5578.68 ============================================== - Mississippi - State Income Tax - ---------------------------------------------- Gross Salary: 5578.68 Tax Rate: 4.00% Tax Amount: 223.15 Net Pay: 5355.53 ==============================================
print("============================================") print("\tWatts' A Loan") print("============================================") 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: ")) years : float = periods / 12.00 iRate : float = interest_rate / 100.00 periodic : float = (1 + iRate) ** years 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("===========================================")
============================================ Watts' A Loan ============================================ Enter the information to set up the loan Loan Amount: 1555.55 Interest Rate: 15.55 Number of months: 28 ============================================ Watts' A Loan ============================================ Loan Amount: 1555.55 Interest Rate: 15.55% Periods: 28 Months ------------------------------------------- Interest Amount: 623.90 Future Value: 2179.45 =========================================== Press any key to continue . . .
If there is a possibility that none of the conditions would respond True, you can add a last else condition and its statetement. The formula to follow is:
if condition1: statement1 elif condition2: statement2 . . . elif condition_n: statement_n else: statement-n
Practical Learning: Using Else If...Else
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: ") if answer == '1': frequency = 365 strFrequency = "Daily" elif answer == '2': frequency = 52.00 strFrequency = "Weekly" elif answer == '3': frequency = 12.00 strFrequency = "Monthly" elif answer == '4': frequency = 4.00 strFrequency = "Quaterly" elif answer == '5': frequency = 2.00 strFrequency = "Semi-Annually" else: # answer == '6': frequency = 1.00 strFrequency = "Annually" 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("Compound Frequency:", strFrequency) print('-------------------------------------------') print(f"Interest Amount: {interest_amount:.2f}") print(f"Future Value: {future_value:.2f}") print("===========================================")
============================================ Watts' A Loan ============================================ Enter the information to set up the loan Loan Amount: 1555.55 Interest Rate: 15.55 Number of months: 28 ----------------------------------------------- Compound Frequency 1. Daily 2. Weekly 3. Monthly 4. Quarterly 5. Semiannually 6. Annually Enter the Compound Frequency: 3 ============================================ Watts' A Loan ============================================ Loan Amount: 1555.55 Interest Rate: 15.55% Periods: 28 Months Compound Frequency: Monthly ------------------------------------------- Interest Amount: 675.19 Future Value: 2230.74 =========================================== Press any key to continue . . .
============================================ Watts' A Loan ============================================ Enter the information to set up the loan Loan Amount: 1555.55 Interest Rate: 15.55 Number of months: 28 ----------------------------------------------- Compound Frequency 1. Daily 2. Weekly 3. Monthly 4. Quarterly 5. Semiannually 6. Annually Enter the Compound Frequency: 5 ============================================ Watts' A Loan ============================================ Loan Amount: 1555.55 Interest Rate: 15.55% Periods: 28 Months Compound Frequency: Semi-Annually ------------------------------------------- Interest Amount: 650.60 Future Value: 2206.15 =========================================== Press any key to continue . . .
|
|||
Previous | Copyright © 2021-2024, FunctionX | Thursday 30 December 2021 | Next |
|