Variables and data types in Python — practice with your average grade, BMI and tuition price (and a few cents that come out of nowhere)

In my first FP1 practice I wrote the classic BMI calculator. I ran it, entered my data and the program told me, very seriously: Your BMI is: 0.0. No error, no warning, nothing. I spent a good while checking the formula until the lecturer leaned over my screen and asked: “what units did you type the height in?”. Centimetres. Python had done the maths perfectly… with a value that didn’t mean what I thought it meant. That’s the lesson of this practice: a program without errors isn’t necessarily a correct program; you need to know the type and the meaning of every value that comes in.

In the variables and data types theory you saw what a variable is, the types int, float, str and bool and how to convert between them. Here we use all of that in three complete programs, all first-week level but with data that looks like real data: grades with decimals, a height that arrives as text (sometimes with a comma or in centimetres) and a price that, split into instalments, invents a few cents. We stick with the example of your student profile: your average grade, your BMI and what your tuition costs.

Before you start

Make sure you’re clear on:

  • That input() always returns a str, and that you convert it with int() or float().
  • The difference between int (counted) and float (measured, or with decimals).
  • That type() tells you the type of any value.
  • That round(x, 2) rounds to two decimals and f"{x:.2f}" writes it with two decimals.

If any of them sounds shaky, review the theory before going on.

In class you’d read the data with input(). Here we write it directly as text (grade1_txt = "7") so the outputs are always the same and you can compare them with yours. It’s exactly what input() would give you if you typed those values. To read them for real, change each line to grade1_txt = input("Grade 1: ") and the rest of the program stays the same. If you don’t have Python yet, start with installing Python on Windows. Create a variables_practice folder in VS Code (here’s how to set it up) and one file per program.

Program 1: Grade average calculator

The program receives your three grades for a subject as text, works out the average, rounds it to two decimals and tells you whether you’ve passed. What makes it tricky isn’t the maths: it’s that the data arrives as str, that a grade can have decimals ("8.5") and that the average of 7, 8.5 and 6 isn’t a “nice” number.

The idea

Four steps, always in this order: convert → calculate → round → decide.

  1. Convert each text to float (not int, because int("8.5") blows up).
  2. Add the three grades and then divide by 3.
  3. Round only the final result, for display.
  4. Store in a bool the answer to “is the average at least 5?”.

Before coding, think about what type each value has at each step. If you know grade1_txt is a str, grade1 is a float and passed is a bool, you’ve already written half the program.

The code

# Program 1 · Grade average calculator
# The grades arrive as TEXT, just as if you had read them with input()
grade1_txt = "7"
grade2_txt = "8.5"
grade3_txt = "6"

# 1) Convert: float and not int, because a grade can have decimals ("8.5")
grade1 = float(grade1_txt)
grade2 = float(grade2_txt)
grade3 = float(grade3_txt)

# 2) Calculate: the brackets make it add EVERYTHING before dividing
average = (grade1 + grade2 + grade3) / 3
print("Unrounded average:", average)

# 3) Round to 2 decimals only at the end, to show the result
rounded_average = round(average, 2)

# 4) A bool stores the answer to "have I passed?"
passed = rounded_average >= 5.0

print(f"Your average grade is: {rounded_average}")
print(f"Passed?: {passed}")
print(type(grade1_txt), type(grade1), type(passed))

Output

Unrounded average: 7.166666666666667
Your average grade is: 7.17
Passed?: True
<class 'str'> <class 'float'> <class 'bool'>

Checking by hand: 7 + 8.5 + 6 = 21.5, and 21.5 / 3 = 7.1666… (the 6 repeats forever). Python keeps the decimals that fit, 7.166666666666667 (the last 7 is internal rounding). round(…, 2) turns it into 7.17, which is ≥ 5, so passed is True. The last line confirms the types: the input was a str, the converted grade is a float and the answer is a bool.

The heart of the program is these three lines:

# 2) Calculate: the brackets make it add EVERYTHING before dividing
average = (grade1 + grade2 + grade3) / 3
print("Unrounded average:", average)

The brackets aren’t decoration. In Python, as in maths, division happens before addition; without brackets, grade1 + grade2 + grade3 / 3 would calculate 7 + 8.5 + 2 = 17.5. The diagram sums up the journey of the data, with the type at each step:

