The Essentials of Branching in Python

Introduction to Branching

Website Developer
9 min readFeb 12, 2023

Branching is what allows the computer to make decisions and act intelligently. In programming, branching is when a program is split into two parts. The correct path is chosen based on a set condition. There are two types of branching: conditional and unconditional. Conditional branching statements rely on a condition to be met before making the code jump, and unconditional branching statements execute without a condition check. Generally, the main conditional branching statements revolve around using if, else-if, and else to specify required conditions. This tutorial will focus mainly on conditional branching statements.

Another way to describe branching is as any time a decision must be made. It is a common process in programming to execute different statements when certain conditions are met, and conditionals allow this to be done. Conditionals will only execute code if the condition stated by the programmer is true or false. The syntax “if”, “elif”, and “else” are used to denote a condition set by the programmer. These can be used in various combinations to create ladders and can even be placed inside each other to set more specific conditions.

https://www.exforsys.com/tutorials/c-language/decision-making-and-branching-in-c.html

Understanding the logic behind branching statements can be challenging at first, but knowing if a programmer desires to write productive and efficient code is a dire concept. Python is a language created for readability, which makes interpreting and using branching statements relatively easy. Each of the three branching statements can work together in any order, with the caveat that an “if” block must always be present first in a branching ladder.

The “if” Statement

First, let’s look at the most basic Statement, the “if” Statement. In programming, the “if” Statement has practically the same meaning as the English word “if”. An “if” Statement introduces a condition that may or may not be met, just like its use in English.

If I go to the store, I will buy coconut flakes.

In this sentence, the word “if” introduces the condition of going to the store. The second half of the sentence states what will happen if the condition is met: buying coconut flakes. In programming, the “if” Statement is used the same way and will generally have the following structure:

if condition == true:
Block of code

It is important to note that two equality symbols are used for logical equality.

Here is what some simple code may look like using an “if” Statement. For reference, the written code asks the user to enter a number; if that number is negative, it will print a statement.

Code:

num = int(input())
if num < 0:
print('The number is negative')
Output with input as "-6":
The number is negative

The program will output nothing in this code if a positive number is an input. Remember that computers are literal machines, doing only what you tell them to do. If the number is positive, there is no condition telling what the computer should do with that number. This new condition can be set with an “else” statement. This is the second type of branching statement and can only be used if an “if’ statement was present beforehand.

It is also important to mention that spacing and colons are crucial when coding in python. A colon is to be always used after a branching statement is used, and proper spacing must always be used before the condition (pressing the “tab” key once). If a colon is not used or spacing isn’t used where required, your code will output an error message.

The “else” Statement

Next, consider another branching statement, the “else” Statement. The “else” Statement tells what the computer is to do if the condition is not met. The computer will read code in order from top to bottom (unless told otherwise), and when it comes to a branch, it will evaluate whether the condition for the first “if” Statement is met. An “else” statement also has a similar meaning and use to the English word, hinting at its purpose. The following structure illustrates how it is to be used.

if condition == true:
Block of Code
else:
Block of Code

When writing simple branches, the “else” Statement can be thought of as another “if” Statement that evaluates if the condition from before is false. However, this becomes inaccurate when combining this information with “elif” statements. With this structure in mind, the computer will only evaluate the “else” portion only if all other conditionals evaluate as “false”.

Now that we know what an “else” Statement is and how to use it, we can optimize our code from before slightly to tell the computer what to do if the number input is positive:

Code:

num = int(input())
if num < 0:
print('The number is negative')
else:
print('The number is positive')
Output with input as "-6":
The number is negative
Output with input as "5":
The number is positive

The “elif” Statement

Finally, the third branching statement, “elif,” can be discussed. The first two branching statements may seem sufficient. However, just an “if” and “else” is not enough when one desires to set multiple conditions. This is where the “elif” statement can be used. The “elif” statement can theoretically be used an infinite number of times to set however many conditions are desired.

The unabbreviated name of “elif” is “else-if”, which may hint at its use. But it is different from an “else” statement because it can have a set condition. The computer evaluates an “elif” statement if and only if the original “if” condition is false.

When “elif” is used, its condition is checked only if the first “if” Statement evaluates as “false”.

if condition == true:
(Code evaluates as false)
elif second condition == true:
Block of code executes

Since the first condition was evaluated as false, the code began executing the second if condition, which was true. This would cause the code under the elif statement to execute.

It is important to note that “if” and “elif” have different meanings in a program and are used for specific situations. An “if” Statement cannot be used interchangeably with an “elif” statement, and vice versa. Using “elif” statements is often quicker than simply stacking many “if” statements.

Here is a graphic to help explain the connection between the three branching statements:

https://www.codecademy.com/forum_questions/51684a3d4ce76309b4001b9c

