Variables and data types in Python — theory with your student profile, labels that point to objects and the “5” that wasn’t a 5 (and the average grade that came out as 78.5)

First week of FP1. We’re asked for a program that reads two grades with input() and works out the average. Easy, right? I type the two grades, add them, divide by 2… and the program shows me this before dying:

# My first "average grade" in FP1 (the version with the bug)
# input() always returns text: here I write what it gave me
grade1 = "7"      # what input() returns if you type 7
grade2 = "8.5"    # what input() returns if you type 8.5

grade_sum = grade1 + grade2     # with text, + glues instead of adding
print("Sum of the grades:", grade_sum)
average = grade_sum / 2         # dividing a text by 2: it blows up here
print("Average:", average)
Sum of the grades: 78.5
Traceback (most recent call last):
  File "hook.py", line 8, in <module>
    average = grade_sum / 2         # dividing a text by 2: it blows up here
              ~~~~~~~~~~^~~
TypeError: unsupported operand type(s) for /: 'str' and 'int'

Look at the first line of the output: 78.5. It looks like a number. It even looks like a reasonable sum if you don’t look too closely. But it isn’t the sum of 7 and 8.5 (that would be 15.5): it’s the text "7" glued to the text "8.5". And when I try to divide that text by 2, Python stops dead with a TypeError. That afternoon I learnt that in Python it isn’t enough to know what value a variable has: you need to know what type it is.

In this article you’ll see what a variable really is (spoiler: a label, not a box), the four data types you’ll use all the time (int, float, str and bool), how to convert from one to another and the three mistakes you’re guaranteed to run into: the input() one, the "5" that isn’t a 5 and the decimals that don’t add up. If you haven’t installed Python yet, start with how to install Python on Windows. And when you finish, there’s the practice with three complete programs.

The whole article revolves around an example you know well: your student profile (name, age, grades, credits, tuition).

In a nutshell: A variable in Python is a name that points to a value, and it is created as soon as you assign something to it (mark = 7.5), without declaring its type. The basic types are int, float, str and bool, and whatever you read with input() is always text, so you have to convert it with int() or float() before doing maths.

Before you start. For this topic all you need is Python installed and knowing how to run a .py file (or a cell); nothing else. If print() rings a bell, even better, but you’ll see it used here from the very first example. The topic has four ideas, in this order: what a variable is (a label stuck to an object, not a box); the data types you’ll use all the time (int, float, str, bool and the special value None); how to convert a piece of data from one type to another; and the three mistakes that show up in the practicals no matter what: the input() one, the “5” that isn’t a 5 and the decimals that don’t add up. If you get lost at any point, go back to your student profile and the 78.5 from the start: the whole topic can be told with them.

What is a variable?

Before the definition, think about what you already do without programming. The admin office has your profile written down: Sergio, 19 years old, a 7.5 in FP1, enrolled. Now imagine a program that needs your FP1 grade in five different places: to work out the average, to say whether you’ve passed, to print the report…

You could write 7.5 five times. But the day your exam is reviewed and you get bumped up to an 8, you’d have to find and change all five, and if you forget one, the program will mix two different grades without warning you. The natural thing is to write the data down once, give it a name that says what it is (fp1_grade) and use the name in all those places. If the grade changes, you change one line.

What you’ve just invented, a name that takes you to a piece of data, is exactly a variable. Now, with its technical name:

A variable is a name you give to a piece of data so you can use it later. You create it the first time you assign it a value with =. You don’t have to “declare” it beforehand or say what type it is: Python works it out by looking at the value.

# Your student profile in variables: name = value
name = "Sergio"       # str: text, always in quotes
age = 19              # int: whole number, no quotes
fp1_grade = 7.5       # float: number with decimals (point, not comma)
enrolled = True       # bool: true or false, with a capital letter

print(name, "is", age, "years old")
print("FP1 grade:", fp1_grade)
print("Enrolled?", enrolled)

