Skip to main content

Lab 01 — Build a CLI Calculator

Hands-on Lab 30 min Beginner

Objectives

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

  1. Use input() to collect numeric data and convert it
  2. Apply all arithmetic operators correctly
  3. Format output with f-strings including alignment and precision
  4. Handle edge cases (division by zero) with conditionals
  5. Organize code with functions

Prerequisites

  • Python 3.10+ installed
  • Lessons 01.1, 01.2, 01.3 completed

Step 1 — Create the Project

mkdir ~/python-course/lab-01
cd ~/python-course/lab-01

Create calculator.py:

#!/usr/bin/env python3
"""
Lab 01 — CLI Calculator
A complete command-line calculator demonstrating Python fundamentals.
"""

def get_numbers():
"""Prompt the user for two numbers and return them as floats."""
while True:
try:
a = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))
return a, b
except ValueError:
print("❌ Invalid input — please enter numeric values.\n")


def calculate(a, b):
"""Perform all operations and return results as a dict."""
results = {
"addition": a + b,
"subtraction": a - b,
"multiplication": a * b,
"division": a / b if b != 0 else None,
"floor_division": a // b if b != 0 else None,
"modulo": a % b if b != 0 else None,
"power": a ** b,
}
return results


def display_results(a, b, results):
"""Print a formatted results table."""
width = 50
print("\n" + "=" * width)
print(f"{'CALCULATION RESULTS':^{width}}")
print("=" * width)
print(f" {'Inputs':<20} a = {a:>10} b = {b:>10}")
print("-" * width)

ops = [
("Addition", "+", results["addition"]),
("Subtraction", "-", results["subtraction"]),
("Multiplication", "×", results["multiplication"]),
("Division", "÷", results["division"]),
("Floor Division", "//", results["floor_division"]),
("Modulo", "%", results["modulo"]),
("Power", "**", results["power"]),
]

for name, symbol, value in ops:
if value is None:
display = "undefined (division by zero)"
else:
display = f"{value:,.6g}"
print(f" {name:<18} ({symbol}): {display:>20}")

print("=" * width)

# Extra statistics
if results["division"] is not None:
ratio = results["division"]
print(f"\n a / b expressed as:")
print(f" Float : {ratio:.10f}")
print(f" 2 dec : {ratio:.2f}")
print(f" Sci : {ratio:.3e}")
print(f" Percent: {ratio:.2%}")
print()


def run_calculator():
"""Main loop — allows multiple calculations."""
print("=" * 50)
print(f"{'Python CLI Calculator — Lab 01':^50}")
print("=" * 50)

while True:
a, b = get_numbers()
results = calculate(a, b)
display_results(a, b, results)

again = input("Calculate again? (y/n): ").strip().lower()
if again != "y":
break

print("\nGoodbye! 👋")


if __name__ == "__main__":
run_calculator()

Step 2 — Run and Test

python3 calculator.py

Verification ✅

Test with a = 17, b = 5:

==================================================
Python CLI Calculator — Lab 01
==================================================
Enter the first number: 17
Enter the second number: 5

==================================================
CALCULATION RESULTS
==================================================
Inputs a = 17 b = 5
--------------------------------------------------
Addition (+): 22
Subtraction (-): 12
Multiplication (×): 85
Division (÷): 3.4
Floor Division (//): 3
Modulo (%): 2
Power (**): 1419857
==================================================
a / b expressed as:
Float : 3.4000000000
2 dec : 3.40
Sci : 3.400e+00
Percent: 340.00%

Step 3 — Test Edge Cases

Run again with b = 0:

Enter the first number: 10
Enter the second number: 0
Division (÷): undefined (division by zero)
Floor Division (//): undefined (division by zero)
Modulo (%): undefined (division by zero)

Verification ✅

The calculator should gracefully display "undefined" instead of crashing.


Step 4 — Test Invalid Input

Enter the first number: abc
❌ Invalid input — please enter numeric values.

Enter the first number:

Verification ✅

The try/except ValueError block catches the error and prompts again.


Bonus Challenge

Add a history feature:

  1. Store each calculation in a list of tuples [(a, b, results), ...]
  2. At the end, print a summary showing all calculations performed
  3. Calculate the average result of all addition operations
history = []

# Inside the loop, after display_results:
history.append((a, b, results))

# After the loop:
print(f"\n{'HISTORY':^50}")
for i, (a, b, res) in enumerate(history, 1):
print(f" #{i}: {a} + {b} = {res['addition']}")

Cleanup

No cleanup required — this is a local Python script.


Summary

In this lab you:

  • Used float(input(...)) with error handling for robust number input
  • Applied all 7 arithmetic operators including edge case (division by zero)
  • Formatted a results table with f-strings: alignment (:<, :>), precision (.2f), scientific notation (.3e), and percentage (.2%)
  • Organized code with focused functions following the single responsibility principle