Conditions and Branching in Python Programming

A computer program is a series of instructions that a computer follows to perform a specific task. To make these programs useful in the real world, we use conditions and branching. Conditions are specific criteria that must be met for a set of instructions to be executed. For example, in the real world, people dance when there is music. The presence of music is a condition and when it is true, people will dance. Similarly, in python programming, we use conditions to determine which set of instructions to execute.

Branching is the process of using conditions to determine which set of instructions to execute. If a certain condition is met, the python program will execute one set of instructions, and if the condition is not met, it will execute a different set of instructions. This allows the program to make decisions and adapt to different scenarios.

Key takeaways from the blog

After reading this blog, you will understand the following topics:

  1. The different comparison operations in Python
  2. The concept of conditions in Python
  3. How does branching work in Python?
  4. The use of logical operations
  5. How to combine two conditions using logical operations?

Let's begin our exploration of the basics of conditions and branching by first understanding comparison operations in Python.

Comparison Operations in Python

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.

What are conditional inequalities in python?

So if we are checking whether the value of the operand is greater than 7 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

Conditions in python programming

As we know, computer programs are a series of instructions that we want our computers to execute. Among these instructions, we often use conditions to determine which set of instructions to execute. These conditions are statements based on comparison operations and act as a gate for certain instructions.

Similarly to other programming languages, in Python, we use the keyword "if" followed by a statement to check if it is true. For example, let's say we have a program with seven sequential instructions. Our Python code will execute the first, second, and so on. On the fourth instruction, we have specified a condition. So, the program will only execute the fourth instruction if the statement is true. If not, it will bypass the fourth instruction and move on to the fifth.

True and False conditioning operations in Python

Let's take a look at an example of this concept using a code snippet. Suppose we are writing a program that checks the age of a traveler and provides information about whether they are eligible to take a window seat. If the traveler is not eligible, the program will give a general statement such as "enjoy your journey." Once the condition of age (being above 18) is met, the program will provide information about both the age eligibility and window seat eligibility. If not, it will skip the information about the window seat eligibility.

In the code below, we define the condition using the keyword "if" followed by the condition. The condition can be enclosed in parentheses, but it is not mandatory. At the end, we place a colon (:) to indicate 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

Branching in Python programming

Branching in Python enables us to execute different statements based on different conditions. We can define multiple conditions using different methods, such as:

  1. "if-else" statements, where a specific block of code is executed if a condition is met and another block of code is executed if the condition is not met.
  2. Multiple "if" statements, where multiple conditions are checked, and the corresponding block of code is executed for the first true condition.
  3. "if-elif" statements, where multiple conditions are checked in sequence, and the first true condition's corresponding block of code is executed.

If-else Statements

We can think of this type of conditioning as two opposite statements. For example, we collect the age of a passenger and based on that, we provide information about whether they are eligible for a window seat or not. If one statement is true, the other will be false, and vice versa.

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 in Python

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.

Enjoy learning, Enjoy programming!

Share Your Insights

☆ 16-week live DSA course
☆ 16-week live ML course
☆ 10-week live DSA course

More from EnjoyAlgorithms

Self-paced Courses and Blogs

Coding Interview

Machine Learning

System Design

Our Newsletter

Subscribe to get well designed content on data structure and algorithms, machine learning, system design, object orientd programming and math.