SciPy Tutorial menu

SciPy Constants

The constants module gives you scientific values and unit conversions, so you never have to type them by hand.

Why Use Constants?

Typing 3.14 or 9.8 yourself is easy, but it can introduce small errors. scipy.constants stores exact, internationally agreed values.

Maths and Physics Constants

Example

python
from scipy import constants

print(constants.pi)
print(constants.golden)
print(constants.speed_of_light)
print(constants.g)
Output
3.141592653589793
1.618033988749895
299792458.0
9.80665
NameMeaningUnit
piRatio of a circle's circumference to its diameternone
goldenThe golden rationone
speed_of_light (or c)Speed of light in vacuummetres per second
gStandard gravity on Earthmetres per second squared
AvogadroParticles in one moleper mole

Seeing All Constants

Example

python
from scipy import constants
names = [n for n in dir(constants) if not n.startswith("_")]
print(len(names) > 100)
Output
True

There are well over a hundred names in the module.

Unit Conversion

The units are stored as their value in the SI base unit: metres for length, kilograms for mass, seconds for time. To convert to SI, multiply. To convert from SI, divide.

Example

python
from scipy import constants

print(constants.kilo)      # 1000
print(constants.minute)    # seconds in a minute
print(constants.hour)      # seconds in an hour
print(constants.inch)      # metres in an inch
print(constants.mile)      # metres in a mile
Output
1000.0
60.0
3600.0
0.0254
1609.3439999999998

The last value has a tiny rounding detail at the end. This is normal for decimal numbers on computers.

A Practical Conversion

A cricket pitch is 22 yards long. How many metres is that? And how many minutes are in 2.5 hours?

Example

python
from scipy import constants

pitch_m = 22 * constants.yard
print(round(pitch_m, 2))

minutes = 2.5 * constants.hour / constants.minute
print(minutes)
Output
20.12
150.0

Mass and Weight

Example

python
from scipy import constants

flour_lb = 10
flour_kg = flour_lb * constants.pound
print(round(flour_kg, 2))
Output
4.54

Temperature

Temperature is different because the scales do not start at zero together. Use convert_temperature():

Example

python
from scipy.constants import convert_temperature

print(convert_temperature(40, "Celsius", "Fahrenheit"))
print(convert_temperature(98.6, "Fahrenheit", "Celsius"))
print(convert_temperature(0, "Celsius", "Kelvin"))
Output
104.0
37.0
273.15

Karachi's 40 degree summer day is 104 degrees Fahrenheit.

You can shorten the scale names: "C", "F" and "K" also work.

Exercise

Exercise

How do you convert 5 inches to metres with scipy.constants?

Learn SciPy with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp