Programming Fundamentals/Condition Examples Python
Appearance
Temperature
[edit | edit source]# 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 get_temperature(label):
print(f"Enter {label} 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, from_label, result, to_label):
print(f"{temperature}° {from_label} is {result}° {to_label}")
def main():
choice = get_choice()
if choice == "C" or choice == "c":
temperature = get_temperature("Fahrenheit")
result = calculate_celsius(temperature)
display_result (temperature, "Fahrenheit", result, "Celsius")
elif choice == "F" or choice == "f":
temperature = get_temperature("Celsius")
result = calculate_fahrenheit(temperature)
display_result (temperature, "Celsius", result, "Fahrenheit")
else:
print("You must enter C to convert to Celsius or F to convert to Fahrenheit.")
main()
Output
[edit | edit source]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.