Control Structures

Session Overview

  • Loops
  • If/Then
  • Case
  • Try/Except
  • Decorators

Control Structures

How and Why to use control structures?

  • Sequencing
  • Decision Making
  • Repeat based on criteria
  • Deploy/Scale our functions


Conditional

  • Make decisions based on criteria: True or False
  • Decide between two (or more) paths based on input
  • if, if-else, switch (case), nested if statements…

Looping

  • Repeat block of code until condition is met
  • Perform task multiple times
  • Iterating through elements
  • for, while, do-while

Flow Modifications: break, continue, exit, goto, etc.

Session Overview

  • Loops
  • If/Then
  • Case
  • Try/Except
  • Decorators

Loops


For Loop: Iterate over a sequence of elements.


for variable in sequence:
    # code to execute for each element in the sequence


variable takes on value of each element in sequence.


What will this output?:

numbers = [1, 2, 3, 4, 5]
for num in numbers:
    print(num)

Loops: Applications


Where can we use loops? Where shouldn’t we use loops?

  • Iterating through elements
  • Bootstrapping
  • Simulations
  • ?

Session Overview

  • Loops
  • If/Then
  • Case
  • Try/Except

If/Then


Execute code based on condition.

if condition:
    # code to execute if condition is true


> condition is an expression that evaluates to true or false.


Example:

num = 5
if num > 0:
    print("The number is positive")


What if we have alternatives?

if condition:
    # code to execute if condition is true
else:
    # code to execute if condition is false

Example:

num = -5
if num > 0:
    print("The number is positive")
else:
    print("The number is negative or zero")

Many Conditions

score = 75

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"

print("Your grade is", grade)


Is there a better way to do this?

Case/Switch Statements

lang = input("What's the programming language you want to learn? ")

match lang:
    case "JavaScript":
        print("You can become a web developer.")

    case "Python":
        print("You can become a Data Scientist")

    case "PHP":
        print("You can become a backend developer")
    
    case "Solidity":
        print("You can become a Blockchain developer")

    case "Java":
        print("You can become a mobile app developer")
    case _:
        print("The language doesn't matter, what matters is solving problems.")


Important Notes:

  • First case to evaluate to true wins!
  • Important to include default condition… what you want to happen if there is no match.

Conditional Applications


Where can we use conditional statements?

  • Data Filtering
  • Quality Control
  • Group Management
  • Decision Recommendations

Session Overview

  • Loops
  • If/Then
  • Case
  • Try/Except
  • Decorators

Try/Except


Error Handling!

  • Detect errors during runtime
  • Handle those errors during runtime

Examples:

try:
    x = 1 / 0
except ZeroDivisionError:
    print("Error: division by zero")
try:
    x = int("hello")
except ValueError:
    print("Error: invalid value")
except TypeError:
    print("Error: type mismatch")


try:
    x = 1 / 0
except ZeroDivisionError:
    print("Error: division by zero")
finally:
    print("Cleanup code")

Error Handling Applications


Where should you handle errors?

Session Overview

  • Loops
  • If/Then
  • Case
  • Try/Except
  • Decorators

Decorators

A Python function that takes a function as an argument and returns a new function.


Allow you to modify the functionality of a function by wrapping it in another function.

Decorator Syntax

Decorators are implemented using the “@” symbol followed by the name of the decorator function. They are placed before the function definition.

@decorator
def function():
    # function body

Making a Decorator

def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()

Decorator Applications

  • Logging
  • Authentication
  • Caching
  • Rate Limiting
  • Deployment
  • Scaling

Decorator Scaling

Note this is pseudo-code:

def launch_on_cloud(func):
    def wrapper(*args, **kwargs):
        spin_up_workers(num_instances, num_cpus, ram)
        result = func(*args, **kwargs)
        collect_results(result_location)
        return result
    return wrapper

@launch_on_cloud
def regrid_gid_point(dataset):
    ...

regrid_grid_point(netcdf_data)