Python Program to Print a Temperature Conversion Table
Beginner · Basics
This program prints a table of temperatures in Celsius next to the same temperatures in Fahrenheit, from 0 to 100 degrees in steps of 10. The formula is F = C x 9/5 + 32, so water freezes at 32 F and boils at 212 F.
Program
temperature_table.py
start = 0 # or: start = int(input("Start (Celsius): "))
end = 100 # or: end = int(input("End (Celsius): "))
step = 10
print("Celsius Fahrenheit")
print("------- ----------")
for celsius in range(start, end + 1, step):
fahrenheit = celsius * 9 / 5 + 32
print(f"{celsius:>7} {fahrenheit:>10.1f}")
Output
Celsius Fahrenheit
------- ----------
0 32.0
10 50.0
20 68.0
30 86.0
40 104.0
50 122.0
60 140.0
70 158.0
80 176.0
90 194.0
100 212.0How it works
range(start, end + 1, step)gives 0, 10, 20 and so on up to 100, with+ 1so the end value is included.- Each Celsius value is converted with
celsius * 9 / 5 + 32. - In the f-string,
:>7right-aligns a value in a space 7 characters wide, so the numbers line up under their headings. .1fshows the Fahrenheit value with one decimal place, which matters for steps that do not give whole numbers, such as 5 degrees.
Other ways to write it
Fahrenheit to Celsius with a while loop
Fahrenheit to Celsius with a while loop
fahrenheit = 32
print("Fahrenheit Celsius")
while fahrenheit <= 212:
celsius = (fahrenheit - 32) * 5 / 9
print(f"{fahrenheit:>10} {celsius:>7.1f}")
fahrenheit += 20
Output
Fahrenheit Celsius
32 0.0
52 11.1
72 22.2
92 33.3
112 44.4
132 55.6
152 66.7
172 77.8
192 88.9
212 100.0The while loop adds 20 each time until it passes 212, and the formula is turned around to C = (F - 32) x 5/9.
Adding a Kelvin column
Adding a Kelvin column
def to_fahrenheit(c):
return c * 9 / 5 + 32
print(" C F K")
for c in range(-40, 41, 20):
print(f"{c:>6} {to_fahrenheit(c):>7.1f} {c + 273.15:>8.2f}")
Output
C F K
-40 -40.0 233.15
-20 -4.0 253.15
0 32.0 273.15
20 68.0 293.15
40 104.0 313.15At -40 degrees the Celsius and Fahrenheit scales meet, and Kelvin is simply Celsius plus 273.15.
Try it yourself
Change the table to run from -20 to 50 degrees Celsius in steps of 5.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises