Programming Fundamentals/Conditions/Python3
Appearance
(Redirected from Computer Programming/Conditions/Python3)
conditions.py
[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()
Try It
[edit | edit source]Copy and paste the code above into one of the following free online development environments or use your own Python3 compiler / interpreter / IDE.
- GDB Online
- Ideone
- InterviewBit
- paiza.IO
- Programiz
- PythonTutor
- Python Fiddle
- repl.it
- RexTester
- Trinket
- TutorialsPoint
- Python Online
- Python Playground
- LabEx
- Python-Fiddle
- Python Sandbox