age = age + 1         # first the right side (19 + 1), then it is stored in age
print("Next year they will be", age)
Sergio is 19 years old
FP1 grade: 7.5
Enrolled? True
Next year they will be 20

Three things worth being clear about from day one:

  • = isn’t the equals sign from maths. It’s an assignment: “work out the right-hand side and give it this name”. That’s why age = age + 1 makes sense in Python (in maths it would be absurd): first 19 + 1 = 20 is calculated with the value that was there, and then the name age starts referring to the 20.
  • Quotes matter. "Sergio" is text; Sergio without quotes would be the name of a variable (and since it doesn’t exist, an error).
  • print() with commas separates the values with a space. That’s why you get Sergio is 19 years old without writing the spaces by hand.

In Java or C you’d write int age = 19;, stating the type in front. Python has dynamic typing: the type belongs to the value, not to the name. That’s exactly what makes getting started so comfortable… and what causes the mistake in the opening story.

age = age + 1, step by step

This is the line that feels the oddest at first, so let’s take it apart. The key is that Python doesn’t read it left to right like a sentence, but in two stages: first everything to the right of the = and, only once it has the result, the name on the left.

StepWhat Python doesWhy
1Looks up the name age on the right and finds the 19To work out age + 1 it needs to know what age is worth right now
2Calculates 19 + 1 and gets 20It’s an ordinary sum between two ints
3Makes the name age refer to the 20Now it’s the left side’s turn: “give the result this name”
4print(..., age) shows 20The name already points to the new value; the 19 is no longer there

Notice that in step 1 age is still 19: the old value is used to build the new one. That’s why in maths x = x + 1 has no solution, while in Python it simply means “add one to it”.

Check you’ve got it: if you write x = 3 and then x = x * 2 + 1, what is x at the end?

It’s 7. On the second line Python first works out the right side with the value it has at that moment: 3 * 2 = 6 and 6 + 1 = 7. Only then does the name x start referring to the 7. The 3 was used for the calculation, but it’s no longer the value of x.

A variable is a label, not a box

Many people picture a variable as a box with the value inside. In Python it’s more accurate to think of labels stuck on objects: the value (the object) lives in memory with its type, and the name just points to it. See it in the diagram with the profile data:

Variables are names that point to objectsFour names from the student profile (name, age, fp1_grade, enrolled) with arrows to their objects: the text Sergio of type str, 19 of type int, 7.5 of type float and True of type bool.Names (variables)Objects in memory: value + typename"Sergio"strage19intfp1_grade7.5floatenrolledTruebooltype(age) → <class 'int'>
The name doesn't store the type: the object it points to does (look at the pill on each box).

Notice that the type pill (str, int, float, bool) is on the right-hand box, the object’s, not on the name. That’s the most important idea in the topic, and we’ll use it in the section on dynamic typing.

Rules for naming variables

Python is strict about how names are written, and the course style (and the style of the whole Python world, the PEP 8 guide) adds a few habits on top:

NameValid?Why
average_gradeYesLowercase, words separated by _ (the recommended style, snake_case)
_temporaryYesIt can start with an underscore
grade2YesIt can contain numbers…
2gradeNo…but not start with one
average gradeNoNo spaces allowed
average-gradeNo- is subtraction: Python would read average - grade
class, if, TrueNoThey’re reserved words of the language
AverageGradeYes, butIt works, but that style is reserved for classes

If you break a rule, the program doesn’t even start: Python checks everything before running the first line and gives you a SyntaxError.

average_grade = 7.17        # good: lowercase and underscore
1grade = 7                  # bad: a name can't start with a number
  File "bad_name.py", line 2
    1grade = 7                # bad: a name can't start with a number
    ^
SyntaxError: invalid decimal literal

The ^ points exactly to where it got lost: at the 1 at the start. And there’s another detail people often forget: Python is case-sensitive. grade and Grade are two different variables, and using a name you’ve never created gives a NameError:

