Structure your code better in Google Colab with Text and Code Cells

Mitesh Parmar
4 min readMar 30, 2021

--

Google Colab is a cloud based Jupyter Notebook that allows you to run and execute your Python code remotely and save your work into your personal Google Drive. It’s ace card is the availability of the free graphics processing units (GPU) to allow fast training.

One of the excellent features of Colab that all developers should take full advantage of is the use of text and code compartmentalisation. Basically, splitting your code up into chucks of code and text in code cells and text cells respectively. This will facilitate eligibility and give you well defined checkpoints so you can visualise your data’s structure as you code.

Allow me to demonstrate…

Opening a new Google Colaboratory file shows the following:

To insert a text cell you can either click on the ‘+ Text’ button in the top left of the screen:

Or you can hover your mouse over the top of the code cell which shows both Code and Text buttons and click on the Text button:

Simply double-click or press enter to start writing your text:

Colab presents you will a series of text editor icons which allow you to do functions found in most text editors:

The final icon toggles the textual display to the right side of the screen instead of the default below the editing area:

Once you’ve entered your text, simply click back into the grey-coloured box to enter your Python code:

As I’ve followed the machine learning tutorials on www.pythonprogramming.net I’ve structured my exercises like so:

I’ve used a text cell for the hyperlinks and synopsis. The first cell code imports a non-native python module and the second cell code imports the libraries and starts my coding. I usually add a short comment above each line of code so reading over this and debugging is easier and its also good programming practice.

Scrolling down shows df.head() being the last code in the second code cell (section 3). Notice how Colab doesn’t need a print(df.head()) statement. Colab simply interprets the df.head() function and displays the data in a nice neat table for visualisation:

This is a good checkpoint to ensure your data is as you expect it to be. At the very bottom I’ve inserted a text cell to explain what we’re looking at when the df.head() is run.

Scrolling further down shows the final code cell (section 4) and the last code is the df.head() function which displays the Pandas dataframe object which has been drastically altered from before:

To execute all code cells from top to bottom click on Runtime and click ‘Run all’:

Conclusion: By using multiple text cells and code cells has helped me to structure my text and code better and create multiple checkpoints which help visualise the data as we code and alter the data object.

I hope this article helps you do this too. Happy Colab coding…

--

--