Learn practical skills, build real-world projects, and advance your career

Branching using Conditional Statements and Loops in Python

Part 3 of "A Gentle Introduction to Programming with Python"

Branching with if, else and elif

A really powerful feature of programming languages is branching: the ability to make decisions and execute a different set of statements based on whether one or more conditions are true.

The if statement

In Python, branching is done using the if statement, which is written as follows:

if condition:
    statement1
    statement2

The condition can either be a variable or an expression. If the condition evaluates to True, then the statements within the if block are executed. Note the 4 spaces before statement1, statement 2 etc. The spaces inform Python that these statements are associated with the if statement above. This technique of structuring code by adding spaces is called indentation.

Indentation: Python relies heavily on indentation (white space before a statement) to define structure in code. This makes Python code easy to read and understand, but you can run into problems if you don't use indentation properly. Indent your code by placing the cursor at the start of the line and pressing the Tab key once to add 4 spaces. Pressing Tab again will indent the code further by 4 more spaces, and press Shift+Tab will reduce the indentation by 4 spaces.

As an example, let's write some code to check and print a message if a given number is even.

The elif statement

Python also provides an elif statement (short for "else if"), to chain a series of conditional blocks. The conditions are evaluated one by one. For the first condition that evaluates to True, the statements in the respective block are executed, and the remaining conditions are not evaluated. So, in a chain of if, elif, elif... statements, exactly one conditional block is evaluted.

Non-Boolean Conditions

Note that conditions do not necessarily have to be booleans. In fact, a condition can be any value. The value is convered into a boolean automatically using the bool operator. This means that falsy values like 0, '', {}, [] etc. evalute to False and all other values evalute to True.

!pip install jovian --upgrade --quiet