In this source code example, we will write a program in Python that converts temperature between Celsius and Fahrenheit.
Python Temperature Converter
Here is a program in Python that converts temperature between Celsius and Fahrenheit, with explanations:
def temperature_converter():
while True:
print("\nOptions:")
print("Enter 'C' to convert from Celsius to Fahrenheit")
print("Enter 'F' to convert from Fahrenheit to Celsius")
print("Enter 'quit' to end the program\n")
user_input = input(": ")
if user_input == "quit":
break
elif user_input == "C":
celsius = float(input("Enter the temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
print("The temperature in Fahrenheit is:", fahrenheit)
elif user_input == "F":
fahrenheit = float(input("Enter the temperature in Fahrenheit: "))
celsius = (fahrenheit - 32) * 5/9
print("The temperature in Celsius is:", celsius)
else:
print("Unknown input")
temperature_converter()
Output:
Options:
Enter 'C' to convert from Celsius to Fahrenheit
Enter 'F' to convert from Fahrenheit to Celsius
Enter 'quit' to end the program
: C
Enter the temperature in Celsius: 90
The temperature in Fahrenheit is: 194.0
Options:
Enter 'C' to convert from Celsius to Fahrenheit
Enter 'F' to convert from Fahrenheit to Celsius
Enter 'quit' to end the program
: F
Enter the temperature in Fahrenheit: 35
The temperature in Celsius is: 1.6666666666666667
Options:
Enter 'C' to convert from Celsius to Fahrenheit
Enter 'F' to convert from Fahrenheit to Celsius
Enter 'quit' to end the program
: quit
Explanation:
- The while loop is used to keep the program running until the user chooses to quit.
- The user is presented with options to convert either from Celsius to Fahrenheit or from Fahrenheit to Celsius.
- If the user inputs "C", the program prompts the user to enter the temperature in Celsius and converts it to Fahrenheit.
- If the user inputs "F", the program prompts the user to enter the temperature in Fahrenheit and converts it to Celsius.
- If the user inputs an unknown option, the program displays an error message.
- The
temperature_converter
a function is called to start the program.
Comments
Post a Comment