Class Notes: Conditionals

Boolean Type:

Comparison operators:

Equality

"Disequality" (not equal)

Less than

Less than or equal

Greater than

Greater than or equal

Boolean operators:

Just like we have operators with numeric types, we also have operators with booleans

And

a b a and b
True True True
True False False
False True False
False False False

Or

a b a or b
True True True
True False True
False True True
False False False

Not

a not a
True False
False True

If conditions

if-else

if (without else)

If an else case "does nothing", we can get rid of it.

Exercise 1: sign function

Write the function that implements the signum function: $$ \text{sgn }x := \begin{cases} -1 & \text{if } x < 0 \\ 0 & \text{if } x = 0 \\ 1 & \text{if } x > 0 \end{cases}$$

When we need multiple conditional expressions after the if condition or between the if and else conditions, we can use the if-elif statements:

if-elif

Act like a computer

What's the output of the following function for x = 3?

The answer is 10

Exercise 2: middle number

Implement the function middle(a, b, c) that takes three different numbers as input, and returns the middle among them.

Let's enumerate all possible cases

$ b < a < c$

$ c < a < b$

$ a < b < c$

$ c < b < a$

$ a < c < b$

$ b < c < a$

Solution only with if statements

Another solution using elif statements

Another solution using elif statements and else at the end

Another equivalent solution with fewer checks

Another (more compact) solution

All previous solutions are equivalent and correct