Conditionals

Overview

Dynamically changing which part of a program is executed can make for more sophisticated logic. Perhaps you used to read choose-your-own-adventure books? Here's an example of a branching story using an interactive storyboard platform.

We can implement branching behavior using conditionals.

A condition is described with an expression that evaluates to either yes or no. We commonly this type of data when considering yes/no questions in everyday life, like “is it raining?”, “are you hungry?”.

In programming, we say that conditions evaluate to either True or False. Generally, programming languages have a boolean type that contains just those two values: true and false. In this topic, we'll focus on the boolean type, how to write expressions that evaluate to either true or false, and how to use boolean expressions to execute code only when a conditions is true.

Boolean type

Remember that we saw an introduction to the boolean type at the start of the course.

A boolean can only have one of two values: True or False.

Boolean operators

We also saw that there are different boolean operators available to us in Python.

Truth tables

Because booleans can only take on 2 possible values, we can completely describe the behavior of an operator using a "truth table."

Some operators are unary (the not operator takes in a single operand) while others are binary (the and, or and xor) take in two operands. Unary operators will have 2 rows, one for each possible value of the single operand, while binary operators will have 4 rows, one for each possible pair of operand values.

(If we had a ternary operator with three operands, there would be 8 rows -- each operand can take 2 values, so we get 2*2*2 possibilities. In general, an operator with n operands would have 2 rows.)

Here are the truth tables for the not and or operators.

Can you come up with the truth tables for and and xor?

Relational operators

A boolean expression is an expression that evaluates to a single boolean value. We have already seen the boolean operators (not, and and or). When we use these, we are creating a boolean expression.

We can also use relational operators to compare two values and get a boolean value in return.

Some of these operators might look a bit unusual to you. For example, we use the two character sequence <= to mean less than or equal to rather than the mathematical notation ≤. (One of these is easier to type than the other!)

Equality testing uses the == operator

Note that we use == (two = characters) to compare values for equality. The = operator is what we use to assign a value to a variable, so it is already taken.

Comparing String values

We can use the same operators compare strings using lexicographic ordering.

Conditional constructs

Conditional structures allow Python to dynamically control which code to execute, based on the value of a boolean expression.

The if construct

The general format of an if construct is the same across most programming languages, though the syntax will differ by language. Here is the syntax for Python:

if <boolean-expression> :

# any code indented one level executes if <boolean-expression> evaluates to True


<boolean-expression> can be any boolean expression, like x > 10, name == "Mary". If the expression evaluates to True, the code block (indented one level below) will be executed; otherwise, it will not execute. Afterwards, program control continues to the code following the if construct.

Try running these examples using Python Tutor see them in action.

if 2 < 3:

# this code will execute if the condition is True

print( "2 is less than 3!" )

print( "I'm done comparing..." )

which outputs:

2 is less than 3!

I'm done comparing...

if 2 < 2:

# this code will execute if the condition is True

print( "2 is less than 2 -- something's wrong!" )

print( "I'm done comparing..." )

which outputs:

I'm done comparing...

The if/else construct

Suppose you want one thing to happen when a condition is True, but a different thing to happen when it is False. This is handled by the if/else construct.

The general format of an if/else construct is the same across most programming languages, though the syntax will differ by language. Here is the syntax for Python:

if <boolean-expression> :

# any code indented one level executes if <boolean-expression> evaluates to True

else:

# any code indented one level executes if <boolean-expression> evaluates to False


If the boolean expression evaluates to True, the associated code block (indented one level below) will be executed, and the next code block (indented one level below the else) will not. If the expression evaluates to False, the code block (indented one level below) will not be executed, and the next code block (indented one level below the else) will. Afterwards, program control continues to the code following the entire if/else construct.

Try running these examples using Python Tutor see them in action.

if 2 < 3:

# this code will execute if the condition is True

print( "2 is less than 3!" )

else:

# this code will execute if the condition is False

print( "2 is not less than 3?? Something's wrong!" )

print( "I'm done comparing..." )

which outputs:

2 is less than 3!

I'm done comparing...

if 2 < 2:

# this code will execute if the condition is True

print( "2 is less than 2 -- something's wrong!" )

else:

# this code will execute if the condition is False

print( "Whew, 2 is not less than 2!" )

print( "I'm done comparing..." )

which outputs:

Whew, 2 is not less than 2!

I'm done comparing...

The if/elif/else construct

Suppose you have multiple conditions to check and want a different block of code associated with each. This is handled by the if/elif/else construct.

The general format of an if/elif/else construct is the same across most programming languages, though the syntax will differ by language. Here is the syntax for Python:

if <boolean-expression> :

# any code indented one level executes if the boolean expression evaluates to True

elif <boolean-expression> :

# any code indented one level executes if the first boolean expression evaluates to False and

# the second boolean expression evaluates to True

else:

# any code indented one level executes if both boolean expressions evaluate to False


Here, the first “branch” of the if-statement whose boolean expression evaluates to True will be executed and all the others will be skipped. If none of the boolean expressions evaluates to True, the code on the else branch is executed.

Note

  • The first branch must be an if branch.

  • There can be any number of elif branches, including zero.

  • The conditions themselves will be evaluated in order. The first one that evaluates to True is the branch that will be executed, so be careful about the order that you put the branches in.

  • The else branch is optional. If it is there, it must come last.

What do you think will print out after executing each of these programs?

x = 1

if x >= 13 :

print( "Hello!")

elif x == 3.1 :

print( "Hi!" )

elif x <= 13 :

print( "Hey!" )

elif x <= 1 :

print( "Welcome!" )

else:

print( "Goodbye." )

Program A

x = 3

if x >= 13 :

print( "Hello!")

if x == 3.1 :

print( "Hi!" )

if x <= 13 :

print( "Hey!" )

if x <= 1 :

print( "Welcome!" )

else:

print( "Goodbye." )

Program B