Python/If Statement


Books-aj.svg aj ashton 01f.png
  • Learn about Python's indentation syntax.
  • Learn about the conditional statement if.
  • Learn about the use of semi-colons and backslashes in Python.
  • Learn about two dependent statements, elif and else.



Unlike many other computer languages, like C++ and java, Python uses indentation to determine blocks of code. The following pseudocode below will help demonstrate.

This is some code.
This is some more code.
 This code is part of a code block.
 And so is this!
 And this!!!
This code isn't part of the code block. =(
 But this code is part of a new code block!
 And this code is, as well!

As we can see, there can be multiple blocks of code. You can also contain blocks of code within another block of code, so long as it indents. There isn't a limit on the indent, but it must be kept constant or you'll get an error.

This is some code.
           This is a block of code indented very far away.
           This is completely legal in Python, although not encouraged.
           The preferred indentation is in multiples of four.
    This isn't a block of code; it follows no indentation style.
   This would cause an error!

Although you're allowed to use white spaces and tabs, it's preferred that you use white spaces. Also, you cannot mix both white spaces and tabs together or you'll get an error.

You should know that since we'll be using the Python Interpreter to compute the example code, ... is exactly the same as >>>, except that it means you're in a code block. The below code will demonstrate.

>>> if True:
...     print("Hello, world!")
Hello, world!

Now that we got this out of the way, we can continue on with the main part of the lesson.

Note: Some of you may feel more comfortable using braces ({}) for code blocks and statements. The use or non-use of these braces in Python has been and continues to be a topic of vigorous debate. In spite of this, the core developers continue to reject any motion for braces based on Python's philosophy. In fact, if you open up Python and type from __future__ import braces you'll get a humorous error that can sum up Python's attitude towards braces...SyntaxError: not a chance.

The If Statement

In most, if not all programming languages, there are special ways to control the flow of code. Such control allows certain parts of code to execute if the conditions are right. This flow control is done by using statements and code blocks. The most common and widely used statement is the if statement. It will compute if a statement is true or false. If it's true, it will execute the code. If it's false, it won't execute the code.

Remember that True and False are Booleans in Python. This means that if and other conditional statements will use Boolean math to compute their Boolean state. You should also note the need for a colon (:) at the end of the if statement. This is needed at the end of a control flow statement.

>>> if 1 == 1:
...     print("This will print!")
This will print!
>>> if 1 == 2:
...     print("This will never print. =/")
>>> if True:
...     print("True!")
>>> if False:
...     print("False!")

You can also mix several conditions together by using the previously taught Boolean operators; not, and, or.

>>> if 1 == 1 and 2 == 2:
...     print("True!")
>>> if 1 == 2 and 2 == 2:
...     print("True")
>>> if 1 == 2 or 2 == 2:
...     print("True!")
>>> if 1 == 2 or 2 == 3:
...     print("True!")
>>> if not False:
...     print("True!")
>>> if not 1 == 2:
...     print("True!")

As stated at the beginning of the lesson, you can nest statements within a code block to begin a new code block, so long as they follow their respective indentations.

>>> if 30 == 30:
...     print("30 equals 30!")
...     if True:
...         print("True is True!")
30 equals 30!
True is True!

Although you can nest statements within each other, it can become hard to manage. It would be more Pythonic to keep statements flat. This means instead of nesting four if statements together to do something, it would be better to use one if statement with several and operators.

>>> if 1 == 1:
...     if 2 == 2:
...         if 3 == 3:
...             print("1, 2, and 3 are equal to their selves!")
1, 2, and 3 are equal to their selves!
>>> if 1 == 1 and 2 == 2 and 3 == 3:
...     print("1, 2, and 3 are equal to their selves!")
1, 2, and 3 are equal to their selves!

Semi-colons, Backslashes, and Parentheses

You're probably going to want to keep several lines of code on just one line. This can be accomplished by using the semicolon (;). The semicolon acts like a newline, though the programmer won't see it like that. Take the following code as an example.

>>> if 1 != 2:
...  a = 1
...  b = 2
...  c = 3

This same code can be condensed into one line, like the example below.

>>> if 1 != 2: a = 1; b = 2; c = 3

The great thing about using semicolons is the need not to indent. Although their use seems great, semicolons should be used sparingly. As such, you shouldn't use them with large or long multi-line blocks of code. This can make it difficult and confusing to manage. Take a look at two bad examples.

>>> if 1 != 2: a = 1; b = 2; c = 3; d = 4; e = 5; f = 6; g = 7; h = 8; i = 9;
>>> if 1 == 1: spam = 2 * 2; eggs = spam / 2; bacon = (spam + eggs) * 4;