grade = 7
Grade = 9                 # a different variable: Python is case-sensitive
print(grade, Grade)
print(final_grade)        # never created: NameError
7 9
Traceback (most recent call last):
  File "uppercase.py", line 4, in <module>
    print(final_grade)        # never created: NameError
          ^^^^^^^^^^^
NameError: name 'final_grade' is not defined

Writing Grade on one line and grade on another, believing it’s the same variable. Python doesn’t warn you: it simply creates another one. If a value “doesn’t update”, look for a treacherous capital letter first.

Use names that say what they hold (fp1_grade, credit_price) instead of x, a or data2. Three weeks from now, when you reread your practice, you’ll thank me.

Variables and data types in Python you’ll always use

In your first year you’ll work almost all the time with four basic types, plus a fifth special value:

TypeWhat it holdsExamplesOn your profile
intWhole numbers, positive or negative, with no size limit19, -3, 0, 2026age, credits, number of subjects
floatNumbers with a decimal part (written with a point)7.5, 18.32, -0.5, 1.0grades, price per credit, height
strText in single or double quotes"Sergio", 'GCID', "7"name, degree, university
boolTrue or falseTrue, Falseenrolled?, passed?
NoneTypeThe “absence of a value”: only None existsNonea grade that hasn’t been given yet

To find out the type of an object, you ask Python with type():

# type() tells you the type of the object each name points to
name = "Sergio"
age = 19
fp1_grade = 7.5
enrolled = True
pending = None         # None: "there is no value yet"

print(type(name))
print(type(age))
print(type(fp1_grade))
print(type(enrolled))
print(type(pending))
print(type(7), type(7.0), type("7"))   # the same 7, three different types
<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>
<class 'NoneType'>
<class 'int'> <class 'float'> <class 'str'>

The last line is the most instructive: the same 7 written in three ways gives three different types. 7 is an int, 7.0 is a float (the point is enough) and "7" is a str (the quotes are enough). For you they’re all “a seven”; for Python they’re three things that behave differently.

<class 'int'> is Python’s way of saying “this is of type int”. In Python every value is an object of some class; you’ll understand it fully when you reach classes in FP2. For now, read class as “type”.

bool: True and False are numbers too

Booleans come, above all, from comparisons. And they have a very handy quirk: inside, bool is a kind of int, so True is 1 and False is 0.

passed = 7.5 >= 5            # a comparison gives a bool
print(passed, type(passed))
print(True + True + False)   # bool is a kind of int: True is 1 and False is 0
print(int(True), int(False))
True <class 'bool'>
2
1 0

True + True + False gives 2 because it’s 1 + 1 + 0. It looks silly, but in the exercises we use it to count how many subjects you’ve passed without writing a single if. Notice the capital letters too: it’s True and False; true would be a variable that doesn’t exist.

Counting passes with True and False, row by row

Let’s actually do the counting without if, with the FP1 grade from your profile and two more first-year grades:

# Count passed subjects without writing a single if
fp1_grade = 7.5
me1_grade = 4
ic1_grade = 6
passed = (fp1_grade >= 5) + (me1_grade >= 5) + (ic1_grade >= 5)
print(passed, type(passed))
2 <class 'int'>

Python first resolves each bracket and then adds up what came out:

ExpressionResultWorth as a numberWhy
fp1_grade >= 5True17.5 is greater than or equal to 5: passed
me1_grade >= 5False04 doesn’t reach 5: failed
ic1_grade >= 5True16 is greater than or equal to 5: passed
the sum221 + 0 + 1; when you add bools the result is already an int

The brackets aren’t decoration: they make it clear that you compare first and add afterwards. And the type() at the end confirms what was said above: even though you add True and False, what you get is a normal whole number.

Dynamic typing: the name has no type, the object does

