What Else?

Introduction

When it comes to logical comparisons, besides the if operator, you have many options and alternatves.

If you use an if condition to perform an operation and if the result is true, we saw that you could execute the statement. Any other result would be ignored. To address an alternative to an if condition, you can use an operator named else. The formula to use it is:

if(condition) {
    statement1
}
else {
    statement2
}

Once again, the condition can be a Boolean operation. If the condition is true, then the statement1 would execute. If the condition is false, then statement2 would execute in the else section. Here is an example:

$number = 248

if($number -eq 248){
    Write-Host 'That number is correct.'
}
else {
    Write-Host 'That number is not right.'
}

Here is an example of executing the program:

PS C:\Windows\System32> C:\Exercises\Conditionals.ps1
That number is correct.

The Ternary Operator (?:)

We have seen that an if...else conditional statement can be performed as follows:

if(condition) {
    statement1
}
else {
    statement2
}

Here is an example of such a statement:

$value;
$choice = 'Residential'

if($choice -eq 'Residential') {
    $value = 16.55
}
else {
    $value = 19.25
}

Write-Host 'Account Type: Residential'
Write-Host 'Value:       ' $value
Write-Host '========================='

This would produce:

PS C:\Windows\System32> C:\Exercises\Conditionals.ps1
Account Type: Residential
Value:        16.55
=========================

If you have a condition that can be checked as an if situation with one alternate else, you can use the ternary operator that is a combination of ? and :. Its formula is:

condition ? statement1 : statement2

The condition would first be checked. If the condition is true, then statement1 would execute. If not, statement2 would execute. Based on this, ehe above code can be written as follows:

$value;
$choice = 'Residential'

$value = $choice -eq "Residential" ? 16.55 : 19.25

Write-Host 'Account Type: Residential'
Write-Host 'Value:       ' $value
Write-Host '========================='

If you want to make your code easy to read, you can (should) include the condition in parentheses. This can be done as follows:

$value;
$choice = 'Residential'

$value = ($choice -eq "Residential") ? 16.55 : 19.25

Write-Host 'Account Type: Residential'
Write-Host 'Value:       ' $value
Write-Host '========================='

One or each of the statements can use an expression. Here are examples:

$environmentCharges = ($answer -eq "1") ? $usage * 0.0025 : $usage * 0.0125

$serviceCharges = ($answer -eq "1") ? $waterUsageCharges * 0.0328
                                        : $waterUsageCharges * 0.11643;

This time too, to make your code easy to read, you can include the statement in parentheses. Here are examples:

Write-Host 'Stellar Water Point'
Write-Host '======================================================'
Write-Output 'Types of Accounts'
Write-Output '1. Residential Household'
Write-Output '2. Laudromat'
Write-Output '3. Health Clinic'
Write-Output '4. Place of Worship/Youth Center'
Write-Output '5. Government Agency'
Write-Output '6. Other Business'

$selectedTypeOfAccount = 6
$counterReadingStart   = 41722
$counterReadingEnd     = 88061 
        
$firstTierTherms
$nextTierTherms
$lastTierTherms

$gallons               = $counterReadingEnd - $counterReadingStart
$HCFTotal              = $gallons / 748

$firstTierTherms       = 25.00 * 1.5573
$next15Therms          = 15.00 * 1.2264
$above40Therms         = ($HCFTotal - 40.00) * 0.9624

$waterUsageCharges     = $firstTierTherms + $next15Therms + $above40Therms
$sewerCharges          = $waterUsageCharges * 0.252

$environmentCharges    = ($selectedTypeOfAccount -eq "1") ? 
                         ($waterUsageCharges * 0.0025)    :
                         ($waterUsageCharges * 0.0125)
$serviceCharges        = ($selectedTypeOfAccount -eq "1") ?
                         ($waterUsageCharges * 0.0328)    :
                         ($waterUsageCharges * 0.11643)

$totalCharges          = $waterUsageCharges + $sewerCharges + $environmentCharges + $serviceCharges;

$localTaxes            = ($selectedTypeOfAccount -eq "1") ?
                         ($totalCharges * 0.002857)       : 
                         ($totalCharges * 0.005259)
