Lec 6: conditionals and boolean algebra

Lecture 6

Conditionals & Boolean Algebra

MCS 260 Fall 2020
Emily Dumas

Reminders

  • No class Monday (Labor day)
  • Quiz 2 due 6pm central on Tue Sep 8
  • Project 1 description will be posted today
    • Project 1 due Fri Sep 18

A tricky list

What do you expect this code to do?

Will it produce an error?


    L = ["a","b","c"]
    L[0] = L
    print(L)
    

Conditionals

You can indicate that a section of code should only execute if certain conditions are met.

Syntax:


    if condition:
        statement
        statement
        ...
    statement that runs regardless of the condition
    

Indenting statements below $\texttt{if}$ by the same amount makes them a code block. The block ends when a line is vertically aligned with $\texttt{if}$.

In many other languages, special symbols are used to indicate the start and end of a block, and indenting is ignored.

$\texttt{\{}$ and $\texttt{\}}$ are common choices.

Python uses indenting as a substitute for block start / block end symbols.


    n = int(input("How many penguins live with you? "))
    if n > 150:
        print("That's quite a crowd!")
    print("Thank you for completing the penguin census.")

This example uses four spaces to indent. That is the recommended (and most popular) number.

Spaces vs tabs

The code point $\texttt{U+0009}$ is "CHARACTER TABULATION", better known as "tab".

Python allows this character to be used for indenting, but recommends against it, and forbids mixing spaces and tabs.

Depending on your editor, pressing the Tab key may:

  • Insert a fixed number of spaces
  • Insert a context-dependent number of spaces
  • Insert $\texttt{U+0009}$

Recommendation for Python coding:

Configure your editor to never insert $\texttt{U+0009}$.

This is often the default behavior.

Conditions

Python supports a lot of conditions (tests) that can appear in an $\texttt{if}$ statement, e.g. comparison operators:
$\texttt{>}$ is greater than
$\texttt{<}$ is less than
$\texttt{==}$ is equal to
note two equal signs!
$\texttt{!=}$ is not equal to
$\texttt{>=}$ is greater than or equal to
$\texttt{<=}$ is less than or equal to

else

An $\texttt{if}$ statement can be followed by $\texttt{else:}$ and a code block to be executed if the condition is False.


        if x == 100:
            print("x is equal to 100")
        else:
            print("x is NOT equal to 100")
    

This is useful for handling dichotomies.

elif

An $\texttt{if}$ statement can also be followed by $\texttt{elif}$ (for "else if"), which begins a new conditional.


        if x == 100:
            print("x is equal to 100")
        elif x % 4 == 0:
            print("x is a multiple of 4, but is not equal to 100")
        elif x % 2 == 0:
            print("x is even, but is not a multiple of 4")
        else:
            print("x is odd")
    

A chain of $\texttt{if}/\texttt{elif}/\texttt{elif}/...$ is the typical way to compare a variable to multiple values or categories.

Example: quadroots.py


# Determine the number of real roots of a quadratic polynomial
# MCS 260 Fall 2020 Lecture 6 - Emily Dumas
print("Enter the coefficients a,b,c of ax^2+bx+c, one per line.")
a = float(input())
b = float(input())
c = float(input())

print("You entered:",a,"x^2 +",b,"x +",c)

discriminant = b**2 - 4*a*c

if discriminant > 0:
    print("This polynomial has two real roots.")
elif discriminant == 0:
    print("This polynomial has exactly one real root.")
else:
    # Now we know discriminant < 0
    print("This polynomial doesn't have any real roots.")

More conditions

$x \texttt{ in } seq$ Sequence $seq$ contains an item equal to $x$
$x \texttt{ not in } seq$ (negation of above)
$cond_0 \texttt{ and } cond_1$ Both $cond_0$ and $cond_1$ are True.
$cond_0 \texttt{ or } cond_1$ At least one of $cond_0$ and $cond_1$ is True.
$\texttt{ not } cond$ $cond$ is False.

Precedence

Comparison operators all have lower precedence than arithmetic, so e.g. $\texttt{5*5>30-10}$ evaluates as True. The order is:

  1. Arithmetic (PEMDAS)
  2. $\texttt{>, >=, <, <=}$
  3. $\texttt{==, !=}$
  4. $\texttt{in, not in}$
  5. $\texttt{and, or, not}$

bool

$\texttt{bool}$, for "boolean", is a type that has only two possible values, $\texttt{True}$ and $\texttt{False}$.

Conditions in $\texttt{if}$ or $\texttt{elif}$ actually evaluate as $\texttt{bool}$s, and you can have $\texttt{bool}$ variables, too.


everything_will_be_ok = True
missed_quiz_deadline = False
x = 1 < 2   # x is now True
y = 3 > 4   # y is now False
if x and not y:
    print("Good news: math is not broken.")

Boolean algebra

Booleans are also considered in math / theoretical CS.

Different symbols are often used for boolean operators:

$x \land y$ means $x$ and $y$
$x \lor y$ means $x$ or $y$
$\lnot x$ means not $x$

In addition, $\bar{x}$ or $!x$ are sometimes used for $\lnot x$.

The operators $\land$ and $\lor$ are commutative and associative. They obey algebraic rules such as:
  • $\lnot(\lnot x) = x$
  • $x \lor x = x$ and $x \land x = x$
  • $x \lor (\lnot x) = \texttt{True}$, $x \land (\lnot x) = \texttt{False}$
  • $x \lor \texttt{True} = \texttt{True}$, $x \lor \texttt{False} = x$, $x \land \texttt{False} = \texttt{False}$, $x \land \texttt{True} = x$.
  • Distributive law:
    $x \land (y \lor z) = (x \land y) \lor (x \land z)$
  • DeMorgan's law:
    $\lnot ( x \land y ) = (\lnot x) \lor (\lnot y)$,
    $\lnot ( x \lor y ) = (\lnot x) \land (\lnot y)$

Once you decode what these rules are saying, all but the named ones will probably become obvious.

If I ever ask you to perform boolean algebra simplification, I will provide this list.

These rules can be used to simplify boolean expressions, e.g.

$x \texttt{ and not } (x \texttt{ and }y)$
$\rightarrow \; x \land \lnot(x \land y)$ Math notation
$\rightarrow \; x \land ((\lnot x) \lor (\lnot y))$ DeMorgan
$\rightarrow \; (x \land (\lnot x)) \lor (x \land (\lnot y))$ Distributive
$\rightarrow \; \texttt{False} \lor (x \land (\lnot y))$
$\rightarrow \; x \land (\lnot y)$
$\rightarrow \; x \texttt{ and not }y$

Back to the tricky list

What do you expect this code to do?

Will it produce an error?


    L = ["a","b","c"]
    L[0] = L
    print(L)
    

Answer: No error. A list in Python can contain itself.


        >>> L = ["a","b","c"]
        >>> L[0] = L
        >>> print(L)
        [[...], 'b', 'c']
        >>> L[0] == L
        True
    

The "$\texttt{...}$" is there so that the print function doesn't get stuck constructing an infinite output!

References

Revision history

  • 2020-09-04 Typo fix
  • 2020-09-04 Initial publication