LESSON 4 / 5 · 8 MIN
Data Types
LET'S MAKE IT CLICK
Know your types
Every Python object has a type. A type describes the kind of value and the operations it supports.
Useful for counts.
These digits are characters.
Type determines the available operations.
A value can look like a number while still being text.
Move through one idea at a time. Watch, experiment, and check your understanding along the way.
Same appearance, different meaning
Add two integers.
Join two pieces of text.
The operand types change the operation.
The same + symbol has different meanings for numbers and strings.
42 is an integer, but "42" is a string. They may look similar when printed, yet they support different operations. Adding two integers calculates a sum; adding two strings joins their contents.
See the Python code
print(42 + 8) # 50
print("42" + "8") # 428Keep in mind
Variables do not need type declarations here. The object has a type; a name can later be bound to an object of another type.
The everyday types
Create a boolean value.
Ask Python for its type.
Print the returned type object.
True and False are booleans. type() helps identify the kind of value.
int holds whole numbers; float represents floating-point numbers; str holds text; bool holds True or False. Python also has collections such as list and dict, and None represents the absence of a value.
Use type(value) to inspect the type of a value. It returns a type object, which print() can display.
YOUR TURN TO EXPLORE
Meet the value behind the label.
Select an example. Inspect its value and type, then step through type() and print().
No assignments yet.
OUTPUT
No output yet.
Predict the result, then take the first step.
Convert deliberately
Start with a string of digits.
Parse the text as an integer.
Now arithmetic can use the number.
A conversion creates a suitable value; int("hello") instead raises ValueError.
int("42") converts a suitable string to an integer. str(42) creates text from the number. A conversion can fail: int("hello") raises ValueError because that text does not represent an integer.
See the Python code
age_text = "21"
age = int(age_text)
print(age + 1) # 22Watch out for mixed types
A string and integer do not join this way.
Create a string from the number.
The result is "Age: 21".
Choose compatible types before combining values.
"Age: " + 21 raises TypeError: a string and an integer cannot be joined this way. Convert the number with str(21), or pass separate values to print("Age:", 21).
Floating-point values approximate many decimal fractions. For example, 0.1 + 0.2 is not represented as exactly 0.3. Later lessons will show how to choose comparisons and numeric types for a task.
TAKE IT WITH YOU
What you have learned
- 42 and "42" have different types.
- type() helps inspect a value.
- Conversions must suit the input; mixed types can cause errors.
Answer both quick checks correctly to mark this lesson complete. You can continue at any time.