Let’s go back to the idea of labels, because it explains two things that surprise people a lot at first: what happens when you write copy = grade, and why a variable can change type.

# Variables are labels that point to objects
grade = 7
copy = grade            # copy points to the SAME object 7: no new 7 is created
print(grade, copy, grade is copy)

grade = grade + 1       # the object 8 is created and the grade label moves to it
print(grade, copy, grade is copy)

value = 19              # a name has no fixed type: now it points to an int...
print(value, type(value))
value = "nineteen"      # ...and now to a str. Python doesn't complain
print(value, type(value))
7 7 True
8 7 False
19 <class 'int'>
nineteen <class 'str'>

Let’s go line by line with a trace table (what points to what after each instruction):

Instructiongrade points tocopy points tograde is copy
grade = 77——
copy = grade7the same 7True
grade = grade + 18 (new object)7False

The is operator asks “are these two labels stuck on the same object?”. After copy = grade the answer is True: the 7 hasn’t been copied, a second label has just been stuck on it. And when you write grade = grade + 1, Python doesn’t modify the 7: it calculates a new 8 and peels the grade label off to stick it on the 8. The copy label doesn’t notice anything and stays on the 7:

What happens when you reassign a variableStep 1: grade and copy point to the same object 7. Step 2: after grade = grade + 1 the object 8 is created, the grade label moves to it and copy still points to 7.1 · copy = gradegradecopy7intgrade is copy → True2 · grade = grade + 1gradecopy8intnew object7grade is copy → False
Assigning doesn't change the 7: it creates an 8 and moves the grade label. That's why copy is still 7.

The second half of the program shows dynamic typing in its purest form: value first points to an int and then to a str. Python doesn’t complain, because the type isn’t in the name: it’s in the object. Being able to doesn’t mean it’s a good idea; if a variable changes type halfway through a program, the code becomes hard to follow.

With numbers and text this behaviour never gives you a fright, because they can’t be modified (they’re immutable): a new object is always created. With lists there will be surprises, and that’s why later on there’s a whole topic on mutability and copies. Hold on to the label diagram: it’ll help you then.

The trace, with the why of each line

The table above shows what points to what; this one adds why it happens, line by line, including the value part the table didn’t have:

LineWhat happensWhy
grade = 7The object 7 is created and the label grade is stuck to itAssigning means “work out the right side and give it this name”
copy = gradeThe label copy is stuck to the same 7The right side is grade, and grade leads to the 7 that already exists: there’s nothing to calculate or copy
first printIt shows 7 7 TrueBoth labels are on the same object, so is gives True
grade = grade + 17 + 1 is calculated, a new 8 comes out and grade moves to itThe 7 can’t be modified (it’s immutable): the only way to “change” it is to build another object
second printIt shows 8 7 Falsecopy hasn’t been touched on any line; it stays where it was
value = 19value points to an intThe type comes from the object 19, not from the name
value = "nineteen"value comes off the 19 and is stuck to a strThe name doesn’t care what type it points to: it’s just a label

If you’re ever unsure what a variable is worth, do exactly this on paper: one row per line and one column per name. It’s the fastest way to catch a bug before running anything.

Check you’ve got it: if right at the end of that trace you write copy = grade, what does each label point to and what would grade is copy give?

Both point to the 8 and grade is copy gives True. It’s the same as on the second line of the program: the right side is grade, which leads to the 8, so copy comes off the 7 and is stuck to that same 8. No new object is created.

The mistake everyone makes with input()

Here’s the cause of the opening story. input() always returns a str, whatever the user types. If you type 19, what reaches your program is the text "19". In the article we don’t use input() so that every output is real and reproducible, so I write directly the text it would give you:

# input() ALWAYS returns text, even if you type a number
age = "19"              # what input("How old are you? ") returns if you type 19
print(type(age))
print(age + 1)          # str + int: TypeError
<class 'str'>
Traceback (most recent call last):
  File "input_text.py", line 4, in <module>
    print(age + 1)          # str + int: TypeError
          ~~~~^~~