Now think about another dilemma. Imagine that you need to compare six numbers in an if statement. Such an if statement could become long and you don't want to make it worse by nesting the separate parts in six separate if statements. A backslash (\) can help solve this problem. A backslash allows you to break up one long piece of code into several parts.

>>> if 1 == 1 and 2 == 2 and 3 == 3 and \
...    4 == 4 and 5 == 5 and 6 == 6:
...     print("True!")

Like the semicolon, you don't need to worry about indentation following the '\\\n'. This allows you to keep code level with the first part of your if statement. Watch out though, since any character after the backslash will cause an error. This even means excess whitespaces will cause an error. You'll need to be extra careful when working with backslashes.

A more workable solution is to use parentheses () to enclose all of the code. Use of parentheses works like the backslash, but it allows for extra characters at the end of an incomplete logical line, including whitespaces.

>>> if (1 == 1 and 2 == 2 and 3 == 3 and
...     4 == 4 and 5 == 5 and 6 == 6):
...     print("True!")

Note: It is considered unpythonic to use parentheses, with backslashes being preferred. Although this isn't the case 100% of the time, you should use them at your own discretion.

The Else Statement

There will be many times when you want to execute code in the event that the if statement isn't true. This would require the use of the else statement. This statement will execute when the if statement is false. It needs to be on the same indentation level as the if statement.

>>> if 2 == 2:
...     print("2 equals 2!")
... else:
...     print("2 doesn't equal 2!")
2 equals 2!
>>> if 2 == 3:
...     print("2 equals 3!")
... else:
...     print("2 doesn't equal 3!")
2 doesn't equal 3!

Although the else and if need to be aligned with each other, the indentation of their code blocks can be different as the example below demonstrates.

>>> if 3 == 3:
...     print("3 equals 3!")
... else:
...            print("3 doesn't equal 3!")
3 equals 3!

Although there isn't a requirement for it, it's recommended that you indent every four spaces.

The else statement can be used to make code more readable. If you want the code to act when a condition is not true, you can negate the condition:

if not (a == 1 and b == 2 and c == 3 and 
    d == 4 and e == 5 and f == 6):
     print("Processing error!")

or you can leave the condition as is and act on the else statement:

if (a == 1 and b == 2 and c == 3 and 
    d == 4 and e == 5 and f == 6) :
    pass # situation normal
else :
     print("Processing error!")

The Elif Statement

Like a similiar problem before, you might need to do something that might seem tedious. Say you wanted four if statements together, but you only wanted one to execute. You could try to write those for statements, but it would be easier writing one big one using the elif statement. elif stands for "else if", which acts like an else and if. This means that if the initial if isn't true, it will go to the elif and see if it's true. This can come in handy later on.

>>> if fraction == 1:
...     print("The fraction is one whole!")
... elif fraction == 3/4:
...     print("The fraction is three fourths!")
... elif fraction == 2/4:
...     print("The fraction is one half!")
... elif fraction == 1/4:
...     print("The fraction is one fourth!")
... else:
...     print("I have no idea what the fraction is!")
The fraction is one fourth!

The elif statement is one of the ways by which Python implements a 'case' or 'switch' statement. The following simple example illustrates the equivalent of a 'case' statement:

status = -2

if status in [-3,-1,0,2,4,7] :
    print ('status', status, 'recognized')
else :
    print ('status', status, 'not recognized')

status -2 not recognized


Crystal Clear app kedit.svg
  • Play around with the Python Interpreter. Mix and match different if statements to get a general feel on how they work.
  • PEP 8 is an official document adopted by the Python Software Foundation to maintain readability within parts of Python. Skim through the document and get a general understanding on how Python code can be readable and maintainable at the same time.

Sweden road sign A10.svg Completion status: Ready for testing by learners and teachers. Please begin!


1. Python's documentation:

"4.1. if Statements," "4.8. Intermezzo: Coding Style," "6.10. Comparisons," "8. Compound statements," "8.1. The if statement," "Why does Python use indentation for grouping of statements?" "Why isn't there a switch or case statement in Python?" "Why are colons required for the if/while/def/class statements?"

2. Python's methods:

3. Python's built-in functions:

  This article uses material from the Wikipedia page available here. It is released under the Creative Commons Attribution-Share-Alike License 3.0.


Manage research, learning and skills at IT1me. Create an account using LinkedIn to manage and organize your IT knowledge. IT1me works like a shopping cart for information -- helping you to save, discuss and share.

  Contact Us  |  About |  IT Training & References |  IT Careers |  IT Hardware |  IT Software |  IT Books