Skip to main content

Computer Programming: Collections, Loops, and Conditions

Collections

  • In programming, we use collections to assemble two or more things together
  • Some collections allow you co-mingle data of varying types (e.g. strings mixed in with integers)
  • While other collections require that the data types are all the same
  • Some collections are immutable -- meaning that once created, they can't be modified
    • For example, your program may want to allow a user to only select a list of permitted items
    • Having it immutable keeps it safe from data manipulation
  • There is a wide variety of collection types, we'll be looking at the basics

Lists and Arrays

PowerShell
#######################
# Fixed-Length Arrays #
#######################

# Demonstrates the various ways to define arrays in PowerShell
$emptyArray = @()
$singleItemArray1 = @('cat')
$singleItemArray2 = , 'dog'
$newArray1 = [char]'a', 1, 'two', '3', [byte][char]'A'
$newArray2 = @([char]'a', 1, 'two', '3', [byte][char]'A')

# Print the contents and number of items in the arrays
$emptyArray.Count
$singleItemArray1
$singleItemArray1.Count
$singleItemArray2
$singleItemArray2.Count
$newArray1
$newArray1.Count
$newArray2
$newArray2.Count

# Attempt to add an item with the .Add() method
$newArray1.Add('new item') # Throws an error that array is a fixed size
$newArray1 # Demonstrate "new-item" was not added
$newArray1 += 'new-item' # Creates a new array with the existing items plus the new item
$newArray1 # Demonstrate "new-item" was added
$newArray1.Remove('new-item') # Demonstrate we cannot remove an item
$newArray1 = $newArray1 | Where-Object {$_ -ne 'new-item'} # Filter out the item and create a new array

# Replace items in the array
$newArray1 # Print the array contents
$newArray1[0] = 'replaced' # Replace the first item in the array
$newArray1 # Print the array contents to show the change


##########################
# Variable-Length Arrays #
##########################

# Most similar to Python Lists
# Create an ArrayList using .NET reflection
$arrayList = [System.Collections.ArrayList]::new(@(1, 2, 3))
$arrayList.Add(4)
$arrayList
$arrayList.Remove(4)
$arrayList


####################################
# Immutable Arrays (Python Tuples) #
####################################

$immutableArray = [System.Array]::AsReadOnly(@(1, 2, 3))
$immutableArray[0] = 100


#########################
# HashSet (Python Sets) #
#########################

# Requires the programmer to specify the data type stored in the HashSet
# Create a HashSet of strings
$stringHashSet = [System.Collections.Generic.HashSet[string]]::new()
$stringHashSet.Add('cat')
$stringHashSet.Add('dog')
$stringHashSet.Add('horse')
$stringHashSet.Add('cat')
$stringHashSet # Print the contents and demonstrate "cat" only exists once
Python
# Python handles collections quite differently from PowerShell
# Lists are collections of unrelated items and are mutable and variable-length
# You'll recall in the PowerShell example, we had to use the ArrayList type to create a variable-legnth array

#########################
# Variable-Length Lists #
#########################

# Demonstrates the various ways to define arrays in Python
empty_list = []
single_item_list = ['cat']
multi_item_list = [1, 2, 'cat', 'dog']

# Print the contents and number of items in the arrays
print(empty_list)
print(single_item_list)
print(len(single_item_list))
print(len(multi_item_list))

# Attempt to add an item with the append() method
multi_item_list.append('horse') # Add a horse to to the list
print(multi_item_list) # Observe the horse is now in the list

# Attempt to add an item with the remove() method
multi_item_list.remove('horse') # Remove the horse from the list
print(multi_item_list) # Observe the horse is no longer in the list


###########################################
# Tuples (Read-Only Arrays in PowerShell) #
###########################################

# Create a tuple containing a list of valid values
valid_values = ('dog', 'cat', 'horse') # This tuple contains three items
valid_values[0] = 'z' # Try and change the first item in the tuple to 'a', observe error


########
# Sets #
########

one_of_each = {'cat', 'dog', 'horse'} # Create a set of animals
one_of_each.add('cat') # Try and add another cat to the set
print(one_of_each) # Note there remains only one cat

