IF Statement - Python (2016)

Python (2016)

CHAPTER 11: IF Statement

Earlier, we had mentioned in passing about the special place indentation has in the Python language. Unlike other languages such as Java and C++, Python uses the indent to determine a block of code. This pseudocode demonstrates this:

This is a line of code.

This is another line of code

This code, on the other hand, is part of a code block.

This is also a part of a code block.

Unfortunately, this code is no longer part of a code block.

But this code is the start of a new code block.

As was seen from the pseudocode, there are multiple areas that form blocks of codes. You can even nest a block of code within another block, as long as it indents. There is technically no limit in indentation, but the programmer has to mind the indentation’s consistency, or else, an error will be generated. Consider this next batch of pseudocode:

This is a line of code.

This line is part of a code block, which is pretty far away.

While not encouraged, this indentation is legal in Python.

For consistency, indenting in multiples of four are preferred.

This line is no longer a part of a code block, since it does not follow any indentation style.

This would get you an error.

While the programmer is allowed to use both white spaces and tabs, it is preferable to use white spaces. Be reminded that you will not be able to use both tabs and whitespaces at the same time, or an error may appear.

One should know that since the Python interpreter is used in demonstrating the example code, an ellipsis (...) is virtually same as three greater-than signs (>>>). The only difference is that an ellipsis means you are in a code block. The following demonstrates this:

>>>if True:

... Print(“Hi there!”)

...

Hi there!

Some programmers may be more comfortable in using curly braces ({}) to determine code blocks and statements, especially those who are just starting Python after learning a different languages. These brackets (also called braces) are some of the most debated-on signs in Python. As of this writing, the core Python developers are continuing to reject the use of braces due to the Python Philosophy. In fact, if you try to opening up the Python interpreter and typing “from_future_import braces”, you will get a little easter egg that will sum up the collective attitude of Python’s core developers (towards braces, at least)—SyntaxError not a chance.

Now that this has been gotten out of the way, we can get into the nitty-gritty of the lesson.

The If Statement and Code Flow

In a majority of programming languages, there are special ways of controlling the code “flow”. Such a control allows specific parts of the code to execute only when the conditions are right. Among the different codes used towards this end, the most commonly used is the if statement. This is meant to first compute whether a statement is true or false—if the statement is true, the code is executed; if it is false, the code is not.

Remember that the True and False expressions are Booleans in the Python language. This means that the if statement (as well as other conditional statements) will be using Boolean math in order to compute the evaluation. One should also note the proper way a conditional statement is written—a colon (:) at the end is necessary at the end of “control flow” statements.

Here is an example:

>>>if 1==1:

... Print(“This is gonna print!)

...

This is gonna print!

>>>if 1==2:

... Print(“This won’t ever print.”)

...

You can also use what was previously discussed about Booleans (and, or, not) in order to mix different conditions together.

>>>if 1==1 and 3 ==3:

... Print(“True”)

...

True

>>>if 1==2 or 3==3:

... Print(“True”)

...

>>>if 1==2 or 3==4

... Print(“True”)

...

>>>if not False:

... Print(“True”)

...

True

As was previously mentioned, you can nest statements within statements so long as the respective indentations are followed.

>>>if 50==50:

... Print(“50 equals 50”)

... If True:

... Print(“True is True”)

...

50 equals 50

True is True

While statements can always be nested within each other, it can quickly become hard to manage. It would have been more Pythonic if the statements are kept flat. This would mean that instead of nesting different if statements together, it would be better to use a single if statement with different and operators.

>>>if 2==2:

... If 4==4:

... If 6==6:

... Print(“2,4, and 6 are equal)

...

2,4, and 6 are equal

>>>if 2==2 and 4==4 and 6==6:

... Print(2,4, and 6 are equal)

...

2,4, and 6 are equal

If you found the line being printed to be queer, remember the basic rules in school logic—operators do not care about the final line being true or not in the real-world, so long as the prerequisite conditions are met.

Backslashes, Semi-colons, and Parentheses

Most likely, you will want to keep several different lines of code in just a single line. This can be done using the semi-colon (;). This acts like a new line, except that the programmer will not see it in this way. Take, for example, the following lines of code:

>>>if 1 !=3:

... a=1

... b=2

... c=3

...

The same code may be condensed into a single line, just like shown here:

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

...

The good thing about semi-colons is that they do not need to indent. This takes away the need to carefully count the number of times you have indented. While this is a great thing, remember that semi-colons should not be used excessively. This is just to make sure that you are not writing a large chunk of code all just on one line as that would be more confusing to manage. Take a look at this bad example:

>>if 1 !=3 a=1;b=2;c=3;d=4;e=5;f=6;g=7;h=8;i=9;j=10;

...

Now, let’s tackle another dilemma. Let’s say that you would need to compare six different numbers using an if statement. This statement would become quite long, and nesting them in different statements would make things worse. This can be solved by using a backslash (\). This allows you to break up a long line of code into different parts.

>>>if 2==2 and 4==4 and 6==6 and 8==8 and \

... 10==10 and 12==12 and 14==14

... Print(“True”)

...

True

Just like in the case of the semi-colon, the programmer will not need to worry about indentations when dealing with the backslash. This will allow you to keep the code in level with the if statement. However, remember that any character appearing directly after the backslash will cause an error to appear. This extends all the way out to excess whitespaces that may have been mistakenly typed. Remember to be extra-careful when dealing with backslashes.

Then again, there is an even more workable solution—using parentheses to include all of the pertinent code. This works just like the backslash, however it allows for extra characters (including whitespaces) appearing at the end.

>>>if (2==2 and 4==4 and 6==6 and 8==8 and

... 10==10 and 12==12)

... Print(“True”)

...

True

Note that for some Pythoneers, it is considered “unpythonic” to use parentheses instead of backslashes. This is, however, not 100% accurate all the time.

The Else Statement

There would be a lot of times when you wish to execute a different line of code in case the if statement is not true. This would call in the use of the else statement. The statement accompanying this will be executed when the preceding statement is false. To work, it needs to be on the same level of indentation as the if statement. Here is an example:

>>>if 3==3:

... Print(“3 equals 3”

... Else:

... Print(“3 is not equal to 3”)

...

3 equals 3

>>>if 3=33:

... Print(“3 equals 33”)

...else:

... Print(“3 is not equal to 33”)

...

3 is not equal to 33

While both if and else have to be aligned to each other to work, the indentations of their code blocks can be different as demonstrated by the following example:

>>>if 2==2:

... Print(“2 equals 2”)

...else:

... Print(“2 is not equal to 2”)

...

2 equals 2

While there is no requirement for it, it is again recommended that you indent in multiples of four.

The Elif Statement

As you might have noticed by now, the Python language often provides shortcuts (or at least some kind of reprieve) in case one has to do tedious tasks. For example, the programmer wants to have four if statements together—but you only need one of these to execute. The programmer can always try to write all those four statements, but then again it would be a lot easier to just write one big chunk directly using the elif statement. The term elif stands for “else if”, that acts like both the else and if statements. This would mean that if the first if is not true, the elif will kick in to see if it is true. This can be avery handy feature later on. Check out the following blocks of code:

>>>if fraction == 1:

... Print(“The fraction is a whole”)

...Elif fraction == 3/4:

... Print(“The fraction is 3/4”)

...elif fraction == 2/4:

... Print (:The fraction is a half”)

...elif fraction == == 1/4:

... Print(“The fraction is 1/4”)

...else:

... Print(“The fraction is none of the above”)

...