Branching using Conditional Statements and Loops in Python
Part 3 of "A Gentle Introduction to Programming with Python"
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.
In Python, branching is done using the
if statement, which is written as follows:
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
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
Tabkey once to add 4 spaces. Pressing
Tabagain will indent the code further by 4 more spaces, and press
Shift+Tabwill 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.
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
elif... statements, exactly one conditional block is evaluted.
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
 etc. evalute to
False and all other values evalute to
!pip install jovian --upgrade --quiet