Combining “if”, “else”, and “elif” Statements in a Single Branch

Consider watching the following YouTube video for any clarifications on branching:

Now that all three main branching statements have been covered, it is appropriate to mention how they can all be combined into a single branch — using all three instead of repeated “if” statements is an excellent habit because using the trio is faster and more efficient to use in a program. This is because when “elif” and “else” are combined with an “if”, once the computer identifies the branch that satisfies the condition, it will automatically be taken and void the other statements.

Any combination of these statements can be made, but it is usually most efficient to use all three statements in a single branch. Below is the general flow and structure of an average branch in a program:

if condition == true:
Block of Code
elif second condition == true:
Block of Code
elif third condition == true:
Block of Code
else:
Block of Code

Notice that after a single “if” Statement is used, “elif” statements begin to be used following it.

Using this information, it is possible to continue to optimize the code for identifying the value of a number. Currently, entering anything other than an integer will cause the program to output an error. Using some “elif” statements, these problems can be fixed.

Code:

num = int(input())
if num < 0:
print('The number is negative')
elif num > 0:
print('The number is positive')
elif num == 0:
print('Zero is neither positive nor negative')
else:
print("Please input an integer")
Output with input as "3":
The number is positive
Output with input as "0":
Zero is neither positive nor negative
Output with input as "ABC":
Please input an integer

In addition to identifying the value of a number, the program now knows what to do if something other than an integer is entered. This program can be extended in many ways simply with more “elif” statements.

Nested “if” Statements

Furthermore, branching statements can be combined with other branching statements. In programming, this is known as a nested “if” Statement. This occurs when another branch is placed in the code of an original branch. This concept of “nesting” is prevalent in programming and used with other concepts and functions.

“If” statements are the most used way to make decisions. Because of this, they have the potential to be combined with almost any other programming function. Many times, branches will be placed inside other branches to create even more specific conditions for the desired output, and nested “if” statements have superb usability in Python and can easily simplify a task that may seem complex at first.

Here is how the general structure of a nested “if” Statement may look:

if condition == true:
if second condition == true:
Block of Code
else:
Block of Code
else:
Block of Code
https://www.programsbuzz.com/article/python-nested-if-statement

In this code, the nested “if” will only be considered if the “if” condition above is true. Otherwise, the code will jump to the “else” Statement and disregard the nested if completely.

This technique is called a “control flow” and refers to using branches within each other. This concept of nesting does not apply only to branching statements and can be done with many different concepts like loops and user-defined functions. The video below may help you understand nested control flow statements:

Common Problems and Issues Encountered

Programming is a task of trial and error. It takes multiple attempts and time to determine what should be done to fix the bugs. Most likely, a program will not work as expected the first time around. Programming branching statements within code is no exception to this, and it takes time to learn how this job should be done.

Sometimes, the code is not working properly because the syntax needs to be written correctly. A beginner programmer may make this mistake multiple times and be frustrated as to why their program needs to be fixed. It is essential to pay attention to little details to ensure that branching statements are being written correctly. The most common mistake is forgetting to use two equal signs when setting a condition. Remember that the logical equality operator differs from the numerical equality operator, and misusing one will cause an error.

Additionally, forgetting to put colons after a branching statement will also cause an error. It is essential to ensure proper spacing before blocks of code beneath branching statements. All code under a branching statement requires the “tab” key to be pressed before typing. This applies to a nested “if” Statement as well.

Moving on from syntax typos, it is essential to understand that in an “if-elif-else” branch, the computer will disregard all other conditional statements as soon as something satisfies a condition. For example, in the code below, notice that “x” is more significant than both two and one. However, the code does not execute both conditionals, only the one that appeared first.

Code:

x = 7
if x > 1:
print('a')
elif x > 2:
print('b')
else:
print('c')
Output:
a

The program did not print out “b” or “c”, only “a” because it was the first condition that was satisfied. Note that if a programmer uses multiple “if” statements instead of an “if-elif-else” branch, then the program will individually check each “if” Statement instead of skipping all of them if it finds a satisfying condition. This is why an “if-elif-else” branch is computationally quicker than an “if-if-if” branch.

Takeaway

Branching is present in practically every program. Statistically, every fifth instruction in a program is a branch. Conditionals are the base decision maker and are usually the reason for the specific output of a program. There is a wide range of usages for conditionals, which can be combined with many other concepts in programming. Whenever a programmer needs a code to perform differently based on different interactions with the program, branching is used to achieve that. It is a process at the core of programming and must be adequately understood to have the ability to write more complex code.

Branching has seemingly endless possibilities for where it can be implemented and combined in infinite ways with other functions. Any developer, whether for the web or mobile apps, will be familiar with branching and conditionals since it is a core part of software development.

--

--