thecodex.expert · The Codex Family of Knowledge
Tier 0 · Absolute Beginner · Python Project

Temperature Converter

Convert temperatures between Celsius and Fahrenheit. You will learn how a program takes a number, applies a formula, and gives back a result — the essence of almost every useful tool.

🧠 Teaches how to think spoonfed, every age Last verified:

1 The Problem

We want a small program that converts a temperature from Celsius to Fahrenheit, or the other way around. The user picks which direction, types a number, and the program does the maths and shows the answer. Simple — but it teaches the core shape of every calculator-style tool: ask, calculate, show.

Where this shows up in real life: every app that takes a number and transforms it — a currency converter, a tip calculator, a unit converter, a tax estimator — is doing exactly this. Take input, apply a formula, return a result. Master the pattern here and you can build any of them.

2 How to Think About It

Before any code, think about the two things the program needs to know and the two formulas it might use. You do not need Python yet — just the plan:

The plan — in plain English
1. Ask the user which way to convert (Celsius→Fahrenheit, or the reverse). → 2. Ask for the temperature number. → 3. Apply the right formula (C→F is ×9/5 then +32; F→C is −32 then ×5/9). → 4. Show the answer. The only “hard” part is remembering the two formulas — and the program remembers them for you.

1

2

Ask: convert which way?

Choice 1 or 2?

Read Celsius

Read Fahrenheit

Multiply by 9/5, add 32

Subtract 32, multiply by 5/9

Show Fahrenheit

Show Celsius

3 The Build — explained part by part

Here is the complete converter. Read each line’s note below — you should understand the whole thing from the notes alone.

Pythonconverter.py
# A temperature converter: Celsius to Fahrenheit and back.

print("Temperature Converter")
print("1. Celsius to Fahrenheit")
print("2. Fahrenheit to Celsius")

choice = input("Choose 1 or 2: ")

if choice == "1":
    celsius = float(input("Enter temperature in Celsius: "))
    # The formula: multiply by 9/5, then add 32.
    fahrenheit = celsius * 9 / 5 + 32
    print(f"{celsius}\u00b0C is {fahrenheit}\u00b0F")
elif choice == "2":
    fahrenheit = float(input("Enter temperature in Fahrenheit: "))
    # The reverse: subtract 32, then multiply by 5/9.
    celsius = (fahrenheit - 32) * 5 / 9
    print(f"{fahrenheit}\u00b0F is {celsius}\u00b0C")
else:
    print("Please choose 1 or 2.")
What each part does — in plain words
print(...) — show the menu so the user knows their two options.

choice = input("Choose 1 or 2: ") — read which direction they want. This comes in as text (“1” or “2”).

if choice == "1": — if they picked Celsius→Fahrenheit, do the first conversion. We compare to the text “1” because input always gives text.

celsius = float(input(...)) — read the temperature and turn it into a decimal number. We use float (not int) because temperatures can have decimals like 36.6.

fahrenheit = celsius * 9 / 5 + 32 — the formula. Python follows normal maths order: multiply and divide first, then add.

elif / elseelif handles the reverse direction; else catches anything that is not 1 or 2 and gently asks again.
Common mistakes — and how to avoid them
✗ Using int() instead of float() — then 36.6 degrees loses its decimal and becomes 36.
✓ Use float() for anything that can have a decimal, like temperature.
✗ Writing the formula as celsius * 9 / 5 + 32 but expecting celsius * (9 / 5 + 32).
✓ Python does × and ÷ before +. The given formula is already correct; do not add brackets around + 32.
✗ Comparing choice == 1 (the number) instead of choice == "1" (the text).
input() gives text, so compare to "1" with quotes.

4 Test & Prove Each Part

How do we know the formulas are right? We test them against temperatures we already know — water freezes at 0°C / 32°F and boils at 100°C / 212°F. If those come out right, the formula is right.

Freezing point: 0°C correctly becomes 32°F
Boiling point: 100°C correctly becomes 212°F
The reverse works: 32°F correctly becomes 0°C
Round-trip: convert there and back, get the original number
Pythontest_converter.py
"""test_converter.py — run: pytest -v"""


def c_to_f(celsius):
    """Convert Celsius to Fahrenheit."""
    return celsius * 9 / 5 + 32


def f_to_c(fahrenheit):
    """Convert Fahrenheit to Celsius."""
    return (fahrenheit - 32) * 5 / 9


def test_freezing_point():
    """0 degrees Celsius is 32 degrees Fahrenheit."""
    assert c_to_f(0) == 32


def test_boiling_point():
    """100 degrees Celsius is 212 degrees Fahrenheit."""
    assert c_to_f(100) == 212


def test_reverse_freezing():
    """32 degrees Fahrenheit is 0 degrees Celsius."""
    assert f_to_c(32) == 0


def test_round_trip():
    """Converting there and back gives the original number."""
    assert round(f_to_c(c_to_f(25)), 5) == 25

Run with pytest -v. We pulled the formulas into small functions (c_to_f, f_to_c) so the tests can check them directly. Testing against known facts — freezing and boiling points — is a powerful way to trust your maths.

5 The Interface

The program’s interface — what it asks for and what it gives back — documented plainly.

INPUTchoice + temperature1 or 2, then a number
What it expects
Choose 1 or 2: 1
Enter temperature in Celsius: 25
OUTPUTconverted temperaturethe result with units
What it returns
25.0°C is 77.0°F

6 Run It & Automate It

Save as converter.py and run it.

Run it locally
python3 converter.py
Pick a direction, type a temperature, and see the conversion.

A CI tool like Jenkins runs the tests automatically whenever the code changes — every line below has a plain explanation.

What you should see when it works
Terminala real run
Temperature Converter
1. Celsius to Fahrenheit
2. Fahrenheit to Celsius
Choose 1 or 2: 1
Enter temperature in Celsius: 100
100.0°C is 212.0°F
If it breaks — how to fix it
🚨 ValueError: could not convert string to float
You typed something that is not a number (or left it blank). Type digits like 25 or 36.6.
🚨 It always prints “Please choose 1 or 2” even when I type 1.
You may have extra spaces, or compared to the number 1 instead of the text "1". Check the quotes.
GroovyJenkinsfile
// Jenkinsfile — runs the tests automatically on every change.
pipeline {
    agent any                                  // run on any available machine
    stages {
        stage('Get the code') {
            steps { checkout scm }             // download the latest code
        }
        stage('Install tools') {
            steps {
                sh 'python3 -m venv venv'                       // clean workspace
                sh '. venv/bin/activate && pip install pytest'  // the test tool
            }
        }
        stage('Run the tests') {
            steps { sh '. venv/bin/activate && pytest -v' }     // check every rule
        }
    }
    post {
        success { echo 'All conversions correct.' }
        failure { echo 'A conversion is wrong — look above.' }
    }
}
🎯 Try this next — make it yours

You have a working converter. Extend it:

  1. Add Kelvin. Offer Celsius→Kelvin too (Kelvin = Celsius + 273.15). (Teaches: more branches.)
  2. Round the answer. Show 77.0°F as a tidy number with round(value, 1). (Teaches: formatting output.)
  3. Keep converting. Loop so the user can do many conversions without restarting. (Teaches: a while loop.)
  4. Guard bad input. If they type “hot”, say “please type a number” instead of crashing. (Teaches: try/except.)
What you learned
You learned the ask → calculate → show pattern behind every converter and calculator, plus float for decimals, if/elif/else for choices, and how to test maths against known facts. Related reference: Variables & Types, Control Flow.