From text to average grade, step by stepThe grades "7", "8.5" and "6" (str) go through float() to 7.0, 8.5 and 6.0; they are added (21.5), divided by 3 (7.166666666666667), rounded to 7.17 and the comparison with 5.0 gives True (bool)."7"7.0"8.5"8.5"6"6.0strfloattextfloat()21.5floatsum7.166666666666667float/ 37.17floatround(…, 2)Truebool>= 5.0
Each step changes the value and sometimes the type: str → float → float → bool (look at the pills).

The same thing the diagram shows, now line by line and with the reason for each row (the line numbers are those of the full program):

LineVariableValueTypeWhy
3-5grade1_txt, grade2_txt, grade3_txt"7", "8.5", "6"strthey’re in quotes: they’re text, just like what input() returns
8grade17.0floatfloat() reads the text "7" and creates a new number; it shows a point because it’s a float
9grade28.5floatthis is where you see why float and not int: the text has decimals
10grade36.0floatthe same as line 8
13average7.166666666666667floatfirst the brackets (21.5) and then / 3, which always gives a float
17rounded_average7.17floatround() creates another number; average stays the same
20passedTruebool7.17 >= 5.0 is a yes-or-no question, and its answer is a bool

No line changes a variable that already existed: each step stores its result in a new one, so you can print any of them and see at which step something went wrong.

Questions you might ask

Why float() and not int()? Because a grade can be "8.5", and int("8.5") gives ValueError. Even if your grades are whole numbers today, the program has to cope with the one that isn’t. float("7") works without a problem and gives 7.0.

Why not round each grade before adding? Because each rounding loses a bit of information, and if you round early, the error builds up. The rule is: calculate with all the decimals and round only what you show.

Does round(average, 2) change average? No. round() creates a new number; average is still 7.166666666666667. That’s why we store the rounded one in another variable, rounded_average.

What’s that f"…{rounded_average}" thing? An f-string: a text with gaps in curly brackets where Python writes the value of the variable. It’s the most comfortable way to mix text and numbers without converting anything by hand.

Why does passed come out as True and not “Yes”? Because it’s a bool, the result of the comparison >= 5.0. If you wanted to write “Yes” or “No”, you’d need an if, which arrives in the conditionals topic.

What would happen if you forgot to convert and calculated (grade1_txt + grade2_txt + grade3_txt) / 3?

The + wouldn’t add: between two str values, + sticks one text after the other. grade1_txt + grade2_txt + grade3_txt gives "78.56", a text that looks like a number but isn’t one. The program would stop at the division with TypeError: unsupported operand type(s) for /: 'str' and 'int', because Python doesn’t know how to divide a text. If you had only added them and shown the result, you’d see 78.56 without any warning. That’s why the conversion comes first, as soon as you receive the data.

Forgetting the brackets in the average. grade1 + grade2 + grade3 / 3 doesn’t give an error: it gives 17.5, a perfectly valid number… and perfectly wrong. Logic errors are the most dangerous because Python doesn’t warn you.

Try it yourself

  • Change grade2_txt to "8,5" (with a comma) and read the error it gives. Then fix it with .replace(",", ".") before converting: float(grade2_txt.replace(",", ".")).
  • Add a fourth grade and notice which two lines you have to touch (the sum and the divisor). What happens if you forget to change the 3 to a 4?

Program 2: BMI calculator

Body mass index is calculated by dividing weight (in kilos) by height (in metres) squared. The program receives your name, weight and height as text and shows your BMI with one decimal. What makes it tricky are the units and the format of the data: a height with a comma or in centimetres breaks the program in two very different ways.

The idea

The name is already text, so it stays as it is. Weight and height are converted to float. Then the formula BMI = weight / height² is applied, rounded to one decimal, and the intermediate steps are shown so you can check them.

Before coding, ask yourself what units each value arrives in and what decimal separator it uses. Those are the two things users will do “their own way”.

The code

# Program 2 · BMI calculator
name = "Sergio"          # str: it's already text, no need to convert it
weight_txt = "70"        # kilos, just as it would arrive from input()
height_txt = "1.78"      # metres, with a decimal POINT

weight = float(weight_txt)
height = float(height_txt)

# BMI = weight / height². ** is the power and is calculated before the division
bmi = weight / height ** 2
rounded_bmi = round(bmi, 1)

print(f"\nResults for {name}:")
print(f"Height squared: {height ** 2}")
print(f"Unrounded BMI: {bmi}")
print(f"Your BMI is: {rounded_bmi}")

