Skip to main content

Programming fundamentals · Beginner · 16 min

Understand values and types in Python: int, float, str, bool and None

By Padding · Updated 18 Nov 2026
Python 3.15.2 · python:3.15-slim (Debian)

You will explore Python's five basic types in the REPL and in small scripts, convert between them, see why 0.1 + 0.2 is not 0.3, and end with a self-checking cheat sheet built from what you ran.

On this page

Every piece of data in a Python program is a value, and every value has a type. The type decides what you can do with it: you can divide a number but not a word, and you can make a word upper case but not a number. Most of the errors beginners meet in their first month, such as "500" + 200 failing, or a total showing 0.30000000000000004, are type questions in disguise.

In this tutorial you look at the five types you use most: int (whole numbers), float (numbers with a decimal point), str (text), bool (True or False) and None (no value). You try them in the REPL, Python's interactive prompt, then save each experiment as a small script so you have a record. You finish by turning everything you learned into a cheat sheet that checks itself every time you run it.

The examples use python3. On Windows outside WSL, type py instead. On an Android phone, the Termux app can install Python with pkg install python; every step here then runs offline, so it costs no mobile data after the install.

Step 1 · Ask Python for a type

Make a folder for this tutorial and check which Python you are running:

Bash
mkdir -p ~/types-demo
cd ~/types-demo
python3 --version

mkdir -p creates the folder (and does nothing if it already exists), cd moves into it, and python3 --version prints the version.

Now start the REPL by typing python3 on its own and pressing Enter. The prompt changes to >>>. Type each line after >>> and press Enter; Python prints the answer straight away:

Text
>>> 42
42
>>> type(42)
<class 'int'>
>>> type(4.2)
<class 'float'>
>>> type("42")
<class 'str'>
>>> type(True)
<class 'bool'>
>>> type(None)
<class 'NoneType'>
>>> exit()

type() is a built-in function: you give it a value in the brackets, and it tells you the value's type. <class 'int'> is Python's way of saying "this is an int". Notice that 42 and "42" look alike but are different types: the quotes make the second one text. exit() leaves the REPL and returns you to the shell.

The REPL forgets everything when you leave it, so save the same experiment as a script:

Bash
cat > basics.py <<'PY'
values = [42, 4.2, "42", True, None]

for value in values:
    print(repr(value), type(value).__name__)
PY
python3 basics.py

The cat > basics.py <<'PY' line writes everything up to the closing PY into a file called basics.py; you can paste those lines into your editor and save them instead. In the script:

  • values = [...] is a list holding one value of each type.
  • for value in values: runs the indented line once for each value.
  • repr(value) shows the value the way you would type it in code, so text keeps its quotes.
  • type(value).__name__ gives just the type's name, such as int, without the <class ...> wrapping.

Check it worked

The output is five lines: 42 int, 4.2 float, '42' str, True bool and None NoneType. The quotes around '42' are the only visible sign that it is text, which is why repr() is useful when you are unsure what you have.

Step 2 · Divide two ways with int and float

Python has two number types because whole numbers and fractional numbers behave differently inside the computer. An int is exact and has no size limit. A float holds a decimal fraction, with about 15 to 17 significant digits of precision.

Python also has two division operators. Write a script that tries them:

