Conditions and Branching in Python Programming

A computer program is a set of sequential instructions we want our computers to perform. To make these programs useful and correlate with the human world, we need the help of conditions and branching. Here a specific set of instructions get executed when they meet specified conditions. For example, in the real world, we dance when there is music. So the presence of music is a condition; when this is true, people will dance. 

Similarly, for our computer programs, we sometimes need to execute specific instructions only when some conditions will be true. If not, then we will perform a different set of instructions. This is known as branching. In this article, we will discuss these two concepts in Python, which makes our Machine Learning and Data Science programs worthwhile. 

Key takeaways from the blog

After going through this blog, we will be able to understand the following things:

  1. What are the various comparison operations in Python?
  2. What are the conditions in python?
  3. What is branching in python?
  4. What are logical operations?
  5. How do we use logical operations to combine the two conditions?

Let’s start our journey of covering the basics about the condition and branching with understanding the comparison operations.

Comparison Operations in Python

We compare the values or operands in comparison operation and produce a boolean data type in Python. It’s similar to what all other programming languages offer. 

Equality

We use a double equal operator to compare the equality of an operand or a value. For example:

# Assigning operand "alpha"  a value of 7
>>> alpha = 7

# Now we want to check whether the value of alpha is 6 or not
>>> alpha == 6
False

# As we can see that it produces a boolean result stating 
# that the value of alpha is not equal to 6
>>> alpha == 7
True

This equality comparison is not limited to integers only. We can also compare strings, floats, lists, tuples, dictionaries, sets, or other data types. For example:

>>> 'EnjoyAlgorithms' == 'Enjoyalgorithms'
False 
# because left side we have "A" in upper caps and in right side, 
# it is in lower caps

>>> a = [1,2,4,3]
>>> b = [1,3,4,2]
>>> a == b
False

>>> c = [1,2,4,3]
>>> a == c
True

>>> a = {1,2,3,4}
>>> b = {3,4,2,1}
>>> a == b
True

Inequality

We not only compare equality but inequalities as well. Let’s say we want to check if an operand or a value is greater than or less than a given value. For example, in the image below, we want to compare the values in a list. Please notice the four different operators for a given operand, 

  • Greater than (>): It does not include the current value of the operand.
  • Greater than or equal to (>=): It includes the current value of the operand.
  • Lesser than (<): It does not include the current value of the operand.
  • Lesser than or equal to (<=): It includes the current value of the operand.

Conditional inequalities

So if we are checking whether the value of the operand is greater than seven and the value of the operand is equal to 5, then the statement will generate a False boolean. For example:

>>> a = 7

>>> a > 7
False

>>> a >=7
True

To just check whether two numbers are not equal, we can place one exclamation (!) operator ahead of an equal operator like (!=).

>>> 7 != 11
True

>>> a = 7
>>> a != 5
True

>>> a != 7
False

>>> "Alpha" != "alpha"
True

Now we know the methods to compare, we can form various conditions based on these boolean values. So let’s understand it in more detail.

Conditions in python programming

As we know, our programs are a set of sequential instructions that we want our computers to operate. Among those instructions, we want to set some conditions, like if that condition is fulfilled, then only execute specific instructions. These conditions are statements based on comparison operations and act as a gate for some instructions. 

Likewise all other programming languages, in Python, we use “if” followed by the statement to check whether it is true. For example, let’s say we have a program with seven sequential instructions, meaning our python code will execute 1st, 2nd, and so on. On the 4th instruction, we have specified a condition, so our program will execute the 4th instruction only when that statement is true. If not, it will bypass 4th instruction and jump to 5th.

Conditioned vs Unconditioned Execution of Program

Let’s see the same with a code snippet. Suppose we are writing a program that checks the age of the traveler and provides them information that they are eligible to take window seats. Otherwise, it gives a general statement like “enjoy your journey”. Once the condition of age (above 18) is fulfilled, it will provide both the information. Otherwise, it will skip the information about the window seat eligibility. If we see the code below, we define the condition using “if” followed by the condition. The condition can be enclosed in small brackets, but it’s not compulsory. And in the last, we place a colon (:) to say that the condition statement is finished. 

age = 15

if (age > 18):
    print("You are eligible to take window seat")
print("Enjoy your journey")
## Output
# Enjoy your journey

age = 19
if (age > 18):
     print("You are eligible to take window seat")
print("Enjoy your journey")

## Output
# You are eligible to take window seat
# Enjoy your journey

Now that we know about the conditions, let’s understand the concept of branching in Python.

Branching in Python programming

Branching in Python allows us to run different statements based on different conditions. We define multiple conditions using various methods,

  1. “if-else” statements
  2. Multiple “if” statements
  3. “if-elif” statements

