Introduction

How can a program make a decision? Can a program choose between two or more options. Actually, it can. This isn't some kind of advanced AI concept, it's just a matter of evaluating whether or not certain conditions have been met and choosing a response.

The way that a program can evaluate a condition comes down to true and false. If something is true, do this. If it isn't true do, that. The if statement is the structure for a program to pose these questions and evaluate whether or not they are true. if statements can check multiple conditions and provide multiple responses. They can be used to divert code down one path or another and control the overall flow of a program. They can also be used as a gating mechanism to determine whether certain blocks of code run. Have you ever gotten a message telling you that you needed to log in to continue? That was the result of if.

If

if has a very simple structure. The word, if, is followed by a set of parenthesis containing a statement that needs to be evaluated for truthfulness and a colon. The following line is indented and contains the action to be performed if the statement is true. There can be multiple actions following if as long as they are all indented.
if (5 ** 2 >= 25):
	print("It's true!")
	print("If is awesome!")
You can resume the normal flow of the program following if by returning to unindented lines of code.

You can, and should, use Boolean Operators in if as well.
if( (5 ** 2 >= 25) and (4 * 2 < 8) or (35 / 7 > 4) ):
	print("Booleans make If more powerful!")
Boolean Operators allow if to evaluate more and more complex conditions in a single line of code. Chances of having more than one factor impacting whether a block of code should run are pretty high. Using Boolean Operators is an elegant way to handle this without needing multiple if statements and many more lines of code.

When the if condition is false, the indented code below just doesn't run. Take a look at an example where that happens.
if (4 * 2 < 8):
	print("This won't run")

print("This is isn't part of if, so it will")

Else

What happens if you want to run a piece of code only if if isn't true. You could use not like the example below.
if (not (5 ** 2 >= 25)):
	print("Bizarro!")
That's weird and counter intuitive. It also creates problems with more complex situations. What if you want the program to do one thing if a statement is true and another if it's not? That's where else comes in. else is placed on the same indent level as if following the code that you want run if if is true. It is also followed by a colon and indented code that will run if if isn't true.
if (5 ** 2 > 25):
	print("Your math looks a bit off...")
else:
	print("That makes sense.")
else is the best way to run code if if is false. It can also be a good way to make sure that things are going along the way they should be.
if ( (5 ** 2 >= 25) and (35 / 7 > 4) and ( 4 * 2 >= 10) and (3 ** 2 < 10) ):
	print("Everything looks good.")
else:
	print("Your math is wrong somewhere.")

Elif

Python supports multiple independent conditions in the same if block. Say you want to test for one condition first, but if that one isn't true, there's another one that you want to test. Then, if neither is true, you want the program to do something else. There's no good way to do that using just if and else. elif is a mashup of the words if and else and is used to test other conditions following the original if before the block defaults to else.
if (5 ** 2 > 25):
	print("The first one is right.")
elif(5 ** 2 = 25):
	print("It was the second one.")
else:
	print("Something went wrong.")
That example is sort of nonsense because >= exists, but you can see the flow of logic from it.

You can have as many elif statements as you need.
if (5 ** 2 > 25):
	print("It is greater.")
elif (5 ** 2 < 25):
	print("It is less.")
elif(5 ** 2 = 25):
	print("It is equal.")
else:
	print("That makes no sense")
Again, that's nonsense, but it still illustrates the point. That last else could actually be left off because it's not really possible to ever get there. That is something else that you can do with elif. If you know that one of multiple conditions must be met, you can use if and elif to funnel your program down the right path.

Nesting If

You can ask a second question only if the first question was answered affirmatively. It works that way in real life, and it works that way in Python. if statements can be nested within other if statements. This can actually be done indefinitely, and it doesn't matter where they are nested. You could put a second if within the initial if. You could put it in one of the elif blocks. You can even put it in the else.
a = 10
b = 15
c = 20
d = 25

if (a > b):
	if (a + b >= d):
		d -= c
	elif (a + >= c):
		c -=b
	else:
		b -= a
elif (b > c):
	print(b - c) 
else:
	print(d)
As you can see, the flow diverts on the first condition down a nested if. The nested if follows the exact same pattern as any other if statement.

Conclusion

By using if you can divert the flow of your program and control the way that it runs in a logical manner. Using conditional logic, you can crate tests that your program will use to make decisions and adapt to circumstances and data values.

Table of Contents

  1. Python Introduction and Installation Guide
  2. Python Files and the Interpreter
  3. Experimenting With Numbers and Text In Python
  4. Python Variables
  5. Working With Number Variables In Python
  6. Python String Basics
  7. Advanced Python Strings
  8. Python Comments
  9. Python Lists
  10. Python List Methods
  11. Python Multidimensional Lists
  12. Python Tuples
  13. Python Boolean Operators
  14. Python If Statements
  15. Python While Loops
  16. Python For Loops
  17. Python Dictionaries
  18. Python Advanced Dictionaries
  19. Python Functions