TypeError: can only concatenate str (not "int") to str

type(age) confirms it: <class 'str'>. And the error message is one of Python’s clearest: can only concatenate str (not “int”) to str, “I can only concatenate (glue) a str to another str, not an int”. For Python, + between text means glue, and it doesn’t know how to glue a number to text.

The fix is to convert the text to the type you need as soon as you read it:

age = int(input("How old are you? "))         # integer
grade = float(input("Exam grade: "))          # decimal
name = input("What's your name? ")            # text: no need to convert

You read it from the inside out: first input() returns the text and then int() turns it into a number. That way the variable age is born as an int.

int(input()) read from the inside out

Why doesn’t input() give you a number directly when you type one? Because when you write the program, Python doesn’t know what the person is going to type: it might be 19, but also “nineteen”, “7,5” or nothing at all. The only type that can hold anything someone types is text, so input() always returns a str and leaves it up to you what to do with it.

That’s why you add the conversion yourself, wrapping input(). This is how age = int(input("How old are you? ")) runs if you type 19 and press Enter:

StepWhat happensValue at that momentWhy
1input() shows the question and waits(nothing yet)It’s the innermost part: it runs first
2You type 19 and press Enter"19" (a str)input() returns what you typed, as text; the Enter isn’t included
3int("19")19 (an int)It creates a new whole-number object from the text
4age = ...age points to the 19First the whole right side and, at the end, the name

If you remove the int(), you’re stuck at step 2: age would point to the text "19" and the age + 1 from before would give TypeError again.

When you see several functions nested inside each other, read them like an onion: start with the innermost brackets and work your way out. Each layer receives what the previous one returned.

Converting from one type to another

The conversion functions have the same names as the types: int(), float(), str() and bool(). Each one creates a new object of the requested type (it doesn’t change the original):

# Converting from one type to another: int(), float(), str() and bool()
age = int("19")                # text -> integer
grade = float("7.5")           # text -> decimal
print(age + 1, grade * 2)

print(str(19) + " years")      # number -> text, so you can glue it to other text
print(int(7.9))                # float -> int CUTS the decimals, it doesn't round
print(round(7.9))              # to really round, round()
print(float(19))               # int -> float: adds the .0
print(int("  19  "))           # spaces on the sides don't matter
print(bool(0), bool(19), bool(""), bool("False"))
20 15.0
19 years
7
8
19.0
19
False True False True

Let’s check the sums: int("19") + 1 gives 20 and float("7.5") * 2 gives 15.0 (it’s a float, that’s why it has .0). There are two results that catch almost everyone out:

  • int(7.9) gives 7, not 8. int() cuts the decimals; it doesn’t round. If you want to round, use round(7.9), which gives 8.
  • bool("False") gives True. For bool() any text that isn’t empty is true, even if it says “False”. Only "", 0, 0.0 and None give False.
Check you’ve got it: what does print(int("8") + int(8.9) + bool("0")) print?

It prints 17. Piece by piece: int("8") turns the text into the whole number 8. int(8.9) cuts the decimals, it doesn’t round, so it gives 8 (not 9). And bool("0") gives True, because "0" is a text with one character: it isn’t empty, even though what’s inside is a zero. Since True is worth 1, the sum is 8 + 8 + 1 = 17.

And then there’s the conversion that fails. int() only understands text that is a whole number:

# int() only understands text of WHOLE numbers
grade = "7.5"             # what input() returns if you type 7.5
print(float(grade))       # float() does understand it
print(int(float(grade)))  # the two-step route: "7.5" -> 7.5 -> 7
print(int(grade))         # int("7.5") directly: ValueError
7.5
7
Traceback (most recent call last):
  File "int_decimal.py", line 5, in <module>
    print(int(grade))         # int("7.5") directly: ValueError
          ~~~^^^^^^^
