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. PressingTab
again will indent the code further by 4 more spaces, and pressShift+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.
a_number = 34
if a_number % 2 == 0:
print("We're inside an if block")
print('The given number {} is even'.format(a_number))
We're inside an if block
The given number 34 is even
Note that we are using the modulus operator %
to find the remainder from the division of a_number
by 2
, and then we are using the comparision operator ==
check if the reminder is 0
, indicating that the number is divisible by 2 i.e. it is even.
Since the number 34
is indeed divisible by 2
the expression a_number % 2 == 0
evaluates to True
, so the print
statement under the if
statement is executed. Also note that we are using the string format
method to include the number within the message.
Let's try the above again with an odd number.
another_number = 33