Writing and Running Code Cells in Google Colab

by | Python

Introduction to Google Colab Interface

Google Colab is a free, cloud-based platform for coding and executing code, ideal for data analysis, machine learning, and other compute-intensive tasks. This guide introduces beginners to the basics of using Google Colab for coding and computation.

Setting Up Google Colab

  1. Accessing Google Colab:

    • Open your web browser and go to Google Colab.
    • Ensure you are signed in with your Google account.
  2. Creating a New Notebook:

    • Click on the “File” menu.
    • Select “New notebook” from the dropdown menu.
    • A new tab with an empty notebook will open.

The Interface Components

Menu Bar

  • File: Options for creating, opening, saving, and managing your notebooks.
  • Edit: Standard editing options like undo, redo, and cut/copy/paste cells.
  • View: Options to toggle the format (e.g., code vs. text), show/hide elements.
  • Insert: Add new cells, text, or other elements.
  • Runtime: Manage the execution environment, including running code, interrupting execution, and changing runtime types.
  • Tools: Additional utilities such as settings and keyboard shortcuts.
  • Help: Access documentation and community support.

Toolbar

  • Run Cell: Executes the code or Markdown in the current cell.
  • Stop Execution: Interrupts the current execution.
  • Insert Code/Text Cell: Adds a new code/text cell below the current one.

Code Cells

  • Where you write and execute code.
  • Can be executed by pressing the “Run” button or using Shift + Enter.

Text Cells (Markdown)

  • Use Markdown for text formatting.
  • Can be used for adding explanations, annotations, and documentation within the notebook.

Basic Operations

Running Code

  1. Click inside a code cell.
  2. Type your code (e.g., print("Hello, world!")).
  3. Press Shift + Enter to execute the cell.