Output

Results for Sergio:
Height squared: 3.1684
Unrounded BMI: 22.093170054286073
Your BMI is: 22.1

Checking by hand: 1.78² = 1.78 × 1.78 = 3.1684, and 70 / 3.1684 = 22.093… which with one decimal is 22.1. The \n at the start of the first print is a line break: that’s why the output starts with a blank line.

weight / height ** 2 works without brackets because ** (the power) is calculated before /. If you wrote (weight / height) ** 2, you’d divide first and square afterwards: 39.3… squared, a BMI of over 1,500.

Now, the two mistakes from the opening story. If the height arrives with a comma (height_txt = "1,78"), the program doesn’t even get to the calculation:

Traceback (most recent call last):
  File "bmi_comma.py", line 7, in <module>
    height = float(height_txt)
ValueError: could not convert string to float: '1,78'

And if it arrives in centimetres (height_txt = "178"), the program works… and lies:

Results for Sergio:
Height squared: 31684.0
Unrounded BMI: 0.0022093170054286074
Your BMI is: 0.0

178² = 31,684 and 70 / 31,684 = 0.0022…, which rounded to one decimal is 0.0. That’s my BMI of 0.0 from the opening story: no error, just a value with a different meaning. Notice the difference: the first is an error Python detects (ValueError); the second, one that only you detect by checking whether the result makes sense.

The three heights, side by side:

height_txtfloat(height_txt)height ** 2BMI shownDoes Python warn you?
"1.78"1.783.168422.1no need: everything is correct
"1,78"ValueError(never gets there)(never gets there)yes: it stops at line 7
"178"178.031684.00.0no: the calculation is fine, the value isn’t

The last row is the dangerous one: only you can notice, by asking yourself whether a BMI of 0.0 makes sense.

Questions you might ask

Why isn’t name converted? Because it’s already a str and we want it as text. Only convert what you’re going to calculate with.

Why float for the weight too, if 70 is a whole number? Because someone will weigh 70.5. If the value can have decimals, float.

What does \n do inside the text? It’s a special character, the line break. Inside a string, the backslash \ announces a special character: \n (line break), \t (tab)…

Why doesn’t Python warn me about the centimetres? Because for Python 178 is a perfectly valid number. Types protect you from some errors (you can’t divide a text), but not from units: that’s the programmer’s job. Later on you’ll be able to check it with an if (“if the height is greater than 3, it’s probably in centimetres”).

Writing decimals with a comma, as we do in Spanish. float("1,78") gives ValueError, and in the code height = 1,78 is even worse: it doesn’t give an error, but it creates the tuple (1, 78).

What would happen if you wrote the height straight into the code as height = 1,78?

Python wouldn’t read it as a number with decimals: the comma separates two values, so height would become the tuple (1, 78), a different data type. That line doesn’t give an error. The error comes later, on the BMI line: height ** 2 gives TypeError: unsupported operand type(s) for ** or pow(): 'tuple' and 'int'. When a TypeError talks about a tuple you don’t remember creating, look for a comma inside a number.

Print the intermediate steps (here, height ** 2) while you develop. If the BMI comes out strange, you’ll see straight away whether the problem is in the height or in the division. Once it works, you can delete those lines.

Try it yourself

  • Make the program accept a comma: float(height_txt.replace(",", ".")), and test it with "1,78".
  • Change the height to "178" and convert it to metres by dividing by 100 right after converting it. Do you get 22.1 again?

Program 3: The price of your tuition

The program works out how much it costs to enrol in 5 subjects of 6 credits at 18.32 € per credit (an example price) and splits it into 3 instalments. It has data of all three numeric kinds (the number of subjects is an int, the credits arrive as text and so does the price) and it shows the problem with money in float: the instalment comes out with some ghost cents.

The idea

First decide the type of each value: subjects and credits are counted (int), the price is measured in euros and cents (float). Then, three chained calculations: total credits, total price and price per instalment. Finally, show the money with two decimals.

Before coding, write each calculation on paper with its types: int * int, int * float, float / int. That way you’ll know in advance what type will come out.

The code

# Program 3 · The price of your tuition
subjects = 5                    # int: subjects are counted, not measured
credits_txt = "6"               # credits per subject, as they arrive from input()
price_txt = "18.32"             # euros per credit (example price)
instalments = 3                 # you pay in 3 instalments