$stateTaxes            = ($selectedTypeOfAccount -eq "1") ?
                         ($totalCharges * 0.000815)       :
                         ($totalCharges * 0.002262)

$amountDue = $totalCharges + $localTaxes + $stateTaxes

Write-Host '======================================================'
Write-Host 'Stellar Water Po$- Customer Invoice'
Write-Host '======================================================'
Write-Host 'Meter Reading'
Write-Host '------------------------------------------------------'
Write-Output 'Counter Reading Start:      ' $counterReadingStart
Write-Output 'Counter Reading End:        ' $counterReadingEnd
Write-Output 'Total Gallons Consumed:     ' $gallons
Write-Host '======================================================'
Write-Host 'Therms Evaluation'
Write-Host '------------------------------------------------------'
Write-Output 'HCF Total:                  ' $HCFTotal
Write-Output 'First 35 Therms (* 1.5573): ' $firstTierTherms
Write-Output 'First 20 Therms (* 1.2264): ' $next15Therms
Write-Output 'Above 55 Therms (* 0.9624): ' $above40Therms
Write-Host '------------------------------------------------------'
Write-Host 'Water Usage Charges:        ' $waterUsageCharges
Write-Host 'Sewer Charges:              ' $sewerCharges
Write-Host '======================================================'
Write-Host 'Bill Values'
Write-Host '------------------------------------------------------'
Write-Output 'Environment Charges:        ' $environmentCharges
Write-Output 'Service Charges:            ' $serviceCharges
Write-Output 'Total Charges:              ' $totalCharges
Write-Output 'Local Taxes:                ' $localTaxes
Write-Output 'State Taxes:                ' $stateTaxes
Write-Host '------------------------------------------------------'
Write-Host 'Amount Due:                 ' $amountDue
Write-Host '======================================================'

This would produce:

PS C:\Windows\System32> C:\Exercises\Conditionals.ps1
Stellar Water Point
======================================================
Types of Accounts
1. Residential Household
2. Laudromat
3. Health Clinic
4. Place of Worship/Youth Center
5. Government Agency
6. Other Business
======================================================
Stellar Water Po$- Customer Invoice
======================================================
Meter Reading
------------------------------------------------------
Counter Reading Start:       41722
Counter Reading End:         88061
Total Gallons Consumed:      46339
======================================================
Therms Evaluation
------------------------------------------------------
HCF Total:                   61.95053475935829
First 35 Therms (* 1.5573):  38.9325
First 20 Therms (* 1.2264):  18.396
Above 55 Therms (* 0.9624):  21.12519465240642
------------------------------------------------------
Water Usage Charges:         78.45369465240643
Sewer Charges:               19.77033105240642
======================================================
Bill Values
------------------------------------------------------
Environment Charges:         0.9806711831550804
Service Charges:             9.134363668379681
Total Charges:               108.3390605563476
Local Taxes:                 0.569755119465832
State Taxes:                 0.2450629549784583
------------------------------------------------------
Amount Due:                  109.15387863079191
======================================================

Variants of an Else Conditional Statement

If...elseif

If you use an if...else situation, you can process only two groups of statements. The first group is for the True condition. The other group is for the False condition. In some cases, you may deal with more than two conditions. In this case, you use an operator named elseif condition. The section the the elseif condition must come after an if section. The formula to use it is:

if(condition1) {
    statement_1
    statement_2
    . . .
    statement_X
}
elseif(condition2) {
    statement_1
    statement_2
    . . .
    statement_X
}

The first condition, condition1, would first be checked. If condition1 is true, then statement1 would execute. If condition1 is false, then condition2 would be checked. If condition2 is true, then statement2 would execute. Any other result would be ignored.

Considering Many Alternate Conditions

If you use an elseif section as introduced above, you mean you want to consider only valid options and reject anything else. In some cases, you may have a list of possibilities and you want to consider each. In that case, you can create an elseif section for each option. Here is an example that uses three options that include two elseif alternatives:

Write-Host '============================================'
Write-Host ' - Mississippi - State Income Tax -'
Write-Host '============================================'

$taxRate     = 0.00
$grossSalary = 3582.97 

