Skip to content
IT Vizag
← Functions & Clean Code

▶ Sign up free for the video, slides & prompts

The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.

Checking…

Mini project: unit converter

Lesson 9 of 9 · 2 min read

A menu-driven converter built from small functions.

🎬 Video version coming soon — read it now

Let's build a menu-driven converter from small, well-named functions, with safe input and clean code.

The plan

  • A function for each conversion
  • One function to ask for a number safely
  • A menu loop that runs until the user quits

The code

🔒 Code example: sign up free (above) to unlock it.

What to notice

  • Functions are values. The dictionary stores km_to_miles itself (no brackets), and convert(value) calls whichever one was chosen. Adding a conversion means adding one function and one dictionary line; the menu updates itself.
  • ask_number handles bad input in one place.
  • main() holds the program flow, so the top of the file is just definitions.
  • Named constants instead of magic numbers.

Try it

Convert 21 km (a half marathon on Beach Road), 34 °C and 70 kg. You should get about 13.05 miles, 93.20 °F and 154.32 lb.

Challenges

  1. Add rupees to US dollars, with the rate as a constant you can update.
  2. Add the reverse conversions (miles to km, and so on).
  3. Keep a history list and show the last 5 conversions with option "h".
  4. Ask AI to review it using the prompt from the previous lesson.

What you learned in this course

  • Defining functions, parameters, return values, defaults and keyword arguments
  • Local and global scope, and why passing data in and out is cleaner
  • try/except, raise and a calm debugging routine
  • Readable code, PEP 8 and AI code reviews

Next course: Files, Modules & Packages. Your programs will save and load data, use Python's huge library collection and run on your own laptop.

In one line

You built a clean, extendable program from small functions, with safe input and a menu driven by a dictionary.

Saved on this device. Sign in to keep progress everywhere.

Share with a friend