By the end of this practical, you will be able to:
len(), range(), enumerate(), zip()math and randomFirst, let's check if Miniconda (or Anaconda) is already installed on your machine.
Terminal (search in Spotlight or find in Applications → Utilities)Command Prompt or PowerShell from the Start menuWindows 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
If conda --version returned an error, follow these steps:
.exe file and follow the wizard. Check "Add to PATH" if prompted..pkg file, or run the shell installer in Terminal:bash Miniconda3-latest-MacOSX-arm64.sh
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
Configure Visual Studio Code for Python development:
Ctrl+Shift+X / Cmd+Shift+X)Ctrl+Shift+P (Windows) or Cmd+Shift+P (macOS)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.
Let's verify everything works by running a simple Python script:
test_script.pyCtrl+`) and run:python test_script.py
✅ 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!
[].list[0]list.append(value)list.insert(idx, value)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']
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.
().# 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
Task: Create a tuple named dimensions containing width 1920 and height 1080. Unpack them into variables w and h, then print w and h.
{}.dict[key] or dict.get(key)dict[key] = valuedel 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'])
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.
{} or set().set.add(value)set.remove(value)|), 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}
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.
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
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".
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
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.
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))
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"].
Write any custom Python code below to test and play around:
Loading Python…