A weight converter is simply used to convert between different units of mass such as: kilogram (kg), stones (st), grams (g), pounds (lbs) etc.
In this shot, we are going to create a weight converter to help us convert and determine the weight of a user be it in kilogram (kg) or in pounds (lbs).
The relationship between kilograms and pounds is given as:
1 kg = 2.205 lbs
This simply means that for every value given in kilogram that we want to convert to pounds, we simply multiply the number by 2.205. Also for any value of pounds we want to convert to kilogram, we simply divide the number by 2.205.
If a user weighs 70kg and wants to know the equivalence in pounds (lbs):
70kg is converted to pounds as: 70 × 2.205 = 154.35 lb
It is as simple as that!
Now let’s write a program that dynamically converts a unit in kilogram to pounds and vice-versa.
try:
weight = int(input('What is your weight? '))
unit = input('In (kg) or (lb)? ')
if unit.lower() == "kg":
conversion = weight * 2.205
print(f'Your weight in pounds is {conversion}lb')
else:
conversion = weight // 2.205
print(f'your weight in kilograms is {conversion}kg')
except ValueError:
print('Sorry you made an invalid input')
What is your weight? 95
In (kg) or (lb)? KG
Your weight in pounds is 209.475lb
What is your weight? 209
In (kg) or (lb)? lb
Your weight in kilograms is 94.0kg
What is your weight? kg
Sorry you made an invalid input
try
and except
block to handle any ValueError
.weight
where the user gives an input of their weight.unit
where we ask the user to input the unit of the weight (whether kg or lb) they inputted in line 2.if
statement, we state a condition that if the user gave a value equal to kg, and also in any letter case not minding, the return value should continue in line 4.conversion
to help compute the conversion and proceed with the condition given in line 4.else
statement, we state a second condition that if the user gave another input other than that in line 4, the return value should continue in line 8.conversion
to help compute and proceed with the condition given in line 10.try
and except
block which helps to check for any ValueError
.ValueError
.