Introduction to Conditional Statements

Introduction

  • Programs so far have executed every line of code in the text file.
  • Conditional Statements allow us to execute specific blocks of code based on certain conditions.
  • We can use this functionality to make a program that reacts to user input.

Structure of a Conditional Statement

  • A conditional statement is a logical statement in the form "if-then".
  • "If today is Tuesday then I buy groceries"
  • Hypothesis
  • Conclusion

Creating a Conditional Statement

To create a conditional statement in Python, you simply use the keyword "if".


            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
          

Assignment Operator vs. Comparision Operator

  • Since we first started programming we have been using the equals sign, =, as an assignment operator
  • To compare two values to check if they are the same we can use the double-equal sign, ==, the comparison operator
  • This comparison returns a value of either True or False

Case Sensitivity

  • String comparisons are case-sensitive
  • 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.

Example


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

              False
              True
            

Checking for Inequality

  • There are some cases where checking if something is not true is more efficient
  • We can use the negation operator denoted by an exclamation mark, !
  • This operator reverses the truth value.
  • This means that !True = False and !False = True.
  • Similarly we can use != to denote "not equal to".

Example


              my_computer = 'dell'
              # Check if the computer is not an HP
              if my_computer != 'hp':
                print("My computer is not an HP")
              else:
                print("You have an HP 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


            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

Sometimes we would like to check if two or more conditions are simultaneously true with the and logical operator. Here is a truth table that demonstrates that.

The AND Operator

In its most simplest form the AND logical operator is only true when BOTH conditions are true.

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

Example

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 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

Example


                computers = ['toshiba', 'thinkpad', 'lenovo', 'hp', 'alienware', 'dell']
      
                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!
                A thinkpad is a very nice computer!
                The lenovo is a great computer!
                The HP is a great computer!
                A alienware is a very nice computer!
                The dell is a great computer!
                We love computers!