﻿ 06: 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

1. Start Microsoft Visual Studio
2. Create a new Python Application named GasCompany1
3. In the empty document, type the following lines:
```print('Quatro Gas Company')
print('======================================================')
print('To prepare an invoice, enter the following information')

first_50_therms : float = 0.00
over_50_therms  : float = 0.00
transportation_charge   = 10.55

total_therms : float    = ccf_total * 1.0367

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('-----------------------------------------------------')
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'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('======================================================')```
4. To execute the application and test it, on the main menu, click Run -> Run Without Debugging
5. In the Terminal, click on the right side of Counter Reading Start, type 6249.27 and press Enter
6. Fort the Counter Reading End, type 6412.46 and press Enter
```Quatro Gas Company
======================================================
To prepare an invoice, enter the following information
======================================================
Quatro Gas Company - Customer Invoice
======================================================
-----------------------------------------------------
CCF Total:                            163.19
Total Therms (* 1.0367):              169.18
======================================================
Bill Values
-----------------------------------------------------
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

1. Change the document as follows:
```print('Quatro Gas Company')
print('======================================================')
print('To prepare an invoice, enter the following information')

first_50_therms : float = 0.00
over_50_therms  : float = 0.00
transportation_charge   = 10.55

total_therms : float    = ccf_total * 1.0367

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('-----------------------------------------------------')
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'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('======================================================')```
2. To execute the application and test it, on the main menu, click Run -> Run Without Debugging
3. In the Terminal, click on the right side of Counter Reading Start, type 6249.27 and press Enter
4. Still in the Terminal, for the Counter Reading End, type 6412.46 and press Enter
```Quatro Gas Company
======================================================
To prepare an invoice, enter the following information
======================================================
Quatro Gas Company - Customer Invoice
======================================================
-----------------------------------------------------
CCF Total:                            163.19
Total Therms (* 1.0367):              169.18
======================================================
Bill Values
-----------------------------------------------------
Transportation Charge:                10.55
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 . . .```
5. Start a new Python Application named TaxEvaluation1
6. In the empty document, type the code follows:
```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("==============================================")```
7. To execute, on the main menu, click Run -> Run Without Debugging
8. Type the Gross Salary as 578.68 and press Enter
```============================================
- 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 . . .```
10. To execute again, on the main menu, click Run -> Run Without Debugging
11. For the Gross Salary, type 1578.68 and press Enter
```============================================
- 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...elif

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

qualifies = True
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 . . .```

if...elif...else

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```

if...elif... elif

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

1. Change the code as follows:
```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("==============================================")```
2. To execute, on the main menu, click Run -> Run Without Debugging
3. For the Gross Salary, type 1578.68, and press Enter
```============================================
- 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 . . .```
5. To execute again, on the main menu, click Run -> Run Without Debugging
6. For the Gross Salary, type 5578.68, and press Enter
```============================================
- 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
==============================================```
7. Click inside the Code Editor. Press Ctrl + A to select everything. Then type the code follows:
```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("===========================================")```
8. To execute, on the main menu, click Run -> Run Without Debugging
9. For the Loan Amount, type 1555.55, and press Enter
10. For the Interest Rate, type 15.55, and press Enter
11. For the Periods, type 28, and press Enter
```============================================
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...elif...elif and else

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

1. Change the document as follows:
```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 = 365
strFrequency = "Daily"
frequency = 52.00
strFrequency = "Weekly"
frequency = 12.00
strFrequency = "Monthly"
frequency = 4.00
strFrequency = "Quaterly"
frequency = 2.00
strFrequency = "Semi-Annually"
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("===========================================")```
2. To execute, on the main menu, click Run -> Run Without Debugging
3. For the Loan Amount, type 1555.55, and press Enter
4. For the Interest Rate, type 15.55, and press Enter
5. For the Periods, type 28, and press Enter
6. For the Compound Frequency, type 3 and press Enter
```============================================
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 . . .```
8. To execute again, on the main menu, click Run -> Run Without Debugging
9. For the Loan Amount, type 1555.55, and press Enter
10. For the Interest Rate, type 15.55, and press Enter
11. For the Periods, type 28, and press Enter
12. For the Compound Frequency, type 5, and press Enter
```============================================
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 . . .```