Booleans + Conditionals

einbahnstrasse.github.io/MTEC1003-slides/slides/python.conditionals.tutorial.v01/

MTEC1003 — Media Computation Skills Lab

In this tutorial, we’ll discuss…

Boolean Values

Boolean Operators

Boolean Expressions

and Conditionals

…but in Python, NOT JavaScript!…

…okay fine, we’ll also talk
a little bit about JavaScript too.
There, ya happy?!

So, let’s get started:

Sometimes

Ya gotta make a choice…

brush

In programming languages

These “choices” are called conditions
and they determine the course of actions our programs take.

brush

But they’re not just choices…

Conditions can indeed mean instructions
given to software programs by users:

brush

Evaluation

Or they can also also be used to evaluate our data.

brush

Notice the use of True and False in the last slide.

In programs like JavaScript and Python,
True and False are called:

Boolean Values

Booleans are values

just like other values types we’ve encountered:

integers

floating-point numbers

strings

And like these other value types, we can do lots with them…

For example, we can assign booleans to variables.
In JavaScript:

 var x = true;

(Notice in JS that the letter “t” is NOT capitalized.)

We can even create a new variable
based on a changing threshold:

 var belowFreezing = temperature < 32;

If the temperature variable is less than 32,

the belowFreezing variable will evaluate to: true.

Or if not, it will be: false.
view source

in Python

Boolean values are essentially the same…

But, we CAPITALIZE True and False

In programming languages,
boolean values only give us words for

“true” or “false.”

At some point, we want to identify

the quality of being “true” or “false”

in the stuff we’re talking about;
in the data we’re processing.

For this, we need to assign a boolean value
to a larger piece of language…
One that binds a boolean value to an object…

Behold! To assign a boolean value, we need a

Statement

the same way that we assign a variable.
Here’s a statement that does just that:

 var x = "I'm a string and now I equal variable x!";

But to assign a boolean value, we must use one of the

Boolean Operators

which can either be:

a logical operator
a comparison operator
or a conditional operator

Yikes! Srsly?!
This seems way too complicated.
What the hell are those things?

Comparison Operators

In JavaScript, we use these:

== (equal to)

=== (equal value AND equal type)

!= (not equal)

!== (not equal value OR not equal type)

> [or] < (greater than [or] less than)

<= (less than OR equal to)

>= (greater than OR equal to)

= vs. ==

Remember!
= is an assignment operator

and is only used to assign a value to something.
For determining equality, we instead
use the equality operators:

==
===
or
!=

Logical Operators

In JavaScript:

&& (logical “AND”)

|| (logical “OR”)

! (logical “NOT”)

Additionally, we can use a

Conditional Operator

to test for a boolean (true/false),
and then assign one of two values to our variable.
In JavaScript, we use the ? operator for this.

For example, in JavaScript:

 var voteable = (age < 18) ? "Too young":"Old enough";

If the age variable is less than 18,

voteable will be “Too young”.

Or if not, voteable will be “Old enough”.
view source

Plain English in Python

In Python, some operators look more like spoken language:

and (logical “AND”)

or (logical “OR”)

not (logical “NOT”)
How do these Python operators compare to JavaScript?

Special cases of this in Python include the operators:

is
is not

These aren’t the same as operators == or !=,
as you might have guessed…

is (or is not) vs. == (or !=)

Whereas == tests for the values
on both sides of the operator,
is tests for the same object.

Let’s demonstrate this with a quick example…

Here are 2 empty lists in Python:

  list1 = []
  list2 = []

(Remember! = does not mean “equal”!)

Now, if I evaluate this statement:

  result = list1 == list2
  print(result)

what do you think will happen?

Well, it will return True because the values contained inside the objects (the lists) are identical, i.e. they’re both empty!

But what if I evaluate this one?

  result = list1 is list2
  print(result)

Will it still be True?

It turns out to be False because, even though their values are the same, the objects are different. Both lists are stored in different locations in computer memory; one for list1 and another for list2. They’re the same type, and indeed contain the same values, but they are not at all the same object.

This means that the operators:

is
and
is not

tell us about the objects
and not just the values contained in them.

view source

With boolean operators and values, we can now form

Boolean Expressions

Boolean expressions evaluate to boolean values,

meaning a statement is evaluated
and its result is either True or False.