ValueError: invalid literal for int() with base 10: '7.5'

float("7.5") works, int(float("7.5")) works (two steps: text → 7.5 → 7), but int("7.5") directly gives ValueError: invalid literal for int() with base 10. In plain words: “that isn’t an integer written in base 10”. The diagram sums up the five conversions you’ve just seen, with the failing one in red:

Conversions between typesFive conversions: int of "19" gives 19; float of "7.5" gives 7.5; int of "7.5" gives ValueError; int of 7.9 gives 7 because it cuts the decimals; str of 19 gives the text "19".You haveYou callYou get"19"strint()19int"7.5"strfloat()7.5float"7.5"strint()ValueError7.9floatint()7intcuts, doesn't round19intstr()"19"str
Each arrow creates a new object of another type. The red row is the error you'll see most with input().

Using int(input(...)) for a grade. It works while the user types 7… and blows up the day they type 7.5. For grades, prices, heights or temperatures, float().

Another ValueError that’s very common in Spain (and anywhere that writes decimals with a comma): writing the decimal with a comma. float("1,78") fails, because Python only understands the point. You’ll see it live in the practice, with the BMI program.

The other classic mistake — the ‘number’ that isn’t a number

This is the cousin of the input() mistake, and the one that explains the 78.5 in the opening story. A number and a text that looks like a number don’t behave the same with the same operators:

a = 5               # whole number
b = "5"             # text that LOOKS like a number
print(a + a)        # addition: 10
print(b + b)        # concatenates: 55
print(b * 3)        # repeats the text: 555
print(a * 3)        # multiplies: 15
print(len(b), type(b))
print(a + int(b))   # convert before operating: 10
print(a + b)        # mixing int and str: TypeError
10
55
555
15
1 <class 'str'>
10
Traceback (most recent call last):
  File "five.py", line 9, in <module>
    print(a + b)        # mixing int and str: TypeError
          ~~^~~
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Line by line:

ExpressionTypesResultWhat it does
a + aint + int10Adds
b + bstr + str55Concatenates (glues)
b * 3str * int555Repeats the text 3 times
a * 3int * int15Multiplies
len(b)len(str)1Counts characters: "5" has one
a + int(b)int + int10Converts first, then adds
a + bint + strTypeErrorPython doesn’t guess what you meant

Notice that print(b + b) shows 55 without quotes: print() never shows the quotes of a text, and that’s why the result looks like a number. It’s exactly what happened to me with the 78.5.

If a result comes out “too big” or with digits glued together (55, 78.5, 1020), suspect a str. Put a print(type(variable)) just before and you’ll know in a second.

The hook, rebuilt line by line

You now have all the pieces to fully understand the program from the start. This is how it ran:

LineWhat happensValueWhy
grade1 = "7"grade1 points to a text"7" (str)It’s what input() returns when you type 7
grade2 = "8.5"grade2 points to another text"8.5" (str)Same: input() always gives text
grade_sum = grade1 + grade2The two texts are glued together"78.5" (str)+ between two strs concatenates, it doesn’t add
print("Sum of the grades:", grade_sum)It shows 78.5print() doesn’t show the quotes, so it looks like a number
average = grade_sum / 2TypeError and the program stopsA text can’t be divided: / doesn’t exist between str and int

The error message said it loud and clear: unsupported operand type(s) for /: 'str' and 'int', “operation not allowed between a str and an int“. The line that fails is the one with /, but the real mistake was two lines earlier, when I didn’t convert what came in from input(). That’s normal: the error goes off where the wrong type can no longer be used, not where it came in.

The fixed version changes just one thing, converting each text as soon as it arrives:

# The same average grade, converting each text as soon as it arrives
grade1 = float("7")      # what float(input()) would give if you type 7
grade2 = float("8.5")    # what float(input()) would give if you type 8.5