Bash
cat > division.py <<'PY'
print(7 / 2)
print(6 / 2)
print(7 // 2)
print(7 % 2)
print(-7 // 2)
print(type(3 + 0.5).__name__)
print(2 ** 100)
PY
python3 division.py

Line by line:

  • 7 / 2 is true division. It always gives a float: 3.5.
  • 6 / 2 gives 3.0, not 3. The answer is whole, but / still returns a float.
  • 7 // 2 is floor division. It divides and rounds down to a whole number: 3.
  • 7 % 2 is the remainder after floor division: 1. Testing n % 2 == 0 is the usual way to check whether a number is even.
  • -7 // 2 gives -4, not -3. Floor division rounds down, towards minus infinity, not towards zero. This surprises people coming from other languages.
  • 3 + 0.5 mixes an int and a float, and the answer is a float. Python widens to the type that can hold the result.
  • 2 ** 100 is 2 to the power of 100. The answer has 31 digits, and Python prints all of them exactly, because ints grow as large as memory allows.

Check it worked

The output is 3.5, 3.0, 3, 1, -4, float and 1267650600228229401496703205376. If your fifth line shows -3, check you typed // and not /.

The script is called division.py on purpose. Python has a standard module called numbers, used by decimal later in this tutorial, and a file named numbers.py in your folder would hide it and break that import. Avoid naming your files after standard modules such as math, random or decimal.

Step 3 · Convert between types

Values often arrive as the wrong type. Anything typed at the keyboard, read from a file or received from a web form is text, even when it looks like a number. The functions int(), float() and str() build a new value of their type from the one you give them:

Bash
cat > convert.py <<'PY'
print(int("42") + 1)
print(float("2.5") * 2)
print(str(42) + " items")
print(int(" 42\n"))
print(int(3.9), int(-3.9))
print(round(3.9), round(2.5), round(3.5))
print(int(float("3.5")))

try:
    int("3.5")
except ValueError as err:
    print("ValueError:", err)

try:
    "5" + 3
except TypeError as err:
    print("TypeError:", err)
PY
python3 convert.py

What each line shows:

  • int("42") + 1 turns the text "42" into the number 42, so adding works: 43.
  • float("2.5") * 2 does the same for a decimal: 5.0.
  • str(42) + " items" goes the other way. + joins two strings, so the number has to become text first.
  • int(" 42\n") gives 42. Spaces and a trailing newline around the digits are allowed, which helps when reading lines from a file.
  • int(3.9) gives 3 and int(-3.9) gives -3. Converting a float to an int cuts off the fraction; it does not round.
  • round() rounds to the nearest whole number. Halves go to the nearest even number, so round(2.5) is 2 and round(3.5) is 4. This is called banker's rounding, and it avoids a bias towards rounding up when you round many values.
  • int(float("3.5")) is how you get a whole number from text with a decimal point: text to float, then float to int.
  • The try: and except ...: blocks run code that you expect to fail and print the error instead of stopping the script. int("3.5") raises ValueError, because "3.5" is not written as a whole number. "5" + 3 raises TypeError, because Python will not guess whether you meant 8 or "53".

Check it worked

The first seven lines are 43, 5.0, 42 items, 42, 3 -3, 4 2 4 and 3. The last two start with ValueError: and TypeError:, followed by Python's explanation, something like invalid literal for int() with base 10: '3.5' and can only concatenate str (not "int") to str. Read those messages when you see them in your own code: they name both types involved.

Step 4 · Test truth with bool

A bool is either True or False. You get one from every comparison, and if statements use them to decide what to run. bool() converts any value to True or False, and the rules for that, called truthiness, matter as soon as you write an if:

Bash
cat > truth.py <<'PY'
print(5 > 3, type(5 > 3).__name__)

for value in [0, 1, -5, 0.0, "", " ", "0", "False", None, []]:
    print(repr(value), "->", bool(value))

print(True + True)
print(isinstance(True, int))

answer = "no"
print(bool(answer), answer == "yes")
PY
python3 truth.py
  • 5 > 3 is a comparison, and its result is the bool True.
  • The loop converts ten values. Zero of any number type, the empty string "", None and an empty list [] are false. Everything else is true, including " " (a space), "0" and even "False", because they are non-empty strings.
  • True + True gives 2. In Python, bool is a special kind of int, with True worth 1 and False worth 0, which isinstance(True, int) confirms. It is handy for counting: sum(x > 100 for x in amounts) counts how many amounts are over 100.
  • The last line shows a common bug. Someone types no, and bool(answer) is True because the text is not empty. To ask whether they said yes, compare the text: answer == "yes".

Check it worked

The first line is True bool. In the loop, 0, 0.0, '', None and [] show False, and the other five show True. Then you see 2, True and finally True False.

Step 5 · Represent no value with None

None means "no value here". There is only one None, and it is the only value of type NoneType. You meet it in three places: a function that does not return anything gives back None; a variable can start as None until real data arrives; and many functions return None to say "not found".

Bash
cat > nothing.py <<'PY'
def greet(name):
    print(f"Hello, {name}")

result = greet("Amara")
print(result, type(result).__name__)

discount = None
if discount is None:
    print("no discount set yet")

print(None == 0, None == "", bool(None))
PY
python3 nothing.py
  • greet prints a greeting but has no return line, so calling it gives back None. result holds that None.
  • discount = None says "we do not know the discount yet", which is different from a discount of 0.
  • if discount is None: is the way to test for None. is checks that it is the very same object, and because there is only one None, that is exact.
  • None == 0 and None == "" are both False: None is not zero and not empty text. It is falsy, though, so if not discount: would treat None and 0 the same. Use is None when the difference matters.

Check it worked

The output is Hello, Amara, then None NoneType, then no discount set yet, then False False False. If you see None printed somewhere you expected a number in your own code, a function you called probably forgot its return.

Step 6 · See why 0.1 + 0.2 is not 0.3

Floats are stored in binary, base 2. Just as 1/3 has no exact decimal form (0.333...), 1/10 has no exact binary form. Python stores the nearest binary fraction it can, and the tiny difference shows up in sums. For money, that is not acceptable, so this step also shows the two usual fixes:

Bash
cat > money.py <<'PY'
import math
from decimal import Decimal

total = 0.1 + 0.2
print(total)
print(total == 0.3)
print(math.isclose(total, 0.3))
print(Decimal(0.1))

print(Decimal("0.1") + Decimal("0.2"))
print(Decimal("0.1") + Decimal("0.2") == Decimal("0.3"))

price_cents = 1999
total_cents = price_cents * 3
print(f"{total_cents // 100}.{total_cents % 100:02d}")
PY
python3 money.py
  • 0.1 + 0.2 prints 0.30000000000000004, and comparing it to 0.3 gives False. Nothing is broken: this is how binary floating point works in almost every programming language.
  • math.isclose(total, 0.3) asks "are these equal to within a tiny tolerance?" and gives True. Use it instead of == when comparing floats from calculations, such as measurements.
  • Decimal(0.1) reveals the value Python actually stored for 0.1: a long number that is very close to, but not exactly, one tenth.
  • Decimal from the standard decimal module does decimal arithmetic exactly. Create it from a string, Decimal("0.1"), not from a float, or you copy the float's error in with it. Then 0.1 + 0.2 is exactly 0.3.
  • The last fix needs no module: store money as a whole number of the smallest unit, such as cents, kobo or pesewas. 1999 cents is 19.99. Ints are exact, so three of them total exactly 5997. To show it, // 100 gives the whole units, % 100 gives the cents, and :02d pads the cents to two digits so 5 cents prints as 05.

Check it worked

The output is 0.30000000000000004, False, True, then 0.1000000000000000055511151231257827021181583404541015625, then 0.3, True and 59.97. Payment systems often send amounts as whole minor units for this reason, so if an API gives you 150000 for a ₦1,500 payment, divide by 100 only when you display it.

Step 7 · Change a name's type and add a type hint

A variable in Python is a name that points to a value. The value has a type, but the name does not, so the same name can point to an int now and a string later. This is called dynamic typing. A type hint is a note you add to say which type you intend. Python stores the note but does not enforce it:

Bash
cat > hints.py <<'PY'
box = 42
print(type(box).__name__)
box = "forty-two"
print(type(box).__name__)


def double(n: int) -> int:
    return n * 2


print(double(21))
print(double("ha"))
print(double.__annotations__)
PY
python3 hints.py
  • box first points to an int, then to a str. Python allows it, which is flexible but means a name can hold a type you did not expect.
  • def double(n: int) -> int: defines a function with hints. n: int says the argument should be an int, and -> int says the function returns one.
  • double(21) gives 42, as intended.
  • double("ha") also runs and gives haha, because * on a string repeats it. The hint said int, and Python ran it anyway. Hints are for people and tools, not for the interpreter.
  • double.__annotations__ shows the hints Python stored with the function.

Type checkers such as mypy and Pyright read these hints without running your code and warn you about calls like double("ha"). Editors such as VS Code use them to suggest and flag mistakes as you type. You can add hints gradually, one function at a time.

Check it worked

The output is int, str, 42, haha, then {'n': <class 'int'>, 'return': <class 'int'>}. The haha line is the proof that the hint was not enforced.

Step 8 · Build a cheat sheet that checks itself

You now have seven small scripts. Collect the facts you checked into one file. Each line pairs a fact, written as you would say it, with the Python expression that proves it. Running the file prints ok next to every fact that still holds, so the cheat sheet can never quietly go out of date:

Bash
cat > cheatsheet.py <<'PY'
"""My cheat sheet for Python values and types. Run it to re-check every fact."""
import math
import sys
from decimal import Decimal


def raises(action, error):
    try:
        action()
    except error:
        return True
    return False


facts = [
    ("42 is an int, 4.2 a float, '42' a str", (type(42), type(4.2), type("42")) == (int, float, str)),
    ("True is a bool, and a bool is an int", type(True) is bool and True + True == 2),
    ("None is the only NoneType value", type(None).__name__ == "NoneType"),
    ("/ always gives a float: 6 / 2 == 3.0", isinstance(6 / 2, float)),
    ("// rounds down: 7 // 2 == 3, -7 // 2 == -4", (7 // 2, -7 // 2) == (3, -4)),
    ("% is the remainder: 7 % 2 == 1", 7 % 2 == 1),
    ("ints have no size limit", 2 ** 100 == 1267650600228229401496703205376),
    ("int('42') turns text into a number", int("42") + 1 == 43),
    ("int('3.5') fails; use int(float('3.5'))", raises(lambda: int("3.5"), ValueError) and int(float("3.5")) == 3),
    ("int() cuts off the fraction", (int(3.9), int(-3.9)) == (3, -3)),
    ("round() sends halves to even", (round(2.5), round(3.5)) == (2, 4)),
    ("'5' + 3 is a TypeError", raises(lambda: "5" + 3, TypeError)),
    ("0, '', None and [] are falsy; '0' is truthy", not any([0, "", None, []]) and bool("0")),
    ("test for None with is", None is None and None != 0),
    ("0.1 + 0.2 != 0.3, use math.isclose", 0.1 + 0.2 != 0.3 and math.isclose(0.1 + 0.2, 0.3)),
    ("Decimal from strings is exact", Decimal("0.1") + Decimal("0.2") == Decimal("0.3")),
]

for text, holds in facts:
    print("ok " if holds else "NO ", text)

failed = [text for text, holds in facts if not holds]
print(f"{len(facts) - len(failed)} of {len(facts)} facts hold on Python {sys.version.split()[0]}")
if failed:
    sys.exit(1)
PY
python3 cheatsheet.py
python3 cheatsheet.py > cheatsheet.txt

New pieces in this file:

  • The text between """ marks at the top is a docstring: a note describing the file.
  • raises(action, error) runs action and returns True if it fails with the given kind of error. That turns "this line should fail" into a fact you can check.
  • lambda: int("3.5") wraps the code in a tiny unnamed function, so raises can run it inside its try block instead of it failing straight away.
  • facts is a list of pairs: a sentence, then an expression that is True when the sentence is right.
  • The loop prints ok or NO before each sentence. The last lines count the failures, print the Python version, and end the script with an error status if any fact did not hold.
  • python3 cheatsheet.py > cheatsheet.txt saves the output to a text file, a one-page summary you can print or keep beside your editor.

Add a fact of your own from your REPL experiments, such as ("bool('False') is True", bool("False")), and run the file again.

Check it worked

The output is 16 lines starting with ok, then a last line like 16 of 16 facts hold on Python 3.15.2 (your patch number may be higher). cat cheatsheet.txt shows the same lines. If any line starts with NO, compare that expression with the step it came from.

When you no longer need the scripts, delete the folder, after copying cheatsheet.py somewhere you keep notes if you want it:

Bash
cd ~
rm -rf ~/types-demo

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.