Dictionaries and Hashtables

  • A dictionary (in Python) or hashtable (in PowerShell) represents a collection of key:value pairs
  • Key:Value meaning that if you fetch the key, you will get the value
PowerShell Hashtables
$countriesHashtable = @{
  'AU' = 'Australia'
  'CL' = 'Chile'
  'JP' = 'Japan'
  'KR' = 'Republic of Korea'
  'IN' = 'India'
  'PK' = 'Pakistan'
  'US' = 'United States of America'
}

$countriesHashtable.Count
$countriesHashtable['US'] # Fetch the "US" key and return the "United States of America" value
$countriesHashtable['KR'] # Fetch the "KR" key and return the "Republic of Korea" value
Python Dictionaries
countries_dictionary = {
    'AU': 'Australia',
    'CL': 'Chile',
    'JP': 'Japan',
    'KR': 'Republic of Korea',
    'IN': 'India',
    'PK': 'Pakistan',
    'US': 'United States of America'
}

print(len(countries_dictionary))
print(countries_dictionary['US']) # Fetch the "US" key and return the "United States of America" value
print(countries_dictionary['KR']) # Fetch the "KR" key and return the "Republic of Korea" value

Program Flow Control Logic

  • Flow control logic is a critical part of any program
  • As a programmer, you'll often be taking inputs from users and making a determination on how to proceed with the reset of the program depending said user input
  • At other times, it may not be direct user input, but perhaps some other environment variables based on conditions the user has created

If/Else Logic

if (try this first)
elseif (then, try this)
esleif (then, try this)
else (run this if all else fails)
PowerShell
$age = 20
if ($age -le 10) {
    # Run this code if
    # Age is less than or equal to 10
    Write-Host "Your bedtime is at 8:00 PM"
}
elseif ($age -gt 10 -and $age -le 18) {
    # Otherwise
    # Run this code if
    # Age is between 11 and 18
    Write-Host "Your bedtime is at 10:00 PM"
}
elseif ($age -gt 18 -and $age -le 30) {
    # Otherwise
    # Run this code if
    # Age is between 19 and 30
    Write-Host "Your bedtime is at midnight"
}
else {
    # Otherwise
    # Run this code if
    # Age is any other number
    Write-Host "Your bedtime is at 11:00 PM"
}

 

Python
age = 20
if age <= 10:
    # Run this code if
    # Age is less than or equal to 10
    print("Your bedtime is at 8:00 PM")
elif age > 10 and age <= 18:
    # Otherwise
    # Run this code if
    # Age is between 11 and 18
    print("Your bedtime is at 10:00 PM")
elif age > 18 and age <= 30:
    # Otherwise
    # Run this code if
    # Age is between 19 and 30
    print("Your bedtime is at midnight")
else:
    # Otherwise
    # Run this code if
    # Age is any other number
    print("Your bedtime is at 11:00 PM")

 

Multiple If Logic

if (try this)
if (also, try this)
if (also, try this)
PowerShell
$string = 'code'
if ($string -eq 'code') {
    # Check if this is true
    # Run this code if the string 'code' is stored in $string
    Write-Host "Code! Nice!"
}
if ($string.Length -eq '4') {
    # Not an 'else' block, so also check if this is true
    # Also, run this code if the string stored in $string is four characters long
    Write-Host "Your string is 4 characters long."
}
if ($string -eq 'yoda') {
    # Not an 'else' block, so also check if this is true
    # Also, run this code if the string 'yoda' is stored in $string
    # Obviously, it's not when looking at the code, but
    # Because this is not an else block, we check anyway
    Write-Host "Do or do not, there is no try."
}
Python
string = 'code'
if string == 'code':
    # Check if this is true
    # Run this code if the string 'code' is stored in the variable, string
    print("Code! Nice!")

if len(string) == 4:
    # Not an 'else' block, so also check if this is true
    # Also, run this code if the string stored in the variable, string is four characters long
    print("Your string is 4 characters long.")

if string == 'yoda':
    # Not an 'else' block, so also check if this is true
    # Also, run this code if the string 'yoda' is stored in the variable, string
    # Obviously, it's not when looking at the code, but
    # Because this is not an else block, we check anyway
    print("Do or do not, there is no try.")

