Skip to content

Temperature Converter

Beginner ~10 min

What you'll build

A Python script with celsius_to_fahrenheit and fahrenheit_to_celsius functions, and a small CLI that asks the user for a value and prints both conversions.

Goals

  • Define functions with parameters and return values
  • Apply the temperature conversion formulas correctly
  • Format output with f-strings
  • Read and convert user input

Prerequisites

  • Functions and return values
  • Basic arithmetic
  • input() and float()

Steps

  1. 1

    Write the conversion functions

    Define celsius_to_fahrenheit(c) and fahrenheit_to_celsius(f). The formulas are F = C * 9/5 + 32 and C = (F - 32) * 5/9. Each function takes one number and returns one number.

    Code
    def celsius_to_fahrenheit(c):
        return c * 9 / 5 + 32
    
    def fahrenheit_to_celsius(f):
        return (f - 32) * 5 / 9

    Expected result

    celsius_to_fahrenheit(0) returns 32.0; fahrenheit_to_celsius(98.6) returns about 37.0.

  2. 2

    Read input from the user

    Ask the user for a temperature in Celsius and convert the input string to a float. float() handles decimal input like 36.6.

    Code
    c = float(input("Enter temperature in Celsius: "))

    Expected result

    The script waits for input and stores the numeric value in c.

  3. 3

    Print the result with an f-string

    Call the conversion function and print the result using an f-string. f-strings let you embed expressions directly inside the string with curly braces.

    Code
    f = celsius_to_fahrenheit(c)
    print(f"{c}°C = {f}°F")

    Expected result

    Typing 25 prints "25.0°C = 77.0°F".

  4. 4

    Add input validation & exception handling

    Add a try/except block in the main function to handle user input errors, using ValueError to catch illegal conversions. Python's exception handling lets the program degrade gracefully on bad input instead of crashing.

    Code
    def safe_input(prompt, validator=None):
        """Read input with validation and error handling."""
        while True:
            try:
                raw = input(prompt)
                value = float(raw)
                if validator and not validator(value):
                    raise ValueError(f"Value {value} failed validation")
                return value
            except ValueError as err:
                print(f"Invalid input: {err}. Please try again.")
    
    # Usage
    age = safe_input("Enter your age: ", lambda x: x > 0)

    Expected result

    Invalid input (non-number or failed validation) prompts for re-entry; valid input returns the number.

  5. 5

    Write unit tests

    Write tests for the core function using unittest or assert statements, covering normal paths, boundary values, and exceptions. Tests are the safety net for code quality.

    Code
    import unittest
    
    class TestCoreFunc(unittest.TestCase):
        def test_normal(self):
            self.assertEqual(core_func(5), expected_5)
    
        def test_boundary(self):
            self.assertEqual(core_func(0), expected_0)
    
        def test_exception(self):
            with self.assertRaises(ValueError):
                core_func(-1)
    
    if __name__ == "__main__":
        unittest.main()

    Expected result

    Running python test.py prints OK with all three test cases passing.

Try it yourself

What you learned

You wrote pure functions that encode a formula and wired them to a command-line interface with input and f-strings — the building blocks of most small Python utilities.

Related Resources

Related Lessons

  • Functions

    Function definition, parameters, and return used here.

  • Strings

    f-string formatting used to display the result.

Related Practice

Related Tools

Related Cheatsheets

Related Reference

Related Errors

Related Glossary

Related Glossary

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

Related Errors

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

← Back to topic