grade_sum = grade1 + grade2    # now + really adds
print("Sum of the grades:", grade_sum)
average = grade_sum / 2
print("Average:", average)
Sum of the grades: 15.5
Average: 7.75

Now 7.0 + 8.5 gives 15.5 and 15.5 / 2 gives 7.75, the calculation you would have done by hand.

Floats aren’t exact

Third surprise, and this one isn’t your fault. Look:

# Floats are stored in binary and some decimals don't fit exactly
print(0.1 + 0.2)
print(0.1 + 0.2 == 0.3)
print(round(0.1 + 0.2, 2))

# On your profile: 30 credits at 18.32 € per credit, paid in 3 instalments
total = 30 * 18.32
instalment = total / 3
print(total)
print(instalment)
print(round(instalment, 2))
print(f"{instalment:.2f} €")
0.30000000000000004
False
0.3
549.6
183.20000000000002
183.2
183.20 €

0.1 + 0.2 gives 0.30000000000000004? And 0.1 + 0.2 == 0.3 gives False? It’s not a Python bug: floats are stored in binary, and just as 1/3 doesn’t fit exactly in decimal (0.3333…), 0.1 doesn’t fit exactly in binary. The closest possible value is stored and, when you add, the tiny leftovers show up.

On your profile it happens with real money: 30 credits at 18.32 € are 549.6 € (by hand: 30 × 18.32 = 549.60), but dividing by 3 instalments gives 183.20000000000002 instead of 183.20. There are two ways to fix it for display:

  • round(instalment, 2) → the number 183.2 (still a float; round doesn’t add trailing zeros).
  • f"{instalment:.2f} €" → the text 183.20 €, always with two decimals. That’s what you want on a receipt.

Why 0.1 doesn’t fit in binary

Let’s go back to the sentence from before, “0.1 doesn’t fit exactly in binary”, because it’s usually said very quickly. In words: in decimal, each position after the point is worth a tenth, a hundredth, a thousandth… In binary, each position is worth half the previous one: a half, a quarter, an eighth, a sixteenth… A number fits exactly in binary only if it can be written as a sum of those pieces using a finite number of positions.

  • 0.5 is a half: it fits exactly.
  • 0.25 is a quarter: it fits exactly. And 0.75 is a half plus a quarter: that too.
  • 0.1 is a tenth, 1/10. However many halves, quarters and eighths you add, you never get exactly to 1/10: you always go over or fall short by a little. Python stores the closest value it can.

You can see it for yourself:

print(0.5 + 0.25 == 0.75)   # halves and quarters: they fit exactly in binary
print(f"{0.1:.20f}")        # 0.1 with 20 decimals: what is really stored
True
0.10000000000000000555

With 0.5, 0.25 and 0.75 the comparison gives True because there’s nothing to approximate. And the 0.1 that’s really stored carries a very small leftover at the end; when you add 0.1 + 0.2, the leftovers pile up, and that’s why the 4 in 0.30000000000000004 shows up.

Check you’ve got it: what do 0.5 + 0.5 == 1.0 and round(0.1 + 0.2, 2) == 0.3 give?

Both give True. The first because 0.5 is a half and fits exactly in binary: a half plus a half is exactly 1, with no leftovers. The second because round() leaves the sum at two decimals before comparing, so the leftover disappears and you get the same 0.3 you write on the right. It’s exactly the round-before-comparing trick from the typical mistake below.

Comparing two floats with == and trusting the result. 0.1 + 0.2 == 0.3 is False. Round before comparing (round(x, 2) == 0.3) or check whether the difference is tiny; you’ll see it in the operators topic.

The FP1 notes explain it with floating-point representation: the number is stored as a mantissa and an exponent, with a limited size, which is why many real numbers can only be stored approximately. That’s where the name float comes from.

Which type should I use for each piece of data?

Before writing a program, decide the type of each piece of data. This table saves you half the mistakes in the topic:

