2.5 Conditionals

Goals:

By the end of this lesson, I will be able to:

  1. Explain what a conditional is and how it is used to change a program’s flow
  2. Explain the order that a conditional uses to evaluate its statements
  3. Describe how Python uses indentation to identify parts of a program
  4. Create an if / else conditional
  5. Identify the parts of a conditional
  6. Explain the importance of order of conditional statements
  7. Create a conditional with an elif (else if) condition

Steps to Success:

  1. What are If Statements?
  2. Use the Tab Key: The Importance of Indentation
  3. Creating a Condition
  4. Advanced Conditionals: The elif
  5. Who Needs Else?
  6. The If Order Ordeal
  7. Challenge 1: Rollercoaster
  8. Challenge 2: Different Altitudes, Different Attitudes

If statements are conditionals, which are used to help your program make decisions. You actually use conditionals every day! Some examples might include:

  1. If my alarm goes off, then I will wake up. Else, I will stay asleep.
  2. If I am hungry, I will eat something.
  3. If it’s sunny out, I will wear sunscreen.
  4. If my room is clean, I will get my allowance. Else, I will make no money.

Watch the video below to learn more about conditionals:

Some important rules to remember:

  • If tests a condition ONCE. If the condition is true, it will do the steps indented under the If. Otherwise, it goes on to the next If or Else.
  • “Else” has no condition. This is because “else” is the last option when using if-else statements.  When a computer reaches the “else” option after checking all the other conditions, the else condition is automatically true and will run its statements.
  • One way to use “else” would be when something needs to happen when a condition is false. When the if condition is false and nothing needs to happen, you don’t need to use an “else”.

Indentation is very important in Python. The indentations indicate which statements belong to a particular section in the code.

You may have noticed that the statements below the if and else statements are indented 4 spaces or one tab. If you want to have multiple statements executed if a condition is true using proper indentation, it would look like this:

if battery_percentage > 60:

    print("Ready for takeoff!")

    drone.takeoff()

    drone.land()

else:

    print("Battery too low.")

Below is an incorrect example. Try running it to see what happens. Your goal: correct the example by indenting correctly and fixing the syntax.

drones = 100

bugs = 55

if drones > bugs print("Squish the bugs!")

else print("Fly away!")

The example should look something like this. Try running it now and change the values of drones and bugs.

drones = 100

bugs = 55

if drones > bugs:

    print("Squish the bugs!")

else:

    print("Fly away!")

Create 3 variables with different numerical values. Next, write at least 3 if statements and an else statement. Use the variables as the conditions for the if statements. The statements of the if statements and else statement should print different strings. The program below is an example — try writing your own!

import CoDrone_mini
drone = CoDrone_mini.CoDrone()
drone.pair()
 
x = 58
y = 12
z = 90
 
drone.takeoff()
if x > y:
   drone.set_pitch(50)
   drone.move(2)
if z > x:
   drone.set_roll(50)
   drone.move(2)
if y+z > x:
   drone.set_yaw(50)
   drone.move(2)
if y > z:
   drone.set_throttle(50)
   drone.move(2)
else:
   drone.land()

We have seen that standard conditionals with an IF and ELSE will give us 2 possible outcomes. But what if we want to have 3 or more possible outcomes? Watch the video below to learn more about how we can make this happen:

So what are the rules with elif (pronounced else if)?

  1. The first IF is evaluated. If it is true, it does this and skips the rest.
  2. If the first IF is False, the elif is evaluated. If true, it does the steps for the elif and skips the rest.
  3. If both the IF and ELIF are False, the else steps are executed.

Now that we know the primary parts of a conditional, what happens when we don’t have all those parts? Can a conditional not have an else or not have an elif? Watch the video below to find out!

Now that we know we don’t need an elif or else, let’s think of some examples where we might want just an if statement. Come up with 5 examples where you might need only an if.

Does the order of statements in a conditional matter? Copy the code below and then watch the video to follow along!

battery_power = 50
if(battery_power <40):
    print("battery is getting low")
elif(battery_power <20):
    print("battery level critical")
else:
    print("battery normal")

Now that we know order is important, try to find the error in the following code:

height = 35
if height > 20:
     print("Ready for movements!")
if height > 40:
     print("Altitude limit exceeded!")
elif height > 30: 
     print ("Warning! Approaching altitude limit")

Additionally, Answer the following questions about the code above:

  1. How many conditionals are there?
  2. What happens if your height variable is 35?
  3. What happens if your height variable is 15?
  4. What happens if your height variable is 25?
  5. What would you do to fix the error in this code?
  6. Will the program still run with the code as it is shown above?

Now, create and run your own code that has an ordering error in the conditional. Demonstrate how different values can return unexpected or unwanted results.

This challenge will be checking if a person is tall enough to ride a rollercoaster.

  • You’ll declare a variable called  height , which will represent height in inches.
  • The height should be checked at 48 and 36.
  • Anyone under 36 inches is not allowed to ride.
  • Riders between 36 and 48 inches can ride with a parent.
  • Riders above 48 inches can ride alone.

Add the drone in by having it throttle up for 3 seconds at 48 inches and above and at 2 seconds for 36-48 inches. For any variable under 36 inches, it should yaw for 1 second.

import CoDrone_mini

drone = CoDrone_mini.CoDrone()

drone.pair()


height = 66  # height in inches

drone.takeoff()


if height > 48:

    drone.set_throttle(50)

    drone.move(3)

    print("Rider can ride alone")

elif height > 36:

    drone.set_throttle(50)

    drone.move(2)

    print("Rider must be accompanied by parent")

else:

    drone.set_yaw(50)

    drone.move(1)

    print("Rider not allowed on the ride")

drone.land()

drone.close()This challenge will be checking our drone’s height and then having it move in different ways based on the height value. 

  • You’ll declare a variable called  height , which will represent height in inches.
  • Have height be a random value between 10 and 40
  • Check the height variable and have your drone do the following:
  • If the height is under 10, increase the drone’s height for 1 second
  • If the height is between 10 and 20, have the drone slide to the right for 1 second
  • If the height is between 20 and 30, have the drone slide to the left for 1 second
  • If the height is between 30 and 40, have the drone fly forward for 1 second