Building a Temperature Converter in Python
One of the best ways to learn programming fundamentals is by building practical, small projects. In this tutorial, we'll create a Temperature Converter in Python that converts between Celsius and Fahrenheit.
What You'll Learn
- Functions and parameters
- User input validation
- Conditional logic
- Error handling
- Basic Python syntax
The Code
Here's the complete temperature converter:
python
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758def celcius_to_fahrenheit(celcius): """Convert Celcius to Fahrenheit""" return (celcius * 9/5) + 32def fahrenheit_to_celcius(fahrenheit): """Convert Fahrenheit to Celcius""" return (fahrenheit - 32) * 5/9def get_temperature_input(): """Get and validate temperature from user""" while True: try: temp = float(input("Enter temperature value: ")) return temp except ValueError: print("Invalid! Please enter a number (e.g., 25 or 77.5)")def get_conversion_choice(): """Get conversion type from user""" print("\nChoose conversion type:") print("1. Celcius -> Fahrenheit") print("2. Fahrenheit -> Celcius") while True: choice = input("\nEnter choice (1 or 2): ") if choice == '1': return 'celcius_to_fahrenheit' elif choice == '2': return 'fahrenheit_to_celcius' else: print("Invalid! Please enter 1 or 2")def main(): """Main program function""" print("=" * 50) print("TEMPERATURE CONVERTER") print("=" * 50) # Get user's conversion choice conversion_type = get_conversion_choice() # Get temperature value temperature = get_temperature_input() # Perform conversion if conversion_type == 'celcius_to_fahrenheit': result = celcius_to_fahrenheit(temperature) print(f"\n{temperature}°C = {result:.2f}°F") else: result = fahrenheit_to_celcius(temperature) print(f"\n{temperature}°F = {result:.2f}°C") print("=" * 50)# Run the programif __name__ == "__main__": main()How It Works
1.Conversion Functions
We define two functions for the conversions:
- celcius_to_fahrenheit(celcius): Uses the formula (C × 9/5) + 32
- fahrenheit_to_celcius(fahrenheit): Uses the formula (F - 32) × 5/9
2.Input Validation
The get_temperature_input() function ensures the user enters a valid number:
python
123456while True: try: temp = float(input("Enter temperature value: ")) return temp except ValueError: print("Invalid! Please enter a number")This uses a try-except block to catch invalid inputs and keep asking until valid data is provided.
3.User Choice
The get_conversion_choice() function presents a menu and validates the selection:
python
123print("Choose conversion type:")print("1. Celcius -> Fahrenheit")print("2. Fahrenheit -> Celcius")4.Main Function
The main() function orchestrates everything:
1.Displays welcome message
2.Gets conversion type from user
3.Gets temperature value
4.Performs the conversion
5.Shows the result
Example Output
text
12345678910111213==================================================TEMPERATURE CONVERTER==================================================Choose conversion type:1. Celcius -> Fahrenheit2. Fahrenheit -> CelciusEnter choice (1 or 2): 1Enter temperature value: 2525°C = 77.00°F==================================================Challenge Extensions
Once you understand this code, try adding:
- Loop the program - Ask if user wants to convert another temperature
- Add Kelvin - Support 3-way conversion (C ↔ F ↔ K)
- Validate ranges - Reject temperatures below absolute zero
- Add history - Track previous conversions
Key Takeaways
- Functions make code reusable and organized
- Always validate user input
- Use try-except for error handling
- Break programs into small, focused functions
- Test with different inputs
Next Steps
Now that you've built a temperature converter, try these projects:
- Calculator with multiple operations
- Number guessing game
- Simple text-based adventure
- To-do list manager