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:
{PYTHON}
if 15 > 5:
print("True")
print("The program continues here...")
The output:
Console application
True
The program continues here...
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 operator
(!
) 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 0
if (a == 0): # if the value is 0, we change its value to 1
a = 1
if (a == 1): # if the value is 1, we change its value to 0
a = 0
print(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 0
if (a == 0): # if the value is 0, we change its value to 1
a = 1
else: # if the value is 1, we change its value to 0
a = 0
print(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 >= 10 and 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 >= 10 and a <= 20) or (a >= 30 and 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:
{PYTHON}
print("Welcome to calculator!")
a = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))
print("Choose one of the following operations:")
print("1 - addition")
print("2 - subtraction")
print("3 - multiplication")
print("4 - division")
option = int(input(""))
if (option == 1):
result = a + b
elif (option == 2):
result = a - b
elif (option == 3):
result = a * b
elif (option == 4):
result = a / b
if option > 0 and option < 5:
print("result: %f" % (result))
else:
print("Invalid option")
print("Thank you for using our calculator.")
Console application
Welcome to our calculator
Enter the first number: 3.14
Enter the second number: 2.72
Choose one of the following operations:
1 - addition
2 - subtraction
3 - multiplication
4 - division
2
result: 0.420000
Thank you for using our calculator.
Notice the trick we used to validate the user's choice. The program should
still work the same even without all the else
s (but why keep on
asking if we already have a result?).
That is all for today. In the next lesson, Solved tasks for Python lesson 4-5, we'll take a look at arrays and loops, i.e. finish up with the absolute basics of the Python language. Look forward to it
In the following exercise, Solved tasks for Python lesson 4-5, we're gonna practice our knowledge from previous lessons.