3.2. Conditionals#

Like Loops, Conditionals are an essential component of all programming languages. Conditionals are a type of logic in programming that allow you to control if something happens based on condition that something is true or false. Conditionals are always binary. I always find it useful to think about conditionals in plain English first.

If something is true, then do this. If that something is not true, then you can specify what should happen if that is the case. In pseudo code, it would look something like this:

if something is true:
    do this
if not:
    do this instead.

Notice again the indentation. As we progress throughout this chapter, you will learn three essential components of conditional statements:

Cheatsheet for Conditionals

code

description

if

Functions as the start of a condition.

else

Functions as ‘if not’

elif

Functions as “or if”.

3.2.1. If Statement#

Let’s begin with the if statement by first creating an object called x and make it equal to 0. Now, we can say if x is equal to 0, then print it off. Notice in the code below the : and the indentation afterwards. Just as we saw with loops, the : indicates that the next line should be indented. Whenever you have a line of code that uses a conditional statement, a : must always be at the end of the line to indicate to Python where that condition ends. The next line also, must always be indented.

x=0
if x==0:
    print (x)
0

We have successfully printed off x variable because the condition we stated is True. Let’s try and state the opposite of this. Let’s set our condition to x == 1.

if x==1:
    print (x)

Notice that nothing happens. This is because our condition is False. In the Trinket application below, try to create a conditional statement.

3.2.2. Else Statement#

If we want something to occur if that condition is not met, we can use the else statement. Think of else as “if not” in English. In pseudo-code, else would look something like this:

if this condition is True:
    do this
if not (else):
    do something else

Let’s write that out in real code.

if x==1:
    print (x)
else:
    print ("X is not 1")
X is not 1

Notice that else has the same indentation placement as the if and it too has a : followed by indented code. As noted above, all conditional statement lines must conclude with a colon and the proceeding line be indented.

The else statement is important because it allows a programmer to create more complex logic.

3.2.3. Elif and the ‘in’ Operator with Strings#

I debated including elif in this chapter for fear that it may introduce too many new things at once, but I think it is import to at least be familiar with its existence, even if you will not be using it right away. In English syntax, elif functions rather like “or if”.

if condition 1 is True:
    do this
or if (elif) condition 2 is True:
    do this instead

Within this paradigm, it functions a little differently than else. In an else statement, we perform a specific action if the preceding condition was False. With elif, we state that another condition must be true.

On the surface, this may seem to function as two sequential if statements, but it functions a little differently than a regular if statement. To understand how, it is best to see the elif statement in code.

In the code below, you will see within the conditional the word in, known as an operator. In Python, in functions rather like the way it functions in English. It is used to test if something is inside a piece of data or a data structure. So, if we want to know if some string is within another string, we can use in to see if that is the case.

In the example below, we want to know if a substring, or a smaller string, appears within the text variable.

text = "I know two people. Marge and Susan."
if "Marge" in text:
    print ("Marge Found")
elif "Susan" in text:
    print ("Susan Found")
Marge Found

This output may appear to be surprising. Both Marge and Susan are in the string, “text”. Why, then, do we not see “Susan Found” printed off? The reason is because elif only is triggered if one of the preceding if or other elif statements has not been triggered. If I wanted to check if both conditions were met, I would, instead, use two if statements, like so:

if "Marge" in text:
    print ("Marge Found")
if "Susan" in text:
    print ("Susan Found")
Marge Found
Susan Found

The elif statement allows for more robust logic and sequential conditionals to occur. When you first start programming, you may not use elif frequently, but it is important, even early in your programming career, to be familiar with it.

In the Trinket application bellow, create conditional statements.

IFrame("https://trinket.io/embed/python3/524597417f", 700, 356)

3.2.4. Conditionals and Lists with ‘in’ and ‘not in’#

Conditionals are frequently necessary when checking to see if something is in a list. Remember, lists are data structures that contain a list of data. The data contained within a list can be strings, integers, floats, or even other data structures, such as lists, tuples, and dictionaries. You will frequently need to understand what a list contains. To do this, we can use conditionals with the same in operator that we saw above.

Let’s begin by first making a list called names.

names = ["Terry", "Marge", "Joanne"]

Now that we have a list of names, let’s use the in operator to see if the name “Marge” is in names.

Warning

Remember: Python is case-sensitive.

In pseudo-code, we could write this as:

if Marge is in names:
    then print off True

Because Python resembles English syntax so closely, we only have to make a few modifications to make this work in actual code.

if "Marge" in names:
    print (True)
True

This same thing can also be done in reverse. What if we wanted to know if another person was not in names. We could write that as pseudo-code that looks something like this:

if Tom is not in names:
    then print off Tom is not on the list

Python makes this construction simple because the in operator has a negative version to, not in. This operator functions precisely the same way, but it is the opposite of the in operator. Let’s see it in action.

if "Tom" not in names:
    print ("Tom is not in the list.")
Tom is not in the list.

Notice that we have successfully created a conditional statement that checked to see if a string is not in names. Both in and not in also work with checking if a substring appears in a string. If we wanted to see if a a substring Jerry appears in the text Tom and Jerry, we could create a conditional that looks something like this:

if "Tom" in "Tom and Jerry":
    print("Tom found.")
Tom found.

In the Trinket application below, experiment with in and not in and conditional statements.

3.2.5. Conclusion#

This chapter has introduced the three essential components of conditional statements: if, else, and elif. I would recommend practicing with these on your own data. The best way to learn about conditionals is to use them. Remember, as you write them in Python, speak out loud in English. I still speak aloud (or in my mind) pseudo code as I write in proper Python syntax.

3.2.6. Quiz#

quiz = '''
# What are the three words you use to create conditional statements?
mc
* if
-c t
-f

* elif
-c t
-f

* else
-c t
-f

* then
-c f
-f

# Conditionals require you to indent.
mc
* True
-c t
-f

* False
-c f
-f

# Conditionals allow you to structure binary logic in your code.
mc
* True
-c t
-f

* False
-c f
-f

# Which of the following is a good example of a conditional statement?
mc
* if x > 0:
-c t
-f

* if x > 0
-c f
-f Remember, in Python a conditional statement should be followed by :

* if x = 0:
-c f
-f Remember, you use a double = to state equal to

* If x > 0:
-c f
-f Incorrect. Note the capitalized I in If
'''
from jupyterquiz import display_quiz
import md2json
import json
myquiz = md2json.convert(quiz)
myquiz = json.loads(myquiz)
display_quiz(myquiz)