I1 · Python Programming for AI

Data Types

A data type says what kind of value something is and what can be done with it. Python's basic types are int (whole numbers), float (numbers with a decimal point), str (text), bool (True or False) and NoneType (the value None, meaning 'nothing'). type() tells you a value's type.

8 min Intermediate Jump to the activity

What you need: The earlier topics of this module.

Definition

Is "5" the same as 5 to Python?

A data type says what kind of value something is and what can be done with it. Python's basic types are int (whole numbers), float (numbers with a decimal point), str (text), bool (True or False) and NoneType (the value None, meaning 'nothing'). type() tells you a value's type.

In simple words

5 is a number you can add to. "5" is a character, like a letter on a sign. 5 + 5 is 10, but "5" + "5" is "55", because joining text glues it together. True and False are for yes-or-no questions, and None means 'no value yet'.

Why it matters

Many bugs come from the wrong type: text read from a file that should be a number, or a decimal where a whole number was expected. In AI, data must be the right type before a model can use it.

How it works

TypeExamplesUsed for
int0, 42, -7Counts, ages, positions
float3.14, 0.5, -2.0Measurements, averages, probabilities
str"Riya", "AI", "42"Names, messages, any text
boolTrue, FalseYes-or-no conditions
NoneTypeNoneNo value yet

In code

type() reveals each value's type, and shows why 5 and "5" behave differently.

types.py
values = [42, 3.14, "AI", True, None]
for value in values:
    print(repr(value), "is", type(value).__name__)

print(5 + 5)
print("5" + "5")
print(10 / 4, "is a float, even though 10 and 4 are ints")

Output

42 is int
3.14 is float
'AI' is str
True is bool
None is NoneType
10
55
2.5 is a float, even though 10 and 4 are ints

Try it yourself

What type is it?

Put each value under its Python type.

  • "True"

  • "17"

  • 98.6

  • 7 / 7

  • False

  • 17

Common mistakes

  • Adding a number to text without converting: TypeError.
  • Writing true instead of True. Capital T and F matter.
  • Expecting 10 / 2 to be 5. It is 5.0, a float.

Check yourself

Question 1

1. What is type("42")?

Question 2

2. "5" + "5" gives…

Question 3

3. What does None mean?

Summary

  • Basic types: int, float, str, bool and None.
  • The type decides what operations make sense.
  • type() shows a value's type; / always gives a float.

Finished reading?

Sources: W3Schools Python Tutorial