Booleans and Conditions

In this lecture, we investigate the notion of variable scope when calling functions.

Then we explore the boolean types True and False in Python, relational and logical operators, and how they help making decisions using the if- else conditional blocks.

Variable Scope

Local variables. An assignment to a variable within a function definition creates/changes a local variable. Local variables exist only within a function's body, and cannot be referred to outside of it. Parameters are also local variables that are assigned a value when the function is invoked.

Boolean Type and Relational Operators

True and False are of type bool in Python and naturally occur as a result of relational operators (<, >, ==, !).

Conditional Statement: If Else

We can ensure that some statements in the program are evaluated conditionally only if the result of a Boolean expression evaluates to True using an if statement. If the Boolean expression evaluates to False, then the control flow skips statements under the if block and evaluates the statements under the else block.

If Else Statement Syntax

statement 1
statement 2
if (boolean expression):
       statement 3
       statement 4
      ...
else:
       statement 5
       statement 6
      ...
statement 7

Indentation matters in Python

Indented statements form a logical block of code in Python:

Checking if a Number is Even

Let us write a function printEven that takes a number as input. If the number is even, it prints "Even", else it prints "Odd".

Question. How can we check if a number is even?

Exercise. Let us write the function print_even(num) below.

Exercise. Suppose instead of printing, we want to return True if num is even, and False if number is odd. Let us define an is_even(num) that does this.

Else block is optional

An if statement does not need an else, and there are often times when removing the else block makes the program shorter. (Although stylistically, you may prefer to include the else.)

Simplify. We can simplify the is_even function by removing the else block, and return False if the if condition fails.

Simplify further. We can shorten it even further and just return the result of the Boolean expression. This is the best approach!

Tracing Control Flow Through Conditionals

Consider the following example of a function zeroToOne() that takes a number num as input. If the number is equal to zero, it adds one to num and returns it. Otherwise it just returns num.

Let us trace the control flow when the function is called with different values of num. We can use print statements in our code to see the control flow of the program.

In situations like this function, it is a good idea to have a single return statement, rather than a return statement in each conditional block.

Notice: Statements above the if block and after the else block are always executed.