Generating PDF…

Preparing…
← Back

Practical Activity 1: Environment Setup & Python Basics Review

Computer Programming 2

Practical Objectives

By the end of this practical, you will be able to:

  • Verify or install Miniconda — ensure your Python environment manager is ready
  • Configure VS Code — install the Python extension and select the correct interpreter
  • Run a test script — confirm your environment is working end-to-end
  • Review Python data structures — lists, tuples, dictionaries, and sets
  • Review built-in functionslen(), range(), enumerate(), zip()
  • Review standard libraries — importing and using math and random

Checking Miniconda

First, let's check if Miniconda (or Anaconda) is already installed on your machine.

  1. macOS: Open Terminal (search in Spotlight or find in Applications → Utilities)
  2. Windows: Open Command Prompt or PowerShell from the Start menu
  3. Run the following command:

Windows users: You can also search for and open Anaconda Prompt from the Start menu — this is a special terminal that automatically activates the conda environment.

# Check if conda is installed
conda --version

# Expected output (version may vary):
# conda 24.x.x

Installing Miniconda

If conda --version returned an error, follow these steps:

  1. Visit the official Miniconda download page:
    https://docs.anaconda.com/miniconda/
  2. Download the installer for your operating system
  3. Run the installer:
    • Windows: Double-click the .exe file and follow the wizard. Check "Add to PATH" if prompted.
    • macOS: Double-click the .pkg file, or run the shell installer in Terminal:
      bash Miniconda3-latest-MacOSX-arm64.sh
  4. Restart your terminal and verify with conda --version
# macOS shell installer example:
bash Miniconda3-latest-MacOSX-arm64.sh

# Follow the prompts, then restart terminal

# Verify installation:
conda --version

# Create your first environment (optional):
conda create -n cp2 python=3.12
conda activate cp2

VS Code Setup

Configure Visual Studio Code for Python development:

  1. Open VS Code — launch it from your Applications or Start menu
  2. Install the Python extension:
    • Go to the Extensions panel (Ctrl+Shift+X / Cmd+Shift+X)
    • Search for "Python"
    • Install the one by Microsoft (it has millions of downloads)
  3. Select the Miniconda interpreter:
    • Press Ctrl+Shift+P (Windows) or Cmd+Shift+P (macOS)
    • Type Python: Select Interpreter
    • Choose the Miniconda environment (e.g., base or cp2)
Command Palette shortcuts:
  Windows / Linux:  Ctrl + Shift + P
  macOS:            Cmd + Shift + P

Then type:
  Python: Select Interpreter

Look for entries like:
  ✓ Python 3.12.x ('base': conda)
  ✓ Python 3.12.x ('cp2': conda)

The selected interpreter appears in the
bottom-left status bar of VS Code.

Running a Test Script

