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 implement a basic type of control flow using exception handling, although this 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 tutorial, 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!
Comparison Operators
Before you begin using conditionals, it will be helpful 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:
Now that you know what comparison operators are available to you in Python, you can start using them!
Here are some examples:
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 are 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:
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:
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.
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 will not run as you intended.
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. {/blurb}
If authenticated had been set to False, then nothing would have been printed out.
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:
What this code is doing is checking the value of authenticated: if it evaluates to True it will print “You are logged in”, otherwise 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 know how you can participate in elections depending on that factor:
In this example, you use if and elif. The keyword elif is short for “else if”. The code here checks the age against different hard-coded values. If the age is less than 18, then the citizen can follow the elections on the news.
If they are older than 18 but less than 35, they can vote in all elections. Next you check if the citizen’s age is greater than or equal to 35. Then they can run for any office themselves and participate in their democracy as a politician.
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 to only have a handful -- a long if/elif statement 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:
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 the first 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- OnlyTrueif both the operands are trueor-Trueif either of the operands are truenot-Trueif the operand is false
Let’s try using the logical operator and with the example from the last section to flatten your conditional statements:
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 18 AND the car is in the list of Japanese cars. Since it isn’t both of those things, you drop down to the first 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:
Wait a minute! You said your car was “Ford”, but this code is saying you buy Japanese cars! What’s going on here?
Well, when you use a logical or 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 >= 18 or car in [’Honda’, ‘Toyota’]. The first one is age >= 18. 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 18 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, but it does work with our previous authentication example:
By using not we switched the success and failure blocks -- this can be useful when the failure-handling code is short.
You can combine logical operators in a conditional statement. Here’s an example:
This time around, you will run the code in the first half of the if statement if the age is smaller than or equal to 14 and the color of the milk is white or green. The parentheses around the 2nd and 3rd expressions are very important because of precedence, which means how important a particular operator is. and is more important than or, so without the parentheses Python interprets the above code as if you had typed if (age <= 14 and color == ‘white’) or color == ‘green’:. Not what you had intended! To prove this to yourself, change color to ‘green’, age to 100, remove the parentheses from the if statement, and run that code again.
Special Operators
There are some special operators that you can use in conditional expressions.
is-Truewhen the operands are identical (i.e. have the same id)is not-Truewhen the operands are not identicalin-Truewhen the value is in a collection (list,tuple,set, etc.)not in-Truewhen the value is not in a collection
The first two are used for testing identity. You want to know whether or not two items refer to the same object; we could use the id() function and either == or !=, but using is and is not is much simpler.
The last two are for checking membership: whether or not an item is in a collection -- such as a value being in a list, or a key in a dictionary.
Let’s look at how identity works:
Wait, what? Didn’t you just assign the same list to both x and y? Not really, no. The first [1, 2, 3] creates a list which Python then assigns to x; the second [1, 2, 3] creates another list and Python assigns that one to y -- two creations means two objects. Even though they are equal objects, they are still different.
Let’s try again with strings:
Okay, looking good! One more time:
What just happened? Well, let’s think about this for a moment... a list is mutable, which means we can change it, but a str is immutable, which means we cannot change it. Because immutable objects cannot be changed, Python is free to reuse existing, equivalent objects instead of creating new ones. So be very careful to only use is when you actually mean exact same object -- using is for equality will sometimes accidently work, but will eventually fail and be a bug in your program.
You can use in and not in to test if something is in a collection. Collections in Python refer to such things as lists, strings, tuples, dictionaries, etc.
Here’s one way you could use this knowledge:
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.
Here is one way you could use not in:
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 in:
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.
Wrapping Up
Conditional statements are instrumental in programming. You will often use them to make decisions based on the user's chosen actions. 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 an excellent conditional statement, but you can do it if you put enough thought and effort into your code!


















