In this exercise, you'll build a temperature conversion program using functions.
Write these three functions:
def celsius_to_fahrenheit(c):
# Convert Celsius to Fahrenheit
# Formula: (C × 9/5) + 32
# Return the result
def fahrenheit_to_celsius(f):
# Convert Fahrenheit to Celsius
# Formula: (F - 32) × 5/9
# Return the result
def celsius_to_kelvin(c):
# Convert Celsius to Kelvin
# Formula: C + 273.15
# Return the result
Test your functions:
print(celsius_to_fahrenheit(0)) # Should print 32.0
print(fahrenheit_to_celsius(32)) # Should print 0.0
print(celsius_to_kelvin(0)) # Should print 273.15
fahrenheit_to_kelvin
¶For this part, I'd like you to write a fahrenheit_to_kelvin
function. HOWEVER, you should not do any math in this function. Write this function only using the functions you have already defined.
def fahrenheit_to_kelvin(f):
# Convert Fahrenheit to Celsius
# Don't do math here, use the other functions
# Return the result
print(fahrenheit_to_kelvin(32)) # Should print 273.15
Write a function that gets a valid temperature from the user:
def get_temperature():
# Ask user for a temperature
# Make sure you convert the input to a float
# A valid temperature must be:
# - Greater than 0 Kelvin (theoretical limit)
# - Less 1127 Celsius (tempurature of a volcano)
# Keep asking (in a loop) until it's a valid number
# Return the temperature as a float
Write a function that shows a menu and gets the user's choice:
def get_menu_choice():
# Display menu:
# 1. Celsius to Fahrenheit
# 2. Fahrenheit to Celsius
# 3. Celsius to Kelvin
# 4. Quit
# Get user's choice and return it as a string
Write a main function that uses all your other functions:
def main():
# Show welcome message
# Loop until user chooses to quit:
# - Get menu choice
# - If quit, break
# - Get temperature from user
# - Call appropriate conversion function
# - Display the result
# Show goodbye message
# Run the program
main()
Welcome to Temperature Converter!
1. Celsius to Fahrenheit
2. Fahrenheit to Celsius
3. Celsius to Kelvin
4. Quit
Choose (1-4): 1
Enter temperature: 100
100.0 C = 212.0 F
1. Celsius to Fahrenheit
2. Fahrenheit to Celsius
3. Celsius to Kelvin
4. Quit
Choose (1-4): 4
Goodbye!
Add a function is_water_boiling(temp, unit)
that returns True
if the temperature would boil water (100°C, 212°F, or 373.15K)
Add a function describe_weather(temp_celsius)
that returns a string describing the weather:
Let the user enter the input unit ("C"
, "F"
, or "K"
), the amount, and then the output unit as three separate inputs.
def celsius_to_fahrenheit(c):
# Convert Celsius to Fahrenheit
# Formula: (C × 9/5) + 32
# Return the result
def fahrenheit_to_celsius(f):
# Convert Fahrenheit to Celsius
# Formula: (F - 32) × 5/9
# Return the result
def celsius_to_kelvin(c):
# Convert Celsius to Kelvin
# Formula: C + 273.15
# Return the result
print(celsius_to_fahrenheit(0))
print(fahrenheit_to_celsius(32))
print(celsius_to_kelvin(0))