Let's verify everything works by running a simple Python script:

  1. In VS Code, create a new file called test_script.py
  2. Type the following code into the file:
  3. Run it using one of these methods:
    • Click the ▶ Play button in the top-right corner
    • Or open the integrated terminal (Ctrl+`) and run:
      python test_script.py
  4. You should see the message printed in the terminal output

Success! If you see the output, your Miniconda environment is active and properly configured.

# test_script.py
print("Miniconda environment is active and running!")
# Run from the integrated terminal:
python test_script.py

# Expected output:
# Miniconda environment is active and running!

Python Review: Lists

  • Lists are ordered, mutable (changeable) collections.
  • They allow duplicate elements and are defined using square brackets: [].
  • Common Operations:
    • Index access (0-based): list[0]
    • Add to end: list.append(value)
    • Insert at index: list.insert(idx, value)
    • Remove item: list.remove(value) or list.pop(idx)
# Creating a list
fruits = ["apple", "banana"]

# Accessing elements
print(fruits[0])          # Output: apple

# Modifying the list
fruits.append("cherry")   # ["apple", "banana", "cherry"]
fruits.insert(1, "mango") # ["apple", "mango", "banana", "cherry"]
fruits.remove("banana")   # ["apple", "mango", "cherry"]
print(fruits)             # Output: ['apple', 'mango', 'cherry']

Practice: Working with Lists

Task: Create a list named languages containing "Python", "Java", and "C++". Append "JavaScript" to the list, insert "Ruby" at index 1, and print the final list.

Loading Python…
Loading Python runtime… (first load may take a few seconds)

Python Review: Tuples

  • Tuples are ordered and immutable (cannot be changed after creation).
  • They allow duplicates and are defined using parentheses: ().
  • Why use Tuples?
    • Protection against accidental modification (read-only collections).
    • Faster execution and smaller memory footprint than lists.
    • Commonly used to return multiple values from functions and for unpacking.
# Creating a tuple
coordinates = (40.7128, -74.0060)

# Accessing elements
print(coordinates[0])     # Output: 40.7128

# Unpacking a tuple
lat, lon = coordinates
print(f"Lat: {lat}, Lon: {lon}")

# Immutable error if you try to assign:
# coordinates[0] = 50.0   # Raises TypeError

Practice: Working with Tuples

Task: Create a tuple named dimensions containing width 1920 and height 1080. Unpack them into variables w and h, then print w and h.

Loading Python…
Loading Python runtime… (first load may take a few seconds)

Python Review: Dictionaries

  • Dictionaries store data in key-value pairs. They are mutable and indexed by keys.
  • Keys must be unique and immutable (like strings or integers). Defined using: {}.
  • Common Operations:
    • Access value by key: dict[key] or dict.get(key)
    • Add/Update value: dict[key] = value
    • Remove key-value pair: del dict[key] or dict.pop(key)
# Creating a dictionary
student = {"name": "Alice", "age": 20}

# Accessing values
print(student["name"])    # Output: Alice

# Adding and updating
student["email"] = "alice@uni.edu" # Adds key
student["age"] = 21                # Updates value

# Getting all keys/values
print(student.keys())     # dict_keys(['name', 'age', 'email'])
print(student.values())   # dict_values(['Alice', 21, 'alice@uni.edu'])

Practice: Working with Dictionaries

Task: Create a dictionary named car with keys "brand" ("Toyota"), "model" ("Corolla"), and "year" (2018). Update the year to 2022, add a new key "color" ("red"), and print the dictionary.

Loading Python…
Loading Python runtime… (first load may take a few seconds)

Python Review: Sets

  • Sets are unordered collections of unique elements.
  • They do not allow duplicates and are mutable. Defined using: {} or set().
  • Common Operations:
    • Add element: set.add(value)
    • Remove element: set.remove(value)
    • Set operations: Union (|), Intersection (&), Difference (-)
# Creating a set (duplicates are removed)
unique_nums = {1, 2, 3, 2, 1}
print(unique_nums)        # Output: {1, 2, 3}

# Modifying set
unique_nums.add(4)
unique_nums.remove(2)     # {1, 3, 4}

# Set algebra
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b)              # Union: {1, 2, 3, 4, 5}
print(a & b)              # Intersection: {3}

Practice: Working with Sets

Task: Create a set named a with values {1, 2, 3, 4} and a set named b with values {3, 4, 5, 6}. Print the intersection and the difference (a - b) of the two sets.

Loading Python…
Loading Python runtime… (first load may take a few seconds)

Python Review: len() & range()

  • len() returns the number of items in any collection (list, string, set, dictionary).
  • range() generates a sequence of integers:
    • range(stop): starts at 0, stops before `stop`.
    • range(start, stop): starts at `start`, stops before `stop`.
    • range(start, stop, step): increments by `step`.
# len() usage
colors = ["red", "green", "blue"]
print(len(colors))        # Output: 3
print(len("Python"))       # Output: 6

# range() usage in loops
for i in range(3):
    print(i, end=" ")     # Output: 0 1 2

print()
for i in range(10, 25, 5):
    print(i, end=" ")     # Output: 10 15 20

Practice: len() & range()

Task: Write a for loop using range() to print all even numbers from 2 to 10 (inclusive). Also, print the length of the string "Computer Programming 2".

Loading Python…
Loading Python runtime… (first load may take a few seconds)

Python Review: enumerate() & zip()

  • enumerate() yields pairs of (index, item) when looping over an iterable.
  • zip() aggregates elements from multiple iterables, stopping when the shortest list is exhausted.
# enumerate()
items = ["apple", "banana"]
for idx, val in enumerate(items):
    print(f"{idx}: {val}")
# Output:
# 0: apple
# 1: banana

# zip()
names = ["Alice", "Bob"]
scores = [90, 85]
for name, score in zip(names, scores):
    print(f"{name} scored {score}")
# Output:
# Alice scored 90
# Bob scored 85

Practice: enumerate() & zip()

Task: Given a list of devices devices = ["LED", "Switch", "Servo"], loop through it using enumerate() and print each index and device. Then zip the devices list with pins = [13, 7, 9] and print each device with its GPIO pin.

Loading Python…
Loading Python runtime… (first load may take a few seconds)

Python Review: Standard Libraries

  • Python comes with powerful built-in libraries that must be imported:
    • import math: mathematical functions (trigonometry, log, constants, etc.)
    • import random: generation of random values and selection helpers.
import math
print(math.sqrt(64))      # Output: 8.0
print(math.pi)            # Output: 3.14159...

import random
# Random integer between 1 and 6 (like rolling a die)
print(random.randint(1, 6)) 

# Pick random item from list
choices = ["yes", "no", "maybe"]
print(random.choice(choices))

Practice: Standard Libraries

Task: Import the math and random libraries. Print the value of math.log10(100). Then pick and print a random name from the list names = ["Alice", "Bob", "Charlie", "David"].

Loading Python…
Loading Python runtime… (first load may take a few seconds)

Interactive Console Sandbox

Write any custom Python code below to test and play around:

Loading Python…
Loading Python runtime… (first load may take a few seconds)