Branching using Conditional Statements and Loops in Python

7RfcHV0.png

This tutorial covers the following topics:

  • Branching with ' if ' , ' else ' and 'elif'
  • Nested conditions and 'if' expressions
  • Iteration with 'while' loops
  • Iterating over containers with 'for' loops
  • Nested loops, 'break' and 'continue' statements

Branching with if, else and elif

One of the most powerful features 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 implemented using the if statement, which is written as follows:

  • if condition:
    • statement1
    • statement2

The condition can be a value, variable or expression. If the condition evaluates to True, then the statements within the if block are executed. Notice the four spaces before statement1, statement2, 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 code structure. This makes Python code easy to read and understand. 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.

For 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.