Lab 04 Pre Lab


Mastery of logic is essential to understanding conditional statements. It is used in pretty much any program that you will ever write. Comparisons are the heart of logical statements. When we write programs, we often want to compare two pieces of information, testing to see if that comparison evaluates to True or False. Then, we alter the way our program operates depending on the result of that comparison.

Comparison operators

We can make those comparisons using any of the following comparison operators, which compare two pieces of information:

For example:

Notice how you can mix variables and "raw" data and still make valid comparisons. Unlike the assignment operator (=), it doesn't matter what goes on the left hand or right hand side of a comparison operator.

Logical operators

You can also combine two or more comparison statements by using:

For example:

You do not have to use parentheses around a comparison statement, but it does have the benefit of making your code clearer and easier to read.

A third logical operator available to you is called not. This operates on one logical statement, flipping the truth value of that statement. So, a logical statement that is True will be flipped to False, and a logical statement that is False will be flipped to True.

For example:

Conditional statements

Being able to make comparisons is only the first part of conditional statements. We also need a structure to execute different code based on the value of a comparison. There are three such structures available: "if", "if-else", and "if-elif-else". These structures combine with one or more logical statements to form a conditional statement.


A basic "if" statement looks like this:

The print statement is only executed if the value of the variable age is larger than or equal to 65. Whatever is "inside" the if statement (meaning one indentation level in) will be executed if the logical statement used evaluates to True.

You must have an "if" statement before you use any "elif" statements or an "else" statement.


What if you want something different to happen if the logical statement is not True? To do this, just use an "else" statement right after an "if" like so:


What if there are several related logical statements you need to test? Simply use an "elif" in sequence with an "if".

Important: The very first logical statement that evaluates to True will have its associated code executed, and everything else will be skipped over. This means that only one of the code statments will be executed.