Skip to Main Content
Blog

Convert Temperature Among Various Scales in Python

Convert Temperature Among Various Scales in Python

Write a Java program that asks the user to enter a source temperature unit and a corresponding temperature value, then converts and displays the equivalent temperatures in all three units.

Get Temperature Conversion Formulas using Copilot

Get Temperature Conversion Formulas using Gemini

Output

# Example 1
Enter source temperature units (F/C/K): F
Enter temperature in Fahrenheit: 98.6
37.0000°C = 98.6000°F = 310.1500K

# Example 2
Enter source temperature units (F/C/K): C
Enter temperature in Celsius: 180.50
180.5000°C = 356.9000°F = 453.6500K

# Example 3
Enter source temperature units (F/C/K): K
Enter temperature in Kelvin: 277.15
4.0000°C = 39.2000°F = 277.1500K

Solution

def main():
	# Read the source temperature unit from the user
	input_unit = input("Enter source temperature units (F/C/K): ").strip()
	unit = input_unit[0].lower() if input_unit else "\0"

	# Initialize variables
	c = f = k = 0.0

	# Convert input temperature based on chosen unit
	if unit == "f":
		f = float(input("Enter temperature in Fahrenheit: "))
		c = (f - 32) * 5 / 9
		k = c + 273.15
	elif unit == "c":
		c = float(input("Enter temperature in Celsius: "))
		f = c * 9 / 5 + 32
		k = c + 273.15
	elif unit == "k":
		k = float(input("Enter temperature in Kelvin: "))
		c = k - 273.15
		f = c * 9 / 5 + 32
	else:
		print("Invalid choice! Please enter F, C, or K.")
		return

	# Print all equivalent temperature values up to 4 decimal places
	print(f"{c:.4f}°C = {f:.4f}°F = {k:.4f}K")


if __name__ == "__main__":
	main()