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"

This tutorial is the third in a series on introduction to programming using the Python language. These tutorials take a practical coding-based approach, and the best way to learn the material is to execute the code and experiment with the examples. Check out the full series here:

  1. First Steps with Python and Jupyter
  2. A Quick Tour of Variables and Data Types
  3. Branching using Conditional Statements and Loops
  4. Writing Reusable Code Using Functions
  5. Reading from and Writing to Files
  6. Object Oriented Programming with Classes

How to run the code

This tutorial hosted on Jovian.ml, a platform for sharing data science projects online. You can "run" this tutorial and experiment with the code examples in a couple of ways: using free online resources (recommended) or on your own computer.

This tutorial is a Jupyter notebook - a document made of "cells", which can contain explanations in text or code written in Python. Code cells can be executed and their outputs e.g. numbers, messages, graphs, tables, files etc. can be viewed within the notebook, which makes it a really powerful platform for experimentation and analysis. Don't afraid to experiment with the code & break things - you'll learn a lot by encoutering and fixing errors. You can use the "Kernel > Restart & Clear Output" menu option to clear all outputs and start again from the top of the notebook.

Option 1: Running using free online resources (1-click, recommended)

The easiest way to start executing this notebook is to click the "Run" button at the top of this page, and select "Run on Binder". This will run the notebook on mybinder.org, a free online service for running Jupyter notebooks. You can also select "Run on Colab" or "Run on Kaggle", but you'll need to create an account on Google Colab or Kaggle to use these platforms.

Option 2: Running on your computer locally

You'll need to install Python and download this notebook on your computer to run in locally. We recommend using the Conda distribution of Python. Here's what you need to do to get started:

  1. Install Conda by following these instructions. Make sure to add Conda binaries to your system PATH to be able to run the conda command line tool from your Mac/Linux terminal or Windows command prompt.

  2. Create and activate a Conda virtual environment called zerotopandas which you can use for this tutorial series:

conda create -n intro-to-python -y python=3.8 
conda activate intro-to-python

You'll need to create the environment only once, but you'll have to activate it every time want to run the notebook. When the environment is activated, you should be able to see a prefix (intro-to-python) within your terminal or command prompt.

  1. Install the required Python libraries within the environmebt by the running the following command on your terminal or command prompt:
pip install jovian jupyter numpy pandas matplotlib seaborn --upgrade
  1. Download the notebook for this tutorial using the jovian clone command:
jovian clone aakashns/python-branching-and-loops

The notebook is downloaded to the directory python-branching-and-loops.

  1. Enter the project directory and start the Jupyter notebook:
cd python-branching-and-loops
jupyter notebook
  1. You can now access Jupyter's web interface by clicking the link that shows up on the terminal or by visiting http://localhost:8888 on your browser. Click on the notebook python-branching-and-loops.ipynb to open it and run the code. If you want to type out the code yourself, you can also create a new notebook using the "New" button.

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:

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.

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.