Python 101: Conditional Statements

Developers have to make decisions all the time. How do you approach this problem? Do you use technology X or technology Y? Which programming language(s) can you use to solve this? Your code also sometimes needs to make a decision.

Here are some common things that code checks every day:

  • Are you authorized to do that?
  • Is that a valid email address
  • Is that value valid in that field?

These sorts of things are controlled using conditional statements. This topic is usually called control flow. In Python, you can control the flow of your program using if, elif and else statements. You can also do a crude type of control flow using exception handling, although that is usually not recommended.

Some programming languages also have switch or case statements that can be used for control flow. Python does not have those.

In this chapter you will learn about the following:

  • Comparison operators
  • Creating a simple conditional
  • Branching conditional statements
  • Nesting conditionals
  • Logical operators
  • Special operators

Let’s get started by learning about comparison operators!

Would you like to learn more about Python?

Python 101 – 2nd Edition

Purchase now on Leanpub

Comparison Operators

Before you get started using conditionals, it will be useful to learn about comparison operators. Comparison operators let you ask if something equals something else or if they are greater than or less than a value, etc.

Python’s comparison operators are shown in the following table:

Operator Meaning
> Greater than – This is True is the left operand is greater than the right
< Less than – This is True is the left operand is less than the right one
== Equal to – This is True only when both operands are equal
!= Not equal to – This is True if the operands are not equal
>= Greater than or equal to – This is True when the left operand is greater than or equal to the right
<= Less than or equal to – This is True when the left operand is less than or equal to the right

Now that you know what comparison operators are available to you in Python, you can start using them!

Here are some examples:

>>> a = 2
>>> b = 3
>>> a == b
False
>>> a > b
False
>>> a < b
True
>>> a >= b
False
>>> a <= b
True
>>> a != b
True

Go ahead and play around with the comparison operators yourself in a Python REPL. It’s good to try it out a bit so that you completely understand what is happening.

Now let’s learn how to create a conditional statement.

Creating a Simple Conditional

Creating a conditional statement allows your code to branch into two or more different paths. Let’s take authentication as an example. If you go to your webmail account on a new computer, you will need to login to view your email. The code for the main page will either load up your email box when you go there or it will prompt you to login.

You can make a pretty safe bet that the code is using a conditional statement to check and see if you authenticated/authorized to view the email. If you are, it loads your email. If you are not, it loads the login screen.

Let’s create a pretend authentication example:

>>> authenticated = True
>>> if authenticated:
...     print('You are logged in')
... 
You are logged in

In this example, you create a variable called authenticated and set it to True. Then you create a conditional statement using Python’s if keyword. A conditional statement in Python takes this form:

if <expression>:
    # do something here

To create a conditional, you start it with the word if, followed by an expression which is then ended with a colon. When that expression evaluates to True, the code underneath the conditional is executed.

If authenticated had been set to False, then nothing would have been printed out.

Indentation Matters in Python

Python cares about indentation. A code block is a series of lines of code that is indented uniformly. Python determines where a code block begins and ends by this indentation.

Other languages use parentheses or semi-colons to mark the beginning or end of a code block.

Indenting your code uniformly is required in Python. If you do not do this correctly, your code may have a hard time diagnosing issues.

One other word of warning. Do not mix tabs and spaces. IDLE will complain if you do and your code may have hard to diagnose issues. The Python style guide (PEP8) recommends using 4 spaces to indent a code block. You can indent your code any number of spaces as long as it is consistent. However, 4 spaces are usually recommended.

This code would be better if you handled both conditions though. Let’s find out how to do that next!

Branching Conditional Statements

You will often need to do different things depending on the answer to a question. So for this hypothetical situation, you want to let the user know when they haven’t authenticated so that they will login.

To get that to work, you can use the keyword else:

>>> authenticated = False
>>> if authenticated:
...     print('You are logged in')
... else:
...     print('Please login')
... 
Please login

What this code is doing is that if you are authenticated, it will print “You are logged in” and when you are not, it will print “Please login”. In a real program, you would have more than just a print() statement. You would have code that would redirect the user to the login page or if they were authenticated, it would run code to load their inbox.

Let’s look at a new scenario. In the following code snippet, you will create a conditional statement that will check your age and let you purchase different items depending on that factor:

>>> age = 10
>>> if age < 18:
...     print('You can buy candy')
... elif age < 21:
...     print('You can purchase tobacco and candy, but not alcohol')
... elif age >= 21:
...     print('You can buy anything!')
... 
You can buy candy

In this example, you use if and elif. The keyword, elif is short for “else if”. So what you are doing here is that you are checking the age against different hard-coded values. If the age is less than 18, then the buyer can only buy candy.

If they are older than 18 but less than 21, they can purchase tobacco. Of course, you shouldn’t do that because tobacco is not good for you, but it has an age restriction in most places. Next you check if the buyer’s age is greater than or equal to 21. Then they can buy whatever they want.

You could change the last elif to be simply an else clause if you wanted to, but Python encourages developers to be explicit in their code and it’s easier to understand by using elif in this case.

You can use as many elif statements as you need, although it is usually recommended that when you see a long if/elif statement, that code probably needs to be reworked.

Nesting Conditionals

You can put an if statement inside of another if statement. This is known as nesting.

Let’s look at a silly example:

>>> age = 21
>>> car = 'Ford'
>>> if age >= 21:
...     if car in ['Honda', 'Toyota']:
...         print('You buy foreign cars')
...     elif car in ['Ford', 'Chevrolet']:
...         print('You buy American')
... else:
...     print('You are too young!')
... 
You buy American

