10.5: Python Examples
selected template will load here
This action is not available.
# This program asks the user to select Fahrenheit or Celsius conversion # and input a given temperature. Then the program converts the given # temperature and displays the result. # # References: # https://www.mathsisfun.com/temperature-conversion.html # https://en.wikibooks.org/wiki/Python_Programming def get_choice(): print("Enter C to convert to Celsius or F to convert to Fahrenheit:") choice = input() return choice def process_celsius(): temperature = get_temperature("Fahrenheit") result = calculate_celsius(temperature) display_result (temperature, "Fahrenheit", result, "Celsius") def process_fahrenheit(): temperature = get_temperature("Celsius") result = calculate_fahrenheit(temperature) display_result (temperature, "Celsius", result, "Fahrenheit") def get_temperature(scale): print("Enter " + scale + " temperature:") temperature = float(input()) return temperature def calculate_celsius(fahrenheit): celsius = (fahrenheit - 32) * 5 / 9 return celsius def calculate_fahrenheit(celsius): fahrenheit = celsius * 9 / 5 + 32 return fahrenheit def display_result(temperature, fromScale, result, toScale): print(str(temperature) + str("° ") + fromScale + " is " + str(result) + "° " + toScale) def main(): choice = get_choice() if choice == "C" or choice == "c": process_celsius () elif choice == "F" or choice == "f": process_fahrenheit () else: print("You must enter C to convert to Celsius or F to convert to Fahrenheit.") main()
Enter C to convert to Celsius or F to convert to Fahrenheit: c Enter Fahrenheit temperature: 100 100.0° Fahrenheit is 37.77777777777778° Celsius Enter C to convert to Celsius or F to convert to Fahrenheit: f Enter Celsius temperature: 100 100.0° Celsius is 212.0° Fahrenheit Enter C to convert to Celsius or F to convert to Fahrenheit: x You must enter C to convert to Celsius or F to convert to Fahrenheit.