If the data…UseExample from the profile
Is counted (there’s no “half”)intsubjects, credits, age, people
Is measured or has decimalsfloatgrades, prices, height, temperature
Is text, or a number you won’t calculate withstrname, ID number, phone, postcode
Answers yes or noboolenrolled, passed
Doesn’t exist yetNonethe grade of an exam you haven’t sat

The phone number or postcode case is interesting: they’re “numbers”, but you’ll never add them, and if you store them as int you lose the leading zero (int("08001") gives 8001). That’s why they go as str.

Common mistakes with variables and data types

Adding what input() returns without converting it. "7" + "8.5" gives "78.5" (glue) and "7" + 1 gives TypeError. Convert when you read: float(input(...)).

int("7.5"). It gives ValueError. If the data can have decimals, float(); if you really want an integer, int(float("7.5")).

Writing decimals with a comma: grade = 7,5 doesn’t give an error, but it creates a tuple (7, 5), not the number 7.5. And float("7,5") gives ValueError. In Python, always a point.

Thinking int(7.9) rounds. It cuts: it gives 7. To round, round().

Writing true, false or none in lowercase. Python takes them for variable names and gives NameError. They’re True, False and None.

Watch it step by step in Python Tutor

Python Tutor runs your code line by line and draws the variables and the objects they point to. It’s the best way to see the label idea with your own eyes. Choose Python 3, paste this program and click Visualize Execution:

grade = 7
copy = grade           # two labels, a single object 7
grade = grade + 1      # grade moves to 8; copy stays on 7

age_txt = "19"         # this is how a value arrives from input()
age = int(age_txt)     # new object, of type int

average = (7 + 8.5 + 6) / 3
passed = average >= 5
average_type = type(average)

print(grade, copy, age)
print(round(average, 2), passed, average_type)

At the end, the output is this:

8 7 19
7.17 True <class 'float'>

What to look for, stepping with Next:

  1. After copy = grade: in the Frames column you’ll see grade and copy with the same value 7. Python Tutor draws small numbers inside the variable, but remember the label diagram: both names point to the same object.
  2. After grade = grade + 1: grade changes to 8 and copy stays at 7. The assignment has moved a label; it hasn’t touched the 7.
  3. After age = int(age_txt): age_txt, with "19" in quotes (a str), sits next to age, with 19 without quotes (an int). Same digits, different type.
  4. After average = …: average is 7.166666666666667. The average of 7, 8.5 and 6 isn’t exact, and Python shows all the decimals it stores.
  5. At average_type = type(average): notice that a type is also an object a name can point to. The final print shows it as <class 'float'>.

In Python Tutor’s options you can switch inline primitives to render all objects on the heap. Then numbers are also drawn as separate objects, with arrows, and you’ll see exactly the label diagram.

Summary

ConceptThe essentialsExample
VariableA name that points to an object; created when you assignage = 19
AssignmentRight-hand side first, then the nameage = age + 1
Basic typesint, float, str, bool (and None)19, 7.5, "GCID", True
type()Tells you the object’s typetype(7.5) → <class 'float'>
Dynamic typingThe type is in the object, not the namevalue = 19 and then value = "nineteen"
input()Always returns a strfloat(input("Grade: "))
Conversionsint(), float(), str(), bool(): they create new objectsint("19") → 19
"5" versus 5+ glues text and adds numbers"5" + "5" → 55
floatApproximate: round for displayf"{x:.2f}"

Three ideas to take away:

  1. A variable is a label stuck on an object, and the object carries the type.
  2. Everything that comes in through input() is text: convert it as soon as you read it.
  3. Floats are approximate: round at the end and never compare decimals blindly with ==.

With types clear, you’re ready to calculate, compare and combine conditions. That’s exactly the next topic: Python operators, where you’ll see //, %, ** and why 5 / 2 gives 2.5. But first, put it into practice with your average grade, BMI and tuition price.

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

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