This code has multiple paths that it can take because it depends on two variables: age and car. If the age is greater than a certain value, then it falls into that code block and will execute the nested if statement, which checks the car type. If the age is less than an arbitrary amount then it will simply print out a message.

Theoretically, you can nest conditionals any number of times. However, the more nesting you do, the more complicated it is to debug later. You should keep the nesting to only one or two levels deep in most cases.

Fortunately, logical operators can help alleviate this issue!

Logical Operators

Logical operators allow you to chain multiple expressions together using special keywords.

Here are the three logical operators that Python supports:

  • and – Only True if both the operands are true
  • orTrue if either of the operands are true
  • notTrue if the operand is false

Let’s try using the logical operator, and with the example from the last section to flatten your conditional statements:

>>> age = 21
>>> car = 'Ford'
>>> if age >= 21 and car in ['Honda', 'Toyota']:
...     print('You buy foreign cars')
... elif age >= 21 and car in ['Ford', 'Chevrolet']:
...     print('You buy American')
... else:
...     print('You are too young!')
... 
You buy American

When you use and, both expressions must evaluate to True for the code underneath them to execute. So the first conditional checks to see if the age is greater than or equal to 21 AND the car is in the list of Japanese cars. Since it isn’t both of those things, you drop down to the elif and check those conditions. This time both conditions are True, so it prints your car preference.

Let’s see what happens if you change the and to an or:

>>> age = 21
>>> car = 'Ford'
>>> if age >= 21 or car in ['Honda', 'Toyota']:
...     print('You buy foreign cars')
... elif age >= 21 or car in ['Ford', 'Chevrolet']:
...     print('You buy American')
... else:
...     print('You are too young!')
... 
You buy foreign cars

Wait a minute! You said your car was “Ford”, but this code is saying you buy foreign cars! What’s going on here?

Well when you use a logical or, that means that the code in that code block will execute if either of the statements are True.

Let’s break this down a bit. There are two expressions in if age >= 21 or car in ['Honda', 'Toyota']. The first one is age >= 21. That evaluates to True. As soon as Python sees the or and that the first statement is True, it evaluates the whole thing as True. Either your age is greater than or equal to 21 or your car is Ford. Either way, it’s true and that code gets executed.

Using not is a bit different. It doesn’t really fit with this example at all, so you’ll have to write something else.

Here is one way you could use not:

>>> my_list = [1, 2, 3, 4]
>>> 5 not in my_list
True

In this case, you are checking to see if an integer is not in a list.

Let’s use another authentication example to demonstrate how you might use not:

>>> ids = [1234, 5678]
>>> my_id = 1001
>>> if my_id not in ids:
...     print('You are not authorized!')
... 
You are not authorized!

Here you have a set of known ids. These ids could be numeric like they are here or they could be email addresses or something else. Regardless, you need to check if the given id, my_id is in your list of known ids. If it’s not, then you can let the user know that they are not authorized to continue.

You can also combine logical operators in a conditional statement. Here’s an example:

>>> hair = 'brown'
>>> age = 21
>>> if age >= 21 and (hair == 'brown' or hair == 'blue'):
...     print(f'You are {age} years old with {hair} hair')
... else:
...     print(f'You are too young at {age} years old')
... 
You are 21 years old with brown hair

This time around, you will run the code in the first half of the if statement if the age is greater than or equal to 21 and the hair color is brown or blue. To make this easier to read, you put parentheses around the the 2nd and 3rd expressions.

Special Operators

There are some special operators that you can use in conditional expressions. In fact, you already used one of them in the previous section.

Do you remember which one of these you just used?

  • isTrue when the operands are identical (i.e. have the same id)
  • is notTrue when the operands are not identical
  • inTrue when the value is in the sequence
  • not inTrue when the value is not in the sequence

You used the last one, not in to determine if an id was not in the authorized access list.

The first two are used for testing identity. You want to know if an item refers to the same object (or id) or not. The last two are for checking membership, which means you want to know if an item is in a sequence or not.

Let’s look at how identity works:

>>> x = 'hi'
>>> y = 'hi'
>>> x is y
True
>>> id(x)
140328219549744
>>> id(y)
140328219549744

When you assign the same string to two different variables, their identity is the same because Python points both x and y to the same ID or location in memory.

Let’s see if the same thing happens when you create lists:

>>> x = [1, 2, 3]
>>> y = [1, 2, 3]
>>> x is y
False
>>> id(x)
140328193994832
>>> id(y)
140328193887760
>>> x == y
True

Python lists work a bit differently. Each list gets its own id, so when you test for identity here, it returns False. Note that when you test equality at the end, the two lists do equal each other.

You can use in and not in to test if something is in a sequence. Sequences in Python refer to such things as lists, strings, tuples, etc.

Here’s one way you could use this knowledge:

>>> valid_chars = 'yn'
>>> char = 'x'
>>> if char in valid_chars:
...     print(f'{char} is a valid character')
... else:
...     print(f'{char} is not in {valid_chars}')
... 
x is not in yn

Here you check to see if the char is in the string of valid_chars. If it isn’t, it will print out what the valid letters are.

Try changing char to a valid character, such as a lowercase “y” or lowercase “n” and re-run the code.

Wrapping Up

Conditional statements are very useful in programming. You will be using them often to make decisions based on what the user has chosen to do. You will also use conditional statements based on responses from databases, websites and anything else that your program gets its input from.

It can take some craftsmanship to create a really good conditional statement, but you can do it if you put enough thought and effort into your code!

1 thought on “Python 101: Conditional Statements”

  1. Pingback: Python 101 - Exception Handling - The Mouse Vs. The Python

Comments are closed.