Exercises#
This page contains three take-home exercises that reinforce the concepts from Lecture 2. Each exercise asks you to write code from scratch based on a specification — no starter code is provided.
All files should be created inside your lecture2/ workspace folder.
Exercise 1 – Operator Expressions
Goal
Demonstrate your understanding of arithmetic, relational, logical, and membership operators by writing a program that computes and reports mission statistics for an autonomous drone.
Specification
Create a file lecture2/mission_stats.py that does the following:
Define the following variables (use the exact names shown):
total_distance:134.7(km)flight_time:2.75(hours)num_waypoints:8battery_capacity:5000(mAh)battery_remaining:1820(mAh)approved_altitudes: a list containing30,60,90, and120requested_altitude:75
Using only the variables above and Python operators, compute and print each of the following on its own line. Format every floating-point result to two decimal places using an f-string.
Average speed (
total_distance / flight_time).Distance per waypoint segment — there are
num_waypoints - 1segments between waypoints.The number of complete 30 km legs that fit into
total_distance(use floor division).The leftover distance after those complete legs (use modulus).
Battery percentage remaining (as a float, not an integer).
Whether
requested_altitudeis inapproved_altitudes(print the Boolean directly).A single Boolean expression that is
Truewhen all three of the following conditions hold:Battery percentage is above 25%.
Average speed is less than 60 km/h.
requested_altitudeis not inapproved_altitudes.
Expected output (your exact numbers should match):
Average speed: 48.98 km/h
Distance per segment: 19.24 km
Complete 30 km legs: 4
Leftover distance: 14.70 km
Battery remaining: 36.40%
Altitude approved: False
All conditions met: True
Deliverables
lecture2/mission_stats.pyThe program must run without errors and produce output that matches the expected values above.
Exercise 2 – String Processing
Goal
Practice string indexing, slicing, methods, and f-string formatting by writing a program that parses and reformats raw sensor log messages.
Specification
Create a file lecture2/log_parser.py that does the following:
Define a variable
raw_logwith this exact value:raw_log = "ts=1706817600;level=WARNING;src=IMU_03;msg=Gyro drift exceeded 0.05 rad/s"
Without hard-coding any index numbers, write code that extracts each field from the raw log. You must use string methods such as
.split(),.find(),.index(), or slicing relative to delimiters — not fixed numeric positions. Store the results in four variables:timestamp— the value afterts=(as a string)level— the value afterlevel=source— the value aftersrc=message— the value aftermsg=
Using the extracted variables, print the following reformatted output. All formatting must be done with f-strings.
A header line:
===== LOG ENTRY =====The timestamp right-aligned in a 20-character field.
The level converted to lowercase.
The source with the first
"_"replaced by" #"(e.g.,"IMU_03"becomes"IMU #03").The message in title case.
The total character count of the original
raw_log.A reversed copy of the
levelstring.A footer line:
=repeated to match the length of the header.
Expected output:
===== LOG ENTRY =====
Timestamp: 1706817600
Level: warning
Source: IMU #03
Message: Gyro Drift Exceeded 0.05 Rad/S
Log length: 76
Reversed level: GNINRAW
=====================
Deliverables
lecture2/log_parser.pyThe program must run without errors and produce output that matches the expected values above.
No index numbers may be hard-coded (e.g.,
raw_log[3:13]is not acceptable).
Exercise 3 – Control Flow
Goal
Write conditional logic from scratch to implement a multi-factor decision system for an autonomous forklift operating in a warehouse.
Specification
Create a file lecture2/forklift_decision.py that does the following:
Define the following variables at the top of your file:
payload_kg:320.0max_capacity_kg:500.0aisle_width:2.8(meters)fork_width:1.2(meters)battery_pct:42.0obstacle_ahead:Falseoperator_override:False
Task A — Load classification: Using
if/elif/else, classify the load and print the result:If
payload_kgis0: print"Load status: EMPTY"If
payload_kgis up to 50% ofmax_capacity_kg: print"Load status: LIGHT"If
payload_kgis between 50% and 85% (inclusive) ofmax_capacity_kg: print"Load status: MODERATE"If
payload_kgis above 85% but at or below 100% ofmax_capacity_kg: print"Load status: HEAVY — reduce speed"If
payload_kgexceedsmax_capacity_kg: print"Load status: OVERLOADED — cannot proceed"
You must compute the thresholds from the variables (do not hard-code
250,425, etc.).Task B — Clearance check: Compute the clearance on each side as
(aisle_width - fork_width) / 2. Using a ternary expression, set a variableclearance_oktoTrueif the per-side clearance is at least0.5meters, otherwiseFalse. Print the per-side clearance (two decimal places) and whether it is acceptable.Task C — Go / No-Go decision: Write a single compound
if/elif/elseblock that prints exactly one of the following outcomes:"DECISION: HALTED — obstacle detected"— ifobstacle_aheadisTrueandoperator_overrideisFalse."DECISION: OVERRIDE — proceeding with caution"— ifobstacle_aheadisTruebutoperator_overrideis alsoTrue."DECISION: RETURN TO CHARGE"— ifbattery_pctis below20and there is no obstacle."DECISION: PROCEED"— if none of the above apply.
Task D — Test your logic: Change the input variables to produce each of the following scenarios and verify your output is correct:
An overloaded forklift with an obstacle ahead.
An empty forklift with low battery and no obstacle.
A heavy forklift with operator override active and tight clearance.
Add a comment block at the bottom of your file showing the variable values you used for each test and the corresponding output.
Expected output for the default values:
Load status: MODERATE
Per-side clearance: 0.80 m — Acceptable: True
DECISION: PROCEED
Deliverables
lecture2/forklift_decision.pyThe program must run without errors and produce the expected output for the default variable values.
The comment block at the bottom must include at least three additional test scenarios with their outputs.