Control Structures - while/if

Today: loops, if-statement, maybe variables

See links to Python Guide front page: loops, if-logic, booleans

Big Picture: Patience + Legos

Hey Up Front: bit.front_clear()

While Loop - Power!

While Loop Demo

> Loop Demo

For reference, here is the code:

def loop_demo(filename):
    bit = Bit(filename)
    while bit.front_clear():

While Loop Syntax

Syntax 4 parts: while, test, colon, indented body lines

while boolean-test:
  body lines inside the while

While Loop Operation

While Loop Observations

If Statement - Logic

While loop is power. If-statement is control, controlling if lines are run or not

Problem statement: for each moved-to square, if it is blue, change it to green. Run it, then we'll talk about how the if-statement works.

> If Demo

For reference here is the code:

def if_demo(filename):
    bit = Bit(filename)
    while bit.front_clear():
        if bit.get_color() == 'blue':

If-Statement Deconstruction

Here is the key line of code:

    if bit.get_color() == 'blue':

1. bit.get_color() - Returns

2. == Compares Two Values - Boolean

3. How If Demo Works

If Statement Syntax

Syntax 4 parts (similar to "while"): if, boolean-test, colon, indented body lines

if boolean-test:
  body lines inside the if

If Statement Operation

With the basic if-structure in place, here are more boolean features, then we'll put it all together.

Bit Test: bit.left_clear()

Boolean Expressions: and or not

Boolean Examples..

Q1: when is the following if-test True?

    if bit.left_clear() and bit.right_clear():
        # when does this happen?

Q2: when is the following if-test True? (just changing and to or)?

    if bit.left_clear() or bit.right_clear():
        # when does this happen?

Q3: when is the following if-test True?

    if not bit.left_clear():
        # when does this happen?


A1: When either both left and right are clear

A2: When either left or right are clear (or both)

A3: When the left is blocked (i.e. lear_clear() returns False)

Put It All Together - Applied Boolean Code

> Bit Logic1 Exercises

First 3 are demos - walk through them

Then last 3 are little exercises to try .. see how many we get through today