Data Types and Type Conversion
Recognize common data types and convert values explicitly when your program needs it.
Values have types
Every value in Python has a data type. A type tells Python what kind of value it is and which operations make sense for it.
You can ask Python for a value's type with type().
| Type | Example | Use |
|---|---|---|
| int | 42 | Whole numbers |
| float | 3.5 | Numbers with a decimal point |
| str | "hello" | Text |
| bool | True | True or false values |
| complex | 2 + 3j | Numbers with real and imaginary parts |
print(type(42))
print(type(3.5))
print(type("hello"))
The output names the type of each value. An int has no decimal point, while a float has one.
Implicit conversion
Sometimes Python converts a value for you. This is called implicit conversion. For example, mixing an integer and a float in arithmetic produces a float.
whole_number = 4 decimal_number = 0.5 result = whole_number + decimal_number print(result) print(type(result))
Python changes the integer 4 to a float so it can add it to 0.5. The result is therefore a float.
Explicit conversion
Explicit conversion means you ask Python to change a value yourself. Use int(), float(), str(), or bool() when the conversion makes sense.
count_text = "7"
count = int(count_text)
price = float("2.5")
label = str(count)
is_ready = bool(1)
number = 0.1 + 0.2
complex_number = 2 + 3j
print(count + 1)
print(price)
print(label)
print(is_ready)
print(number)
print(complex_number)
int() turns the numeric text "7" into a number. bool(1) is True; in general, zero and empty values are false, while many other values are true.
Computers store most floats in binary, so some decimal values cannot be represented exactly. That is why 0.1 + 0.2 prints 0.30000000000000004. A complex number uses j for its imaginary part.
Key points
- Common types include int, float, str, bool, and complex.
- type() reports a value's type.
- Python can convert some values implicitly.
- Use int(), float(), str(), and bool() for explicit conversion.
- Floating-point math can show tiny precision differences.
Worked example
An SMS arrives showing 12 as TEXT ('12'), but you need to add postage of 60 taka. Convert, then add.
sms_number = "12" cost = int(sms_number) + 60 print(cost)
How it works, step by step
- "12" is a string — adding 60 directly would crash.
- int("12") converts it to the number 12.
- Numbers add normally: 72.
References & Further Reading
Related entries from PyLabs's own reference library.
Practice exercise
Not passed yetConvert the text "12" to an integer, add 3, and print the result.
# Write your code below
Check yourself
Data Types and Type Conversion quiz
10 questions. You get instant feedback per question, and the timer starts when you press the button.
Lesson incomplete
Not completedCreate an ID or sign in to save lesson completion across devices.