Skip to content
← Back to Community
Python unit conversions (pint module)
Profile icon

I posted this as the current weekly challenge is related to unit conversions, and there's one day left to enter, this might help some last minute submissions.

STEP 1 (Initialization)

First of all, we need to use the import statement to import the python pint module:
import pint

Then we need to use the following statement, to "allow" our program to access the pint database.
To do this, we type up the following:

STEP 2 (Assigning a variable to a unit value)

Let's create a variable called mylen.
For example, to assign a distance such as 8 km variable to mylen, we type up the following statement:


In this case, we are assigning mylen to 8* 8 is the "amount" or "quantity" of our length. .km indicates to python that we are trying assign the number 8 to the unit km. You can research all the valid units available in the pint unit registry

STEP 3 (Conversion)

Ok, so now we have assigned mylen to "8 km" (refer above).
We need to convert this to another unit in the length category, say "cm". To do this, we use the .to() function. This takes a variable, and converts it to the unit parameter entered. For example, to convert mylen to "cm", we would have to assign the converted value to a variable as well. In this case, we will call ours dest. To convert mylen to "cm" and assign the result to dest, we would type up the following:

This is assigning the variable dest to the result of mylen when converted. the .to() function is taking the parameter. Because we wished to convert mylen to "cm", we typed as the parameter. If we wanted to assign dest to the value when mylen is converted to metres, we would type

You can see that the parameter to the .to() function has changed from to ureg.m because we are changing the unit of the end result. You can change this parameter to any length unit required.
To output dest, type in, you guessed it, print(dest).


Hope this helped at least a few people. To see this code in action, you can click here to see my unit converter, that uses the pint module and the statements shown in this tutorial.
Feedback, upvotes and comments are appreciated :)

Profile icon