Introduction to conditionals in Python

There are 5 skils you need to master in your toolset for building algorithms with python:

  1. Variables.
  2. Conditionals.
  3. Lists (or arrays).
  4. Loops.
  5. Functions.

The use of conditionals is the easies way we have to make decisions when coding our algorithms.

Let's say we are building a program to help us pick what to wear, but we hate the blue color, we could tell the computer to avoid that color using a statement like this:

if color == 'blue':
    #do something
else:
    #do something else or do nothing

Condicionales

🔗 Using switch is not available in python.

What is a logical expression in Python?

Logical expressions let you conditionally skip a series of lines of your code. The best wat to understand them, is to think of them like questions you can ask to the computer about your variables, for example:

  1. 21:
  2. if day == "tuesday"
  3. if car_model == "toyota" and number_of_tires == 6:

In order to ask a question, or conditionally excuse a particular set of lines, you first need to have data (information) stored on useful variables, above we had the variables user_age, day, car_model and number_of_tires.

If we don't have the information pre-stored in variables we are not able to ask any question, it is all about strategy and planning!

For example, if we have the user's age stored in a variable age then, and only then, we are able to code for something like:

# We use two equal signs when we want to compare two variables for equality
if age == 21:
    print("You are old enough!!")

What type of conditions/questions can we use/ask?

The previous example was a simple condition, but in real life picking what to wear involves a combination of several conditions to make the final decision, for example: Let's look at this algorithm that tells you if you have the flu

Hit by car or have a flu

If you want to represent this algorithm in Python it will look something like this:

feels_like_hit_by_train = True
you_were_hit_by_train = False

if feels_like_hit_by_train == True:
    if you_were_hit_by_train == True:
        print("You don't have a flu")
    else:
        print("You have a flu")
else:
    print("You don't have a flu")

Basically, this algorithm has two variables to consider: feels_like_hit_by_train and you_were_hit_by_train. Our job as developers is to sit down and try to prepare a strategy and come up with an algorithm that solves a problem.

Logical Operators in Python

Mostly all the questions can be asked using the following comparisons: ==, >, <, !=, is None, is not None, in:

OperatorExampleDescription
==if a == bif the value of variable A is identical to the value of B (same data-type and value)
<if a < bif the value of variable A is less than the value of B
> bif the value of variable A is greater than the value of B
!=if a != bif the value of variable A is different (not identical) from the value of B
is not Noneif a is not NoneThis is self-explanatory, isn't it?
is Noneif a is NoneThis is self-explanatory, isn't it?
inif name in ['bob','maria','nancy']If the value of name is contained inside the list of names

AND & OR Operators in python

Another way to write the algorithm is to combine to questions in the same condition using the and and or:

feels_like_hit_by_train = True
you_were_hit_by_train = False

if feels_like_hit_by_train and you_were_hit_by_train:
    print("You don't have a flu")
elif feels_like_hit_by_train:
    print("You have a flu")

As you can see here we are using elif together for the first time, for faster coding. Another trick you can use for faster coding:

OriginalEquivalent
instead of if(feels_like_hit_by_train == true)you write if(feels_like_hit_by_train)
instead of if(you_were_hit_by_train == false)you write if(!you_were_hit_by_train)

If...else in Python

You can also use the else expression to refer to the negation of the first condition:

if color == "blue":
    # Discard this clothing item
else:
    # Put it in your closet

age = 12
if age < 18:
    print("Old enough")
else:
    print("Not old enough")

You can also nest several if...else conditions on top of one another, like this:

if age < 16:
    # You cannot do anything
elif age < 18:
    # At this point, we know it's older than 15 because if not it would have entered
    # into the first condition
elif age < 21:
    # If the algorithm enters here, we know its older than 17
else:
    # If the algorithm enters here, we know its older than 20

Here is another example that runs an algorithm to find out if a number is in the "hundreds".

value = 14

if value < 10:
  print("Single unit value")
elif value < 100:
  print("dozens")
elif value < 1000:
  print("hundreds")
elif value < 10000:
  print("thousands")
else:
  print("hundrends of thousands or maybe more")

The switch statement in Python

Python does not have a switch statement.

Conclusion

It's all about what question to ask: The previous example was a simple condition, but real life is not that simple. There are lots of nested conditions and complicated flows that will challenge your skills to the limit. For example:

This will be the algorithm to pick what to wear on Valentine's Day:

What to ware in valentine's day

if going_out:
    if can_I_get_burger:
        if place_bottle_white:
            if cool_mix:
                # do something
    else:
        if blazers > 3:
            # do something
        else:
            # do something
    elif she_pants:
        # do something
    else:
        # do something
else:
    if naked_she_door:
        # do something
    elif blazers > 3:
        # do something
    else:
        # do something