Generate a code to convert Celsius to Fahrenheit in Python
- User
Generate a code to convert Celsius to Fahrenheit in Python
Assistant
Generate a code to convert Celsius to Fahrenheit in Python
Core Formula: Fahrenheit = (Celsius × 9/5) + 32, or equivalently F = C × 1.8 + 32
Design Considerations:
Architectural Decision: I'll build a modular solution with:
Edge Cases to Handle:
| Decision | Rationale |
|---|---|
| Modular Design | Separate core logic from I/O for reusability and testability |
| Type Hints | Improves code clarity and enables IDE support |
| Input Validation | Prevents crashes on invalid input with descriptive errors |
| CLI + Function | Dual interface: import as module OR run as standalone script |
| List Support | Batch conversion capability for multiple temperatures |
| Precision Parameter | Optional rounding for cleaner output |
"""
Celsius to Fahrenheit Converter Module
A robust temperature conversion utility supporting:
- Single value conversion
- Batch conversion (lists)
- CLI interface
- Input validation
"""
from typing import Union, List
import sys
def celsius_to_fahrenheit(
celsius: Union[int, float],
precision: int = 2
) -> float:
"""
Convert temperature from Celsius to Fahrenheit.
Formula: F = (C × 9/5) + 32
Args:
celsius: Temperature in Celsius (int or float)
precision: Decimal places for rounding (default: 2)
Returns:
Temperature in Fahrenheit as a float
Raises:
TypeError: If input is not a number
ValueError: If temperature is below absolute zero (-273.15°C)
Examples:
>>> celsius_to_fahrenheit(0)
32.0
>>> celsius_to_fahrenheit(100)
212.0
>>> celsius_to_fahrenheit(-40)
-40.0
"""
# Input validation
if not isinstance(celsius, (int, float)):
raise TypeError(
f"Expected int or float, got {type(celsius).__name__}"
)
# Physical validation (absolute zero check)
ABSOLUTE_ZERO_C = -273.15
if celsius < ABSOLUTE_ZERO_C:
raise ValueError(
f"Temperature cannot be below absolute zero ({ABSOLUTE_ZERO_C}°C)"
)
# Conversion formula
fahrenheit = (celsius * 9/5) + 32
return round(fahrenheit, precision)
def batch_convert(
celsius_values: List[Union[int, float]],
precision: int = 2
) -> List[float]:
"""
Convert a list of Celsius temperatures to Fahrenheit.
Args:
celsius_values: List of temperatures in Celsius
precision: Decimal places for rounding
Returns:
List of temperatures in Fahrenheit
Example:
>>> batch_convert([0, 25, 100])
[32.0, 77.0, 212.0]
"""
return [
celsius_to_fahrenheit(temp, precision)
for temp in celsius_values
]
def main():
"""CLI interface for interactive temperature conversion."""
print("=" * 45)
print(" CELSIUS TO FAHRENHEIT CONVERTER")
print("=" * 45)
print("Enter 'q' to quit, 'batch' for multiple values\n")
while True:
try:
user_input = input("Enter temperature in °C: ").strip()
# Exit commands
if user_input.lower() in ('q', 'quit', 'exit'):
print("\nGoodbye!")
break
# Batch mode
if user_input.lower() == 'batch':
values = input("Enter temps (comma-separated): ")
temps = [float(v.strip()) for v in values.split(',')]
results = batch_convert(temps)
for c, f in zip(temps, results):
print(f" {c}°C → {f}°F")
continue
# Single conversion
celsius = float(user_input)
fahrenheit = celsius_to_fahrenheit(celsius)
print(f" ─────────────────────────")
print(f" {celsius}°C = {fahrenheit}°F")
print(f" ─────────────────────────\n")
except ValueError as e:
print(f" ⚠ Error: {e}\n")
except TypeError as e:
print(f" ⚠ Error: {e}\n")
if __name__ == "__main__":
main()
from temperature_converter import celsius_to_fahrenheit, batch_convert
# Single conversion
temp_f = celsius_to_fahrenheit(25) # Returns: 77.0
# With custom precision
temp_f = celsius_to_fahrenheit(37.777, precision=1) # Returns: 100.0
# Batch conversion
temps_f = batch_convert([0, 25, 37, 100]) # Returns: [32.0, 77.0, 98.6, 212.0]
$ python temperature_converter.py
=============================================
CELSIUS TO FAHRENHEIT CONVERTER
=============================================
Enter 'q' to quit, 'batch' for multiple values
Enter temperature in °C: 100
─────────────────────────
100.0°C = 212.0°F
─────────────────────────
Enter temperature in °C: q
Goodbye!
| Feature | Implementation |
|---|---|
| ✅ Core Formula | F = (C × 9/5) + 32 |
| ✅ Type Safety | Type hints with Union[int, float] |
| ✅ Input Validation | TypeError for non-numbers |
| ✅ Physical Validation | ValueError below absolute zero |
| ✅ Precision Control | Configurable rounding |
| ✅ Batch Processing | batch_convert() function |
| ✅ CLI Interface | Interactive prompt with loop |
| ✅ Documentation | Full docstrings with examples |