If-else Statements

We can treat this type of conditioning as two complementary statements, meaning if one is true, the other will be false and vice versa. Taking the same example, we collect age, and based on that, we provide information on whether a passenger is eligible for a window seat or not.

age = 19

if (age > 18):
     print("You are eligible to take a window seat")
else:
     print("You are not eligible to take a window seat")
print("Enjoy your journey")

## Output
# You are eligible to take a window seat
# Enjoy your journey

Here age will be either greater than 18 or <=18, so the conditions are complementary, and we can use the if-else statement here. If the age exceeds 18, the program provides information that “You are eligible to take a window seat”. Otherwise, if the age is less than or equal to 18, the program states, “You are not eligible to take a window seat”. And in the last, we also have a general statement that is present without any condition. So our program will execute that and print “Enjoy your journey”.

Multiple “if” Statements

Here we treat all the conditions independent of each other. If we take the same example, we could have covered the exact execution sequence with multiple “if” statements. Let’s see, 

age = 19

if (age > 18):
     print("You are eligible to take a window seat")
if (age <= 18):
     print("You are not eligible to take a window seat")

print("Enjoy your journey")

We could also place other conditions like, 

age = 19

if (age > 18):
     print("You are eligible to take a window seat")
if (age <= 18):
     print("You are not eligible to take a window seat")
if (age < 2):
     print("No seat allowed")
     
print("Enjoy your journey")

“if-elif” statements

An elif statement is a short form of “else if” which allows us to check additional conditions if the proceeding condition is false. If the proceeding condition is true, they will skip all the elif conditions. We can concatenate multiple additional conditions using multiple elif statements. Let’s see the code example snippet:

age = 15

if (age > 18):
     print("You are eligible to take a window seat")
elif (age < 2):
     print("No seat allowed")
else:
     print("You are not eligible to take a window seat")


## Output
#You are not eligible to take a window seat

Please note that the elif condition will be executed only when the proceeding condition is false. If you see the example below, although the condition of age≤18 is true, our program did not execute it.

age = 1

if (age > 18):
     print("You are eligible to take a window seat")
elif (age < 2):
     print("No seat allowed")
elif (age <=18):
     print("You are not eligible to take a window seat")

## Output
No seat allowed

Now that we know all about branching, let’s learn some logical operations that will be used frequently in Python programming to combine multiple conditions into one.

Logical Operations in Python

In practical programs, we need to check multiple conditions or may need to combine multiple conditions. For that, we use logical operations; likewise, we do for boolean data types. If you are familiar with logical gate operations, like

AND and OR Gate Table

Here, inputs are different statements represented as A and B. If both statements are true for AND gate, then only our program executes the conditioned line. And for the OR gate, if both statements are false, then only our program will not execute the conditioned statement. These two logical operations are the most frequently used operations to combine statements. Let’s see how we can place it in codes. The code below combines two statements using AND operation, (age is greater than 18) and (greater than or equal to 2). As both these statements are true if the age is 19. Hence “first if” condition passed, and our program printed, “You are eligible for a window seat”. But the “second if” statement did not pass as the second statement is false (age<2). 

age = 19

## First "if"
if (age>18 and age >=2):
     print("You are eligible for a window seat")
     
## Second "if"
if (age>18 and age < 2):
     print("You are not eligible for a seat")


## Output
# You are eligible for a window seat

Similarly, for the conjunction of statements using OR gate,

age = 19

## First "if"
if (age>18 or age >=2):
     print("You are eligible for a window seat")

## Second "if"
if (age<18 or age>2):
     print("You are not eligible for a seat")

## Output
# You are eligible for a window seat
# You are not eligible for a seat

The “second if” statement was executed as one of the statements is true (age>2).

We can also form a negation of statement using a NOT gate. Negation reverts the boolean value (True → False and False → True). In code,

age = 19

if not age < 18:
   print("Age is just a number")

# Output
# Age is just a number

As the statement (age < 18) was false, the negation made it true; hence, our program executed the conditioned instruction.

Conclusion

In this article, we discussed conditions and branching concepts which are very important for learning the basics of Python. Without these concepts, we might not have seen any machine learning and data science code or Github repository. That justifies the importance of this basic theory. In our subsequent blogs, we will discuss Functions and Loops in Python. Till then, Stay Tuned and Enjoy Learning!

Next Blog: Introduction to loop

Previous Blog: Sets and Dictionaries in Python

Share feedback with us

More blogs to explore

Our weekly newsletter

Subscribe to get weekly content on data structure and algorithms, machine learning, system design and oops.

© 2022 Code Algorithms Pvt. Ltd.

All rights reserved.