# Convert each value to the type it needs
subject_credits = int(credits_txt)    # "6" -> 6: credits are whole numbers
credit_price = float(price_txt)       # "18.32" -> 18.32: money has decimals

credits = subjects * subject_credits    # int * int = int
total = credits * credit_price          # int * float = float
instalment = total / instalments        # / always returns a float

print("Credits:", credits, type(credits))
print("Total:", total, type(total))
print("Each instalment (unrounded):", instalment)

# To show money: 2 decimals with round() or with the :.2f format
print("Each instalment (round):", round(instalment, 2))
print(f"Each instalment (:.2f): {instalment:.2f} €")
print(f"Summary: {credits} credits x {credit_price} € = {total:.2f} €")

Output

Credits: 30 <class 'int'>
Total: 549.6 <class 'float'>
Each instalment (unrounded): 183.20000000000002
Each instalment (round): 183.2
Each instalment (:.2f): 183.20 €
Summary: 30 credits x 18.32 € = 549.60 €

Checking by hand: 5 × 6 = 30 credits; 30 × 18.32 = 549.60 €; 549.60 / 3 = 183.20 € per instalment. Python gets the first two right, but in the third it writes 183.20000000000002: that’s the binary leftover you saw in the theory. round(instalment, 2) fixes it as a number (183.2, without the trailing zero) and :.2f as text (183.20 €, with both decimals, as on any receipt).

Where exactly does the leftover come from? Floats are stored in binary, and 18.32 has no exact binary representation (just as 1/3 has none in decimal: 0.333…). Python stores the closest value that fits. When multiplied by 30, the result lands exactly on the float closest to 549.6, and Python writes it as 549.6. When divided by 3, however, it lands on the float next to the one that corresponds to 183.2, and to tell them apart Python has to write it in full: 183.20000000000002. If you need exact cents, count in cents with integers: 54960 // 3 gives 18320 cents, with no remainder, which is 183.20 €.

The three calculations, zoomed in:

credits = subjects * subject_credits    # int * int = int
total = credits * credit_price          # int * float = float
instalment = total / instalments        # / always returns a float

The rule the types follow is simple: int with int gives int (except with /), one float in the calculation is enough to make the result a float, and / always gives a float, even when the division is exact. You can see it in the output (<class 'int'> and <class 'float'>) and in the diagram:

Which type comes out of each tuition calculation5 times 6 gives 30 (int times int, int); 30 times 18.32 gives 549.6 (int times float, float); 549.6 divided by 3 gives 183.20000000000002 (float); the :.2f format turns it into the text 183.20 €.subjects * subject_credits5 * 6intint30intcredits * credit_price30 * 18.32intfloat549.6floattotal / instalments549.6 / 3floatint183.20000000000002↑ leftover from binaryfloatf"{instalment:.2f} €"183.20000000000002float"183.20 €"str
One float in the calculation is enough to make the result a float; and / always gives a float. The final text is no longer a number.

A trace table with the value and type of each variable after each line:

LineVariableValueType
8subject_credits6int
9credit_price18.32float
11credits30int
12total549.6float
13instalment183.20000000000002float
21(text of the print)"Each instalment (:.2f): 183.20 €"str

The table tells you which type comes out; here’s why, row by row:

  • Line 8: int("6") gives 6: credits are counted.
  • Line 9: float("18.32") gives 18.32: the price has cents.
  • Line 11: 5 * 6 is int times int, and multiplying two integers always gives another integer: 30.
  • Line 12: 30 * 18.32 mixes an int and a float. Python turns the 30 into 30.0 to operate, and the result is a float.
  • Line 13: 549.6 / 3 is a float for two reasons at once: there’s a float in the calculation and it’s also a /. Even 30 / 3 would give 10.0, not 10.
  • Line 21: :.2f doesn’t return a number but a piece of text; that’s why the last row is str.

Questions you might ask

Why does subjects = 5 have no quotes while credits_txt = "6" does? To practice both cases: a value you write yourself as a number and another that comes from outside as text. In a real program, everything coming from input() will arrive like the second one.

Why int() for the credits and not float()? Because credits are counted: there’s no 6.5-credit subject in the degree plan. Using int makes clear what the value means and, if someone types "6.5", the ValueError warns you something’s off.

Is 183.20000000000002 a Python bug? No. It’s how floats work in every language (Java and C too). Banking software works in cents with integers, or with the decimal module, precisely because of this.