For example, this boolean expression in Python:

  result = 60 == (30 * 2)
  print(result)

will return the boolean value:

  True

whereas this boolean expression:

  result = 'there' == 'their'
  print(result)

will definitely be

  False

since the strings are not the same.

We can also form compound boolean expressions
by testing multiple statements at the same time.

For example:

  result = 4 > 0 and 2 < 1
  print(result)

What do you think the value of result will be?

In our console, we’ll see False because both of the expressions are not true. In this case, only one of them is true, and by using the operator and we’re requiring that both expressions be true.

Okay, I just can’t stop myself.
How about this one?

  result = 4 > 0 or 2 < 1
  print(result)

This time we’ll def get a True because at least one of the expressions is true. By invoking the operator or we’re dropping our requirement that both expressions be true.

Obviously, when evaluating multiple boolean expressions
things get complicated really fast!

Often we need to visualize all possible outcomes at once. This is done with a Truth Table. For example:

brush

To sort out the confusion, you can
read all about Truth Tables here.

So far we’ve examined:

boolean values
boolean operators
boolean expressions

We’ve now got all the building blocks we need
to make some fancy, shmancy conditions…

In addition to states of true- or false-ness,
we still need language to express
what will happen or what to do
in one scenario or another.

Each of these scenarios is a

Condition

If, then, else, else if

Think back, waaaayy back, many slides ago…
way back to your JavaScript Conditionals slides
and you’ll remember how a basic condition
is constructed in JavaScript:

  var a = parseInt(prompt("Give me a number, any number..."), 10);
  if (a > 5) {
    console.log(a);
  }

What does this conditional statement “say”?

If a is greater than 5, then print a to the console.”

In Python

the same story is told with a different construction:

  a = float(input("Give me a number, any number... "))
  if a > b:
    print(a)

So, what’s different in Python?

no semicolon ;

no brackets { or }

no (parens) around the boolean expression

use of a colon : following the boolean expression

But what about multiple conditions?

For this, we need another kind of statement:

Else if

To make an “else if” statement in JavaScript:

  var a = parseInt(prompt("Give me a number, any number..."), 10);
  if (a <= 40) {
    console.log("Your number is less than or equal to 40");
  } else if (a <= 60) {
    console.log("Your number is less than or equal to 60");
  } else {
    console.log("Your number is greater than 60");
  }

And what do the conditional statements “say”?

If a is less than or equal to 40, then print to the console.”

Or if a is less than or equal to 60, then print a 2nd message.”

Or if neither condition is true, print a 3rd message.”

Python Syntax

  a = float(input("Give me a number, any number... "))
  if a <= 40:
      print("Your number is less than or equal to 40")
  elif a <= 60:
      print("Your number is less than or equal to 60")
  else:
      print("Your number is greater than 60")

no semicolon ; as before

no brackets { or } as before

no (parens) as before

use of a colon : as before and…

elif instead of else if

brush

And what’s SIMILAR in both JavaScript and Python?

if

else

statements begin without indentation

statements always end with indentation
(i.e. the “then” clause)

can chain together multiple “elif”s (in JS: “else if”)…

Chaining ‘Elif’s

Let’s augment our Python to include multiple “scenarios”:

  a = float(input("Give me a number, any number... "))
  if a <= 40:
      print("Your number is less than or equal to 40")
  elif a <= 60:
      print("Your number is less than or equal to 60")
  elif a <= 100:
      print("Your number is less than or equal to 100")
  else:
      print("Your number is greater than 100")

You’re not limited to just 3: if / else if / else.
It’s easy to add as many conditions as you need!

How would you do this in JavaScript? Try it!

Compound Boolean Expressions in Conditions

We can also make a conditional statement
that includes compound boolean expressions.

For example, in Python:

  a = float(input("Give me a number, any number... "))
  if a >= 5 and a <= 40:
      print("Your number is in between; it's a sandwich!")
  elif a < 5 or a > 40:
      print("Your number is out-of-range!")
  else:
      print("Umm, you didn't type a number...")

Here, we’ve created an interval spanning the range 5-40:
\(a = \{ 5 \leqslant x \leqslant 40 \}, \forall x \in \mathbb{R}\)

Meaning: a is a set of all numbers x between (and including) 5 and 40, for all x contained in the set of Real whole numbers.

How would you do this in JavaScript? Try it!

Finé

Now, time to do the labs…