Temperature Converter
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
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.
Codedef celsius_to_fahrenheit(c): return c * 9 / 5 + 32 def fahrenheit_to_celsius(f): return (f - 32) * 5 / 9Expected result
celsius_to_fahrenheit(0) returns 32.0; fahrenheit_to_celsius(98.6) returns about 37.0.
- 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.
Codec = float(input("Enter temperature in Celsius: "))Expected result
The script waits for input and stores the numeric value in c.
- 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.
Codef = celsius_to_fahrenheit(c) print(f"{c}°C = {f}°F")Expected result
Typing 25 prints "25.0°C = 77.0°F".
Hint
Round with round(f, 1) if you want fewer decimal places in the output.
- 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.
Codedef 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
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.
Codeimport 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
# TODO: define celsius_to_fahrenheit and fahrenheit_to_celsius
# Then read Celsius input and print the Fahrenheit result
def celsius_to_fahrenheit(c):
return c * 9 / 5 + 32
def fahrenheit_to_celsius(f):
return (f - 32) * 5 / 9
c = float(input("Enter temperature in Celsius: "))
f = celsius_to_fahrenheit(c)
print(f"{c}°C = {f}°F")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
Related Practice
- Functions Concept
Solidify parameters and return values.
- Strings Predict
Predict the output of f-string expressions.
Related Tools
- Temperature Converter
Compare your Python output with a browser-based converter.
Related Cheatsheets
- Python Cheatsheet
Function, input, and f-string syntax reference.
Related Reference
- Python String Methods
Complete string method reference.
Related Errors
- Type Error
Operating on incompatible types.
- Name Error
Using undefined variables.
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.
- Type Error
Operating on incompatible types.
- Name Error
Using undefined variables.