What’s the difference between round(instalment, 2) and f"{instalment:.2f}"? round returns a number (you can keep calculating with it) and doesn’t add zeros: 183.2. :.2f produces a text with exactly two decimals: 183.20. For calculations, round; for showing money, :.2f.

What would happen if you rounded with round(instalment, 2) and multiplied by 3 to check that you get the total?

The check wouldn’t come out clean: round(instalment, 2) * 3 gives 549.5999999999999, not 549.6. Rounding doesn’t remove the underlying problem: 183.2 can’t be stored exactly in binary either, so when you multiply, a leftover appears again, this time below. The takeaway: rounding doesn’t make a float exact. For the instalments to add up to exactly the total, work in cents with integers, as in the hint above.

Formatting with :.2f and then trying to calculate with the result. f"{instalment:.2f}" is a str: if you do f"{instalment:.2f}" * 3 you get the text repeated three times, not 549.60.

The price of 18.32 € per credit is an example so the maths is easy to follow. Each university and each Spanish region sets its own, and it changes from one year to the next.

Try it yourself

  • Add a fixed admin fee (a float, for example "27.50") to the total before splitting it into instalments, and check the result by hand.
  • Work out how much you’d pay if you enrolled in 8 subjects instead of 5. Which variable do you have to change, and how many calculations update on their own?

Common mistakes in this practice

  • Converting with int() a value that can have decimals. int("8.5") gives ValueError. Grades, weights, heights and prices go with float().
  • Forgetting to convert. "7" + "8.5" gives "78.5": the program carries on with a text that looks like a number.
  • Forgetting the brackets in the average. a + b + c / 3 divides only the last grade.
  • Writing decimals with a comma. In code it creates a tuple; in float() it gives ValueError.
  • Mixing units. A height in centimetres doesn’t give an error, it gives a BMI of 0.0. Check that the result makes sense.
  • Showing money without formatting. 183.20000000000002 € on a receipt looks awful: use :.2f.

Watch it step by step in Python Tutor

Open Python Tutor, choose Python 3 and paste this short version of program 1:

grade1_txt = "7"          # text, as if it came from input()
grade2_txt = "8.5"
grade3_txt = "6"

grade1 = float(grade1_txt)
grade2 = float(grade2_txt)
grade3 = float(grade3_txt)

grade_sum = grade1 + grade2 + grade3
average = grade_sum / 3
rounded_average = round(average, 2)
passed = rounded_average >= 5.0

print(rounded_average, passed)

Its output:

7.17 True

What to look for, stepping with Next:

  1. After the first three lines, the variables grade1_txt, grade2_txt and grade3_txt appear with quotes: "7", "8.5", "6". They’re text.
  2. After the conversions, grade1 is 7.0 (with a point: it’s a float), even though the text was "7". And grade1_txt is still there, untouched: converting creates a new object, it doesn’t change the original.
  3. When grade_sum is calculated, it’s 21.5; and average, 7.166666666666667. Compare with your calculation by hand.
  4. When rounded_average is calculated, average doesn’t change. The two live side by side: one for calculating and one for showing.
  5. At the end, passed appears as True, without quotes: it’s a bool, not the text "True".

Summary

  • Everything that comes from outside (like what input() returns) is text: convert it as soon as you receive it.
  • int for what’s counted and float for what’s measured or has decimals.
  • Calculate with all the decimals and round only at the end, for display.
  • int with int gives int, one float in the calculation makes it float, and / always gives a float.
  • round() returns a number; :.2f returns a text with two decimals.
  • A program without errors can still be wrong: check the units and do the maths by hand.

Checklist: have you practised it?

  • Have you run the three programs and checked the outputs?
  • Could you say the type of each tuition variable without looking at the table?
  • Have you triggered the "1,78" ValueError yourself and fixed it?
  • Do you understand why the height in centimetres doesn’t give an error?
  • Do you know when to use round() and when to use :.2f?
  • Have you tried the “Try it yourself” ideas without looking at the theory?

If you answered yes to almost everything, you’re ready for the variables and data types exercises, where I no longer give you the code. See you there! And after that, the next topic: Python operators.

Next step: exercisesVariables and data types in Python — exercises with a receipt, temperatures, tips and your student profile (and a True that’s worth 1)

Did this article help you? Here is how you can support SergioLearns →