Lesson 5 - Conditions (branching) in Python

In the previous lesson, More on the Python type system: Data types, we discussed Python data types in
details. We need to react somehow to different situations if we want to program
something. It may be, for example, a value entered by the user, according to
which we would like to change how the program runs. We metaphorically say that
the program branches, and for branching we use conditions. We will focus on
those in today's article. We're going create a program which calculates square
roots, and we're going to improve our calculator.

Conditions

In Python, conditions are similar to all of the C-like languages. We write
conditions using the if keyword, which is followed by a logical
expression and then by a colon (:). If the expression is true, the
following statement will be executed. If it's not true, the following statement
will be skipped, and the program will continue with the next statement. Let's
try it out:

If the condition is true, a command that writes text to the console will be
executed. In both cases, the program continues. Of course, a variable can also
be part of the expression:

{PYTHON}
a = int(input("Enter a number: "))
if (a > 5):
print("The number you entered is greater than 5!")
print("Thanks for the input!")

Let's look at the relational operators which can be used in expressions:

Meaning

Operator

Equal to

==

Greater than

>

Less than

<

Greater than or equal to

>=

Less than or equal to

<=

Not equal

!=

Negation

not

We use the == operator for equality to avoid confusing it with a
normal assignment to a variable (the = operator). If we want to
negate an expression, we write it in parentheses using the negation
mark (!) before the actual expression within the parentheses. If you want to
execute more than one command, you have to indent each line with a tab:

{PYTHON}
a = int(input("Enter a number and I'll calculate its square root: "))
if (a > 0):
print("The number you entered is greater than 0, so I can calculate it!")
root = a ** (1/2)
print("The square root of %d is %f " % (a, root))
print("Thanks for the input")

Console application
Enter a number and I'll calculate its square root: 144
You've entered a number greater than 0, I can calculate it!
The square root of 144 is 12.000000
Thanks for the input

The program retrieves a number from the user, and it calculates its square
root (if it is greater than 0). We have used the ** operator and
set the variable a to be computed with an exponent of 1/2, which is
the equivalent to getting its square root. At the end of this course, we'll
learn more about mathematical functions in Python. It would be nice if our
program warned us if we entered a negative number. With what we know up until
now, we'd be able to write something like this:

{PYTHON}
a = int(input("Enter a number and I'll get its square root: "))
if (a > 0):
print("The number you entered is greater than 0, so I can calculate it!")
root = a ** (1/2)
print("The square root of %d is %f" % (a, root))
if (a <= 0):
print("I can't calculate the square root of a negative number!")
print("Thanks for the input!")

We must keep the case where a == 0 in mind, and also when it is
less than 0. The code can be greatly simplified using the
else keyword which executes the following
statement or block of statements if the condition was not
true:

{PYTHON}
a = int(input("Enter a number and I'll get its square root: "))
if (a > 0):
print("The number you entered is greater than 0, so I can calculate it!")
root = a ** (1/2)
print("The square root of %d is %f" % (a, root))
else:
print("I can't calculate the square root of a negative number!")
print("Thanks for the input!")

The code is much clearer, and we don't have to make up a negating condition
which could be very difficult with complex conditions sometimes. In the case of
multiple commands, each line after the else keyword would also have to be
indented.

Else is also used when we need to set a variable from the
condition up so we can't evaluate it later again. The program remembers that the
condition didn't apply and then moves to the else branch. Let's look at an
example: Consider a number whose value will be either 0 or 1 and we'll be asked
to swap these values (if there is 0, we put a 1 there, and the other way
around). Naively, we could write the code like this:

{PYTHON}
a = 0# the variable is initialized with a value of 0if (a == 0): # if the value is 0, we change its value to 1
a = 1if (a == 1): # if the value is 1, we change its value to 0
a = 0print(a)

It doesn't work, does it? Let's take a closer look at the program. At the
very beginning, a contains a value of 0, the first condition is
undoubtedly fulfilled and it assigns a value of 1 to a. Well, suddenly,
the second condition becomes true. What should we do? If we swapped the
conditions, we'd run into the same problem. Now, how do we solve this? You
guessed it, using else!

{PYTHON}
a = 0# the variable is initialized with a value of 0if (a == 0): # if the value is 0, we change its value to 1
a = 1else: # if the value is 1, we change its value to 0
a = 0print(a)

Conditions can be composed using two basic logical operators:

Operator

syntax

Logical AND

and

Logical OR

or

Let's take a look at another example:

{PYTHON}
a = int(input("Enter a number between 10-20: "))
if a >= 10and a <= 20:
print("The condition has been met.")
else:
print("You did it wrong.")

Of course, operators can also be combined using parentheses:

{PYTHON}
a = int(input("Enter a number between 10-20 or 30-40: "))
if (a >= 10and a <= 20) or (a >= 30and a <= 40):
print("The condition has been met.")
else:
print("You did it wrong.")

Enhancing the calculator

Let's look back to our calculator from the first lesson, which had read two
numbers and calculated all 4 operations. Now, we'll have it single out an
operation. Since we'll need a sequence of else-if statements, we'll use the
shortened elif keyword:

The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.

The author learned IT at the Unicorn College - a prestigious college providing education on IT and economics.