Switch

Python does not natively have switch statement support, but adding here for clarity

PowerShell Switch Statement
$color = 'orange'
switch ($color) {
    
    'red' {
        # Run this code block if
        # The string 'red' is stored in $color
        # 'break' is required to complete
        # Code execution once a true condition is found
        Write-Host "Red."
        break
    }
    'orange' {
        # Run this code block if
        # The string 'orange' is stored in $color
        # 'break' is required to complete
        # Code execution once a true condition is found
        Write-Host "Orange."
        break
    }
    'yellow' {
        # Run this code block if
        # The string 'yellow' is stored in $color
        # 'break' is required to complete
        # Code execution once a true condition is found
        Write-Host "Yellow."
        break
    }
    'green' 
        # And, so on...
        Write-Host "Green."
        break
    }
    'blue' {
        # And, so forth...
        Write-Host "Blue."
        break
    }
    'indigo' {
        Write-Host "Indigo."
        break
    }
    'violet' {
        Write-Host "Violet."
        break
    }
    default  {
        # Run this code if none of the conditions match
        # For example, this would run if
        # The string, 'pink' is stored in $string
        Write-Host "Enter a valid color."
        break
    }

}

 

Loops

  • Loops are another core component to programming, usually used in conjunction with arrays
  • We loop over a set of data a specific number of times

Watch Out for Infinite Loops

  • Infinite loops are created when a condition never stops being True
  • 1 will always equal 1
  • a will always equal a
  • True will always be True
Infinite Loops

 Press CTRL + C to break out of an infinite loop in your testing 

PowerShell

while ($true) {
  Write-Warning 'Infinite loop!'
}

while (1 -eq 1) {
  Write-Warning 'Infinite loop!'
}

Python

while True:
  print('Infinite loop!')

while 1 == 1:
  print('Infinite loop!')
  

These examples are a bit contrived, but the point still stands. If you create a condition with your logic that never stops evaluating to True, then you will have created an infinite loop.

ForEach / For Loops

  • Take each item from the array one at a time and run some code
PowerShell foreach Loops
# Make an array of animals
# It's an array of strings
# Each string is an animal name
$animals = @('dog', 'cat', 'parrot', 'horse')

foreach ($animal in $animals) {
    Write-Host "Say hello to the $animal"
}

 

Python for Loops
# Make a list of animals
# It's a list of strings
# Each string is an animal name
animals = ['dog', 'cat', 'parrot', 'horse']

for animal in animals:
    print(f"Say hello to the {animal}")

 

image.png

For Loops

  • Python does not natively support for loops
  • Since PowerShell is tightly integrated into .NET there is support for these loops
PowerShell For Loops
$repetitions = 10 # How many times to repeat the loop
for ($counter = 0 ; $counter -lt $repetitions ; $counter++) {
    Write-Host "Loop $counter" # Run this code at each loop
}

# Explaining the code...
$counter = 0 # is an incrementer variable...
$counter++ # increates $counter by 1 every time the loop finishes
$counter -lt $repetitions # as long as $counter is less than $repetitions, keep looping

While Loops

  • While a condition is true, run some code
PowerShell While Loops
$counter = 0 # Set the variable to the integer zero

while ($counter -ne 10) {
    # While the $counter variable is not equal to 10...
    Write-Host $counter # Run this command
    $counter++ # Increase the value of $counter by 1
}
Python While Loops
counter = 0 # Set the variable to the integer zero

while counter != 10:
    # While the $counter variable is not equal to 10...
    print(counter) # Run this command
    counter += 1 # Increase the value of $counter by 1

Do-While Loops

  • Run some code while a condition is true
  • Just semantically different way of doing a while loop
  • No support in Python
PowerShell Do-While Loops
$counter = 0 # Set the variable to the integer zero


do {
    # Do this...
    Write-Host $counter # Run this command
    $counter++ # Increase the variable by 1
}
while ($counter -ne 10) # While this statement is true

 

Fun Project to Reinforce Some Concepts

https://benheater.com/intro-to-programming-powershell/#final-project