Python/If Statement

< Python

Objective

  • 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.

Lesson

Indentations

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 else 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 your 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 curly brackets ({}) for code blocks and statements. The use of these brackets, or commonly called braces, in Python has been and continues to be asked. 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 would allow a 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 its evaluation. 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!")
...
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!")
...
True!
>>> if 1 == 2 and 2 == 2:
...     print("True")
...
>>> if 1 == 2 or 2 == 2:
...     print("True!")
...
True!
>>> if 1 == 2 or 2 == 3:
...     print("True!")
...
>>> if not False:
...     print("True!")
...
True!
>>> if not 1 == 2:
...     print("True!")
...
True!


Like the beginning of the lesson stated, you can nest statements within each other, 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 in just on 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 it will large code or long multi-line 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 thing 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 them 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!")
...
True!


Like the semicolon, you don't need to worry about indentation. 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 in. It works like the backslash, but it allows for extra characters at the end, including whitespaces.

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


Note: It is considered unpythonic to use parentheses, with backslashes begin 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 their of code block 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 one it, it's recommended that you indent ever four spaces.

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!

Assignments

  • 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 readable and maintainable at the same time.

Completion status: Ready for testing by learners and teachers. Please begin!

This article is issued from Wikiversity - version of the Wednesday, April 01, 2015. The text is available under the Creative Commons Attribution/Share Alike but additional terms may apply for the media files.