Python Coding Exercise #21: Grams to Kilograms
Part of the series Python Practice Exercise — part 21
Before you start: Know input() and int() · Know the / and % operators · Know if, elif and else
The question
Write a program that enters mass in grams and displays it in grams and kilograms.
In other words, the user types a mass in grams, and the program shows it as whole kilograms plus the grams left over. There are 1000 grams in a kilogram, so for example:
Weight in grams: 2500
2 kilograms and 500 grams
Weight in grams: 3000
3 kilograms
Weight in grams: 750
750 grams
I solved this in two steps: first a beginner-friendly version that gets the maths right, and then a final version that fixes the small problems in how the answer reads.
My First Solution (Beginner-Friendly)
weight = int(input("Weight in grams: "))
weight_in_kg = int(weight / 1000)
remaining_weight = weight % 1000
if remaining_weight == 0:
print(f"{weight_in_kg} kilograms")
else:
print(f"{weight_in_kg} kilograms and {remaining_weight} grams")
How it works
1. Read the mass as a whole number. int(input("Weight in grams: ")) asks for the mass and converts the typed text to an integer. (input() always returns text, so the conversion is needed before any maths. See Exercise #08.)
2. Work out the whole kilograms. Dividing by 1000 turns grams into kilograms. For 2500 grams, 2500 / 1000 is 2.5. The / operator always gives a float, even when both numbers are integers. We only want the whole kilograms, so int() cuts off the decimal part and leaves 2. (int() truncates, it doesn’t round: int(2.9) is 2.)
3. Work out the leftover grams. The % operator gives the remainder after a division. After taking the 2 whole kilograms (2000 grams) out of 2500 grams, there are 2500 % 1000 = 500 grams left over. This line needs no int(): because weight is a whole number, the remainder is a whole number too.
4. Choose what to print. If nothing is left over (remaining_weight == 0), the mass is an exact number of kilograms, so only the kilograms are printed. Otherwise, the else branch prints both parts.
The issues
This program does the calculation correctly, but some of its answers read badly:
| Input | Output of my first solution | What’s wrong |
|---|---|---|
| 750 | 0 kilograms and 750 grams | The 0 kilograms isn’t needed |
| 1000 | 1 kilograms | It should be 1 kilogram |
| 1001 | 1 kilograms and 1 grams | Both words should be singular |
| 1 | 0 kilograms and 1 grams | It should be just 1 gram |
| 0 | 0 kilograms | 0 grams is more natural for no mass at all |
There are two kinds of problem here: singular and plural (1 kilograms), and a part that should be left out (0 kilograms and ...). My final solution fixes both.
My Final Solution
weight = int(input("Weight in grams: "))
weight_in_kg = int(weight / 1000)
remaining_weight = weight % 1000
kg_word = "kilogram" if weight_in_kg == 1 else "kilograms"
g_word = "gram" if remaining_weight == 1 else "grams"
if weight_in_kg == 0:
print(f"{remaining_weight} {g_word}")
elif remaining_weight == 0:
print(f"{weight_in_kg} {kg_word}")
else:
print(f"{weight_in_kg} {kg_word} and {remaining_weight} {g_word}")
The calculation in the first three lines is unchanged. Everything new is about how the answer is worded.
How My Final Solution Works
1. Choose the right word first
kg_word = "kilogram" if weight_in_kg == 1 else "kilograms"
g_word = "gram" if remaining_weight == 1 else "grams"
Each line picks the correct word before printing. "kilogram" if weight_in_kg == 1 else "kilograms" reads as “use kilogram when the number is exactly 1, otherwise use kilograms”. It’s a one-line if / else, and it does the same job as this longer form:
if weight_in_kg == 1:
kg_word = "kilogram"
else:
kg_word = "kilograms"
Use whichever you find easier to read. The word is then slotted into the f-string with {kg_word} and {g_word}, instead of being typed in directly.
2. Three cases instead of two
My first solution had two cases. The final one has three, each with its own print():
| Condition | Meaning | What is printed |
|---|---|---|
weight_in_kg == 0 | less than a kilogram | only the grams |
remaining_weight == 0 | an exact number of kilograms | only the kilograms |
| otherwise | kilograms and some grams | both parts |
Notice that a zero part is now simply never printed.
Here is how five inputs move through the program:
| Input | weight_in_kg | remaining_weight | Branch | Printed |
|---|---|---|---|---|
| 750 | 0 | 750 | if | 750 grams |
| 1000 | 1 | 0 | elif | 1 kilogram |
| 1001 | 1 | 1 | else | 1 kilogram and 1 gram |
| 2500 | 2 | 500 | else | 2 kilograms and 500 grams |
| 3000 | 3 | 0 | elif | 3 kilograms |
3. The order of the checks matters
Python checks the if, elif and else branches from top to bottom and runs the first one that matches. That makes the order important. For an input of 0, both weight_in_kg == 0 and remaining_weight == 0 are true. Because the weight_in_kg == 0 check comes first, the program prints 0 grams. If the two checks were swapped, the remaining_weight == 0 branch would match first and print 0 kilograms. Exercise #36 explores the same idea with age groups.
Key takeaways
- To convert units, divide by the conversion factor. There are 1000 grams in a kilogram.
/always returns a float, andint()cuts off the decimal part, which is how you get whole kilograms.%gives what’s left over after the division. With a whole-number input, it needs noint().- A calculation can be right while the wording is wrong. Check outputs like
1 kilogramsand0 kilograms and 750 grams. "word" if condition else "other"is a compact way to choose between two values, such as a singular and a plural word.- Branches are checked from the top, and the first match wins, so the order of
ifandelifcan change the result. - Leave a part out entirely when it would be zero, instead of printing it.
✦ This is part of my Python Practice Exercise series, where I work through exercises while learning Python and explain each answer in plain language. ✦
Practice Source: This exercise is taken from Ultimate Python Programming: Learn Python with 650+ Programs, 900+ Practice Questions, and 5 Projects by Deepali Srivastava, published by BPB Publications. I’m working through the exercises as part of my Python learning journey and documenting my answers and explanations here.