Python Logo

Tuples

Key Terms

Conditional Statement
A declarative sentence that is generally has the form of "if-then". The first part of the sentence is called the "hypothesis" and the second part is called the "conclusion".

Introduction

Our programs so far were only capable of one and only one thing upon execution which limits what we can accomplish. We will use conditional statements to allow our program to change its behavior depending on certain conditions. A use case for this is when we (soon) create a program that allows for user input and depending on the type of input the program performs a different function. We will use these logical statements to create more complex programs.

Structure of a Conditional Statement

A conditional statement is a logical statement in the form "if-then". An example of a conditional statement is "If today is Tuesday then I buy groceries". Notice that there's two parts: the statement immediately after the "If" is called the "hypothesis". The part immediately following "then" is called the "conclusion".

Conditional Statements in Programming

In terms of programming, a conditional statement is used to perform a different action depending on if a condition stated in the hypothesis is true. This allows your program to perform different things depending on if a certain condition or set of conditions are met. An example is if a list contains the string "red" then print "Red is in the list!".

Creating a Conditional Statement

To create a conditional statement in Python, you simply use the keyword "if" and immediately state the condition and end it with a colon. The block of code you wish to run if the condition is met is indented in on the next line. An example of this is shown below:


          computers = ['hp', 'toshiba', 'dell', 'lenovo']
          for computer in computers:
            # Conditional statement checking for the string 'hp'.
            if computer == 'hp':
              print(computer.upper())
            else:
              print(computer.title())
        

          HP
          Toshiba
          Dell
          Lenovo
        

In the simple program above, we used a for loop to go through a list and then we used an "if" statement to check if there was a string 'hp' in the list. If that string was found in the list the the .upper() method is used to capitalize all the characters in the string to get "HP", anything else had the .title() method applied to it to capitalize the first letter.

Assignment Operator vs. Comparison Operator

Since we first started programming we have been using the equals sign, =, as an assignment operator that assigns a value to a variable. However, in computer science we also need to compare two values to check if they are in fact the same. This is where we can use the double-equal sign, ==, the comparison operator to check if two things are equal. Comparing two things returns a data type called a "boolean" which has one of two values, True or False.

Case Sensitivity

When we compare strings, we have to be aware that the comparison is "case-sensitive". This means that the string "hello" is different from the strings "Hello", "heLLo" or "helLO" or any other string that isn't exactly identical to it. To work with this we need to have strings with a consistent case, we will choose to make all the strings lower case in order to compare them.


          # Use the assignment operator to store the string 'hp' in the variable 'computer'
          computer = 'HP'
          
          # Comparision between 'HP' and 'hp'
          print(computer == 'hp')

          # Comparison between 'hp' and 'hp'
          print(computer.lower() == 'hp')
        

          False
          True
        

Checking for Inequality

In most cases, it is simplest to frame conditional statements on if a certain condition is true but there are some cases where checking if something is not true is more efficient. In order to do that we can use the negation operator denoted by an exclamation mark, !. With this operator we can reverse the truth value. This means that !True = False and !False = True. Similarly we can use != to denote "not equal to".


          my_computer = 'dell'
          # Check if the computer is not an HP
          if my_computer != 'hp':
            print("MY computer is not an HP")
          else:
            print("I have another type of computer.")
        

          My computer is not an HP
        

Numerical Comparisons

Numerical comparisons are pretty straightforward since we do not have to check the case on them. In addition to checking for equality we can also check for inequality as shown below.


          num = 45
          # Check for equality
          print(num == 45)
          # Check for inequality
          print(num != 45)
          # Check if the number is less than 20
          print( num < 20)
          # Check if the number is greater than 40
          print(num > 40)
        

          True
          False
          False
          True
        

Compound Conditional Statements

The AND Logical Operator

Sometimes we would like to check if two or more conditions are simultaneously true with the and logical operator. In its most simplest form the and logical operator is only true when BOTH conditions are true. Here is a truth table that demonstrates that.

P Q P AND Q
T F F
F T F
F F F
T T T

Here is a small program that demonstrates how to use the AND conditional statement in Python which conveniently has the keyword and.


          car_1 = 'mazda'
          car_2 = 'honda'
          # The AND operator evaluates to FALSE since one of the cars is a Mazda
          if car_1 == 'honda' and car_2 == 'honda':
            print('Both cars are Hondas!')
          else:
            print('One of the cars is not a Honda!')
        

          One of the cars is not a Honda!
        

The OR Logical Operator

Another type of logical operator is the OR operator. In short, the OR logical operator is only false when both statements are false; otherwise it is true.

P Q P OR Q
T F T
F T T
T T T
F F F

Below we have an example of a program using an OR logical operator. The program prints a slightly different message when either the variable computer holds either the string 'thinkpad' or 'alienware'


          computers = ['toshiba', 'dell', 'lenovo', 'hp', 'alienware', 'thinkpad']

          for computer in computers:
            if computer == 'thinkpad' or computer == 'alienware':
              print(f'A {computer} is a very nice computer!')
            else:
              print(f'The {computer} is a great computer!')
          print('We love computers!')
        

          The toshiba is a great computer!
          The dell is a great computer!
          The lenovo is a great computer!
          The HP is a great computer!
          A alienware is a great computer!
          A thinkpad is a great computer!
          We love computers!
        

Checking if an Element is Contained in a List

We can use the in and not in keyword(s) to check if an element is or is not in a list.


          # List of computers you own.
          computers = ['hp', 'dell', 'lenovo', 'toshiba']
          if 'thinkpad' in computers:
            print('I already have a thinkpad!')
          else:
            "I don't have a thinkpad yet!"
        

          I don't have a thinkpad yet!
        

Boolean Data Types

This section has taught us to think of expression as a value of TRUE or FALSE. These values can be referred to as Boolean data type. A boolean data type can store only one of two values: TRUE, FALSE. Booleans can be used to make a program perform different functions based on certain conditions.