# Mississippi
if($grossSalary -ge 10000) {
    $taxRate = 5.00
}
elseif($grossSalary -ge 5000) {
    $taxRate = 4.00
}
elseif($grossSalary -ge 1000) {
    $taxRate = 3.00
}

$taxAmount = $grossSalary * $taxRate / 100.00
$netPay    = $grossSalary - $taxAmount

Write-Host ' - Mississippi - State Income Tax -'
Write-Host '----------------------------------------------'
Write-Output "Gross Salary: $grossSalary"
Write-Output "Tax Rate:     $taxRate%"
Write-Output "Tax Amount:   $taxAmount"
Write-Output "Net Pay:      $netPay"
Write-Host '=============================================='

This would produce:

PS C:\Windows\System32> C:\Exercises\Conditionals.ps1
============================================
 - Mississippi - State Income Tax -
============================================
 - Mississippi - State Income Tax -
----------------------------------------------
Gross Salary: 3582.97
Tax Rate:     3%
Tax Amount:   107.4891
Net Pay:      3475.4809
==============================================

In the same way, you can create as many elseif alternatives as you judge them necessary. Here is an example:

Write-Host '=========================================='
Write-Host ' - Amazing DeltaX - State Income Tax -'
Write-Host '=========================================='

$taxRate
$stateName

Write-Host 'States'
Write-Host ' CO - Colorado'
Write-Host ' IN - Indiana'
Write-Host ' MI - Michigan'
Write-Host ' NC - North Carolina'
Write-Host ' PA - Pennsylvania'
Write-Host ' TN - Tennessee'
$abbr = "NC"

$grossSalary = 1497.68

if($abbr -eq "CO") {
    $taxRate   = 4.63
    $stateName = 'Colorado'
}
elseif($abbr -eq "IN") {
    $taxRate = 3.23
    $stateName = 'Indiana'
}
elseif($abbr -eq "MI") {
    $taxRate = 4.25
    $stateName = 'Michigan'
}
elseif($abbr -eq "NC") {
    $taxRate = 5.25
    $stateName = 'North Carolina'
}
elseif($abbr -eq "PA") {
    $taxRate = 3.07
    $stateName = 'Pennsylvania'
}
elseif($abbr -eq "TN") {
    $taxRate = 1.00
    $stateName = 'Tennessee'
}

$taxAmount = $grossSalary * $taxRate / 100.00
$netPay    = $grossSalary - $taxAmount

Write-Output '============================================'
Write-Output ' - Amazing DeltaX - State Income Tax -'
Write-Output '--------------------------------------------'
Write-Output "State Name:   $stateName"
Write-Output "Gross Salary: $grossSalary"
Write-Output "Tax Rate:     $taxRate%"
Write-Host '--------------------------------------------'
Write-Output "Tax Amount:   $taxAmount"
Write-Output "Net Pay:      $netPay"
Write-Host '============================================'

This would produce:

PS C:\Windows\System32> C:\Exercises\Conditionals.ps1
==========================================
 - Amazing DeltaX - State Income Tax -
==========================================
States
 CO - Colorado
 IN - Indiana
 MI - Michigan
 NC - North Carolina
 PA - Pennsylvania
 TN - Tennessee
============================================
 - Amazing DeltaX - State Income Tax -
--------------------------------------------
State Name:   North Carolina
Gross Salary: 1497.68
Tax Rate:     5.25%
--------------------------------------------
Tax Amount:   78.6282
Net Pay:      1419.0518
============================================

A Last Alternative

If you use one or more elseif sections as done above, it is still possible to have at least one possibility that doesn't fit any of those elseif options. To consider any option that doesn't fit any of the elseif options, you can add a last else option. The formula to follow is:

if(condition1) {
    if-statement_1
    if-statement_2
    . . .
    if-statement_n
}
elseif(condition2) {
    else-if-1-statement_1
    else-if-1-statement_2
    . . .
    else-if-1-statement_n
}
. . .
elseif(condition_n) {
    else-if-n-statement_1
    else-if-n-statement_2
    . . .
    else-if-n-statement_n
} 
else {
    else-statement_1
    else-statement_2
    . . .
    else-statement_n
}

The else section, when used must be the last from the other sections.


Previous Copyright © 2024-2025, FunctionX Tuesday 11 February 2025, 15:42 Next