If Statements

The most basic element of control flow in Python

Purpose of Control Flow

Control flow is basically the decision-making that goes on in your program. If one thing is True, do this, if not, do that. This is a central concept to programming. When programming robots to make decisions on their own, we use this concept to let robots decide which path to take on their own, based on information gathered from encoders and other sensors. In addition, to decision-making, control flow involves looping through a section repeatedly until a condition is met.

Such concepts also come in handy with autonomous robots. But, on top of that, you can use such control flow concepts for basic tasks like controlling a lamp, or more advanced ones like matching english words to spoken words in new virtual assistant technology like Apple’s Siri or Microsoft’s Cortana.


First, we will work with "If" statements. Basically, if this is True, run this code. If not, don’t run it and skip to the next part of the code. The code should be formatted like this…

if condition:
	# processing and commands go here… 

Replace ‘condition’ with the condition we are checking for. For example, "does a equal b?"

Equality Operator

In order to ask whether a equals b, we can’t use the ‘=’ symbol. In Python, this symbol is used to assign values to a variable, so it can’t be used to check if a variable is equal to some value. For this, we use the ‘==’ operator. So, to check if a equals b, and then print a plus b…

a = 5
b = 5
if a==b:



And that's it!

Inequality Operators

Obviously, we don’t always want to check if something is just equal to something. We can also use the ‘not equals’ operator ‘!=’. And for mathematical comparisons, we can also use arithmetic comparisons, like ‘>’,’ <’,’>=’,and ‘ <=’. Here are some examples…

a = 5
b = 6
if a != b:
    print(str(a) + " is not equal to " + str(b))
if a >= b:
    print(str(a) + " is greater than or equal to " + str(b))
if a < b:
    print(str(a) + " is less than " + str(b))    


5 is not equal to 6
5 is less than 6

Notice how the second "if" statement’s code isn’t run because the condition is not True.