Adding and Formatting Text

  1. Click on a cell and change its type to “Text” using the dropdown on the toolbar.
  2. Enter your Markdown-formatted text (e.g., # Heading 1, ## Heading 2, **bold text**).
  3. Press Shift + Enter to render the text.

Managing Runtime

  • Change Runtime Type:

    1. Go to the “Runtime” menu.
    2. Select “Change runtime type”.
    3. Choose your preferred hardware accelerator (e.g., GPU, TPU) and click “Save”.
  • Restarting the Runtime:

    1. Go to the “Runtime” menu.
    2. Select “Restart runtime”.

Practical Example

Step-by-Step Example

  1. Create a new code cell and type:
    print("Welcome to Google Colab!")

  2. Create a new text cell and type in Markdown:
    # Introduction
    This notebook demonstrates basic usage of Google Colab.

  3. Execute the cells by pressing Shift + Enter.

By following these steps, you have now successfully created a Google Colab notebook, executed a simple piece of code, and added formatted text. Google Colab is a flexible and powerful tool that supports various types of computation and documentation directly in your web browser.

Creating and Managing Code Cells in Google Colab

In this part of the guide, we’ll cover how to create, edit, and manage code cells in Google Colab. Follow these steps to effectively work with code cells.

Creating Code Cells

  1. Adding a New Code Cell:
    • Click on the “+ Code” button located at the top left of the toolbar.
    • Alternatively, use keyboard shortcuts for quicker access:
      • Press Ctrl + M + B (Windows/Linux)
      • Press Cmd + M + B (Mac)

Editing Code Cells

  1. Editing Content:

    • Click on the code cell you want to edit.
    • Start typing or make any necessary changes.
  2. Running Code Cells:

    • Click the “Run” button (play icon) on the left side of the code cell.
    • Alternatively, use keyboard shortcuts:
      • Press Shift + Enter to run the current cell and move to the next cell.
      • Press Ctrl + Enter to run the current cell and stay in the same cell.
      • Press Alt + Enter to run the current cell and insert a new code cell below.

Managing Code Cells

  1. Moving Code Cells:

    • Click and drag the cell by the “Cell Handle” (a six-dot icon) on the left side of the cell to move it up or down.
  2. Deleting Code Cells:

    • Click on the cell to select it.
    • Click the trash can icon on the toolbar to delete the selected cell.
    • Alternatively, use the keyboard shortcut:
      • Press Ctrl + M + D (Windows/Linux)
      • Press Cmd + M + D (Mac)
  3. Undo Cell Deletion:

    • Click the “Edit” menu and select “Undo Delete Cells”.
    • Or use the keyboard shortcut:
      • Press Ctrl + Z (Windows/Linux)
      • Press Cmd + Z (Mac)
  4. Splitting Code Cells:

    • Place the cursor at the position where you want to split the cell.
    • Use the keyboard shortcut:
      • Press Ctrl + Shift + - (Windows/Linux)
      • Press Cmd + Shift + - (Mac)
  5. Merging Cells:

    • Select the cells you want to merge.
    • Use the keyboard shortcut:
      • Press Ctrl + Shift + M (Windows/Linux)
      • Press Cmd + Shift + M (Mac)
  6. Commenting Code:


    • Select the code you want to comment.


    • Use the keyboard shortcut for single-line comments:

      • Press Ctrl + / (Windows/Linux)
      • Press Cmd + / (Mac)

    • For block comments, manually enclose the code with appropriate comment symbols depending on the language being used.


Conclusion

These steps should help you effectively create, edit, and manage code cells on Google Colab. Practice frequently to become proficient in handling cells for various computational tasks. This guide assumes that you are familiar with the primary interface elements required to access the mentioned features.

Writing Basic Python Code in Google Colab

This guide covers the basics of writing and running Python code in Google Colab.

Printing Output

# Print a simple message
print("Hello, world!")

Basic Arithmetic Operations

# Addition
addition = 5 + 3
print("Addition:", addition)

# Subtraction
subtraction = 10 - 4
print("Subtraction:", subtraction)

# Multiplication
multiplication = 7 * 6
print("Multiplication:", multiplication)

# Division
division = 8 / 2
print("Division:", division)

# Modulus
modulus = 10 % 3
print("Modulus:", modulus)

Variables and Data Types

# Integer
integer_var = 10
print("Integer:", integer_var)

# Float
float_var = 10.5
print("Float:", float_var)

# String
string_var = "This is a string"
print("String:", string_var)

# Boolean
boolean_var = True
print("Boolean:", boolean_var)

Lists

# Create a list
my_list = [1, 2, 3, 4, 5]

# Access elements
print("First element:", my_list[0])
print("Last element:", my_list[-1])

# Append elements
my_list.append(6)
print("After appending:", my_list)

# Remove elements
my_list.remove(3)
print("After removing:", my_list)

Dictionaries

# Create a dictionary
my_dict = {
    'name': 'John',
    'age': 25,
    'city': 'New York'
}

# Access values
print("Name:", my_dict['name'])
print("Age:", my_dict['age'])

# Add a new key-value pair
my_dict['email'] = 'john.doe@example.com'
print("After adding email:", my_dict)

# Remove a key-value pair
del my_dict['city']
print("After deleting city:", my_dict)

Conditional Statements

x = 10

# If-else statement
if x > 5:
    print("x is greater than 5")
else:
    print("x is less than or equal to 5")

Loops

For Loop:

# For loop with list
for i in my_list:
    print(i)

While Loop:

# While loop
count = 0
while count < 5:
    print("Count is:", count)
    count += 1

Functions

# Define a function
def greet(name):
    return f"Hello, {name}!"

# Call the function
print(greet("Alice"))

Importing Libraries

# Importing numpy library
import numpy as np

# Using numpy to create an array
array = np.array([1, 2, 3, 4, 5])
print("Numpy array:", array)

By following this guide, you will be able to write basic Python code in Google Colab, execute it, and see the results directly in the environment.

Utilizing Libraries and Importing Data

Utilizing Libraries

Google Colab offers a wide range of pre-installed libraries that you can use for data analysis, machine learning, visualization, and more. Here’s a practical example:

Loading Necessary Libraries

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression

Importing Data

Google Colab allows you to import data from various sources, such as your local machine, Google Drive, or online URLs.

Importing Data From Local Machine

You can use the following code to upload a file from your local machine:

from google.colab import files

# This will prompt you to upload a file from your local machine
uploaded = files.upload()

# Assume uploaded file is named 'data.csv'
data = pd.read_csv('data.csv')

# Display the first few rows of the dataset
data.head()

Importing Data From Google Drive

First, you’ll need to mount your Google Drive to access files stored there.

from google.colab import drive
drive.mount('/content/drive')

# Now you can read a file from your Google Drive
file_path = '/content/drive/MyDrive/data.csv'
data = pd.read_csv(file_path)

# Display the first few rows of the dataset
data.head()

Importing Data From a URL

If your data is available online, you can directly import it using pandas’ read_csv function.

url = 'https://example.com/data.csv'
data = pd.read_csv(url)

# Display the first few rows of the dataset
data.head()

Summary

  • We loaded essential libraries for data processing, analysis, and visualization.
  • We imported data from a local machine, Google Drive, and a URL.

These simple steps should help you kickstart your data analysis project in Google Colab.

Executing and Troubleshooting Code

Executing Code in Google Colab

To execute code in Google Colab, follow these steps:

  1. Write the Code:

    • Insert your code into a code cell.
    • For instance, if writing Python, it might look like this:
      # Example: Simple Python Code
      a = 10
      b = 20
      print(a + b)

  2. Run the Code Cell:

    • Click the Run button on the left side of the code cell, or press Shift + Enter.

Troubleshooting Code

When writing and executing code, you might encounter errors. Here’s how to troubleshoot:

Syntax Errors

Example:

# Example with a syntax error
a = 10
b = 20
print(a + b)

Error:

SyntaxError: invalid syntax

Solution:

  • Carefully check the syntax according to the language rules.
  • In this case, ensure all keywords, variable names, and operators are correctly used.

Runtime Errors

Example:

# Example with a runtime error
a = 10
b = 0
print(a / b)

Error:

ZeroDivisionError: division by zero

Solution:

  • Investigate the error message which usually indicates the type and position of the error.
  • Here, the issue is dividing by zero. Correct the logic to avoid this situation.

Logical Errors

Example:

# Example with a logical error
a = 10
b = 20
print(a - b)  # Intent is to add, but the code subtracts

Issue:

  • No error is raised, but the output is not as expected.

Solution:

  • Carefully review the logic and ensure it meets the intended objectives.
  • In this example, change the operation to addition:
    print(a + b)

Using Debugging Tools

  1. Printing Debug Statements:

    • Add print statements to trace code execution:
      a = 10
      b = 20
      print('Value of a:', a)
      print('Value of b:', b)
      print('Sum:', a + b)

  2. Using Assert Statements:

    • Ensure conditions are met during execution:
      a = 10
      b = 20
      assert b != 0, "b should not be zero"
      print(a / b)

  3. Utilizing Python’s Built-in Debugger:

    • Insert breakpoints and step through the code:
      import pdb
      pdb.set_trace()

      a = 10
      b = 20
      result = a + b
      print('Sum:', result)

By following these steps, you can effectively execute and troubleshoot your code in Google Colab. Remember to keep an eye on the error messages and use debugging tools wisely to locate and fix issues in your code.

Related Posts