But we could break down this program further, thinking about the underlying steps:
Get user input for Fahrenheit temperature
Convert to celsius
Show output
We could create modular pieces for each of these tasks.
# function for getting input
def getFahrenheit():
fahrenheit = float(input("Enter a temperature in Fahrenheit: "))
return fahrenheit# function for converting to Celsius
def convertTemp(fahrenheit):
celsius = (fahrenheit -32) * 5/9
return celsius# function for returning output
def result(fahrenheit, celsius):
print(f"{fahrenheit} degrees Fahrenheit is equal to {celsius} degrees celsius")And we could create a combined function from each of those three individual functions.
# combined function
def combined():
fahrenheit = getFahrenheit()
celsius = convertTemp(fahrenheit)
result(fahrenheit, celsius)To run our entire temperature conversion program, we would just need to call the combined() function using its name.
# combined temperature conversion program function call
combined()Putting It All Together¶
To summarize, we created a function for each piece of our conversion program (getFahrenheit, convertTemp, result), and then created a main function that combined those three steps.
# function for getting input
def getFahrenheit():
fahrenheit = float(input("Enter a temperature in Fahrenheit: "))
return fahrenheit
# function for converting to Celsius
def convertTemp(fahrenheit):
celsius = (fahrenheit -32) * 5/9
return celsius
# function for returning output
def result(fahrenheit, celsius):
print(f"{fahrenheit} degrees Fahrenheit is equal to {celsius} degrees celsius")
# combined function
def combined():
fahrenheit = getFahrenheit()
celsius = convertTemp(fahrenheit)
result(fahrenheit, celsius)
# combined temperature conversion program function call
combined()