Type Conversion
in Python
Master the art of converting between types using int(), float(), str(), and bool() to build flexible, error-free programs.
What Are Data Types?
Every value in Python has a type that tells the interpreter how to store, display, and operate on that value. The four foundational types you will use every day are:
Why Convert Types?
Python is strongly typed: it will not silently mix incompatible types. If you try to add a string to an integer, you get a TypeError. Type conversion lets you bridge these gaps deliberately.
The Conversion Landscape
The Core Rule of Conversion
These are explicit conversions (also called type casting). You, the programmer, decide when and how to convert.
Implicit vs Explicit Conversion
Example: 3 + 2.5 promotes 3 to 3.0, result is 5.5.
Only happens between int and float.
Example: int("42") converts the string "42" to integer 42.
Works across all four types.
Deep Dive: int()
Deep Dive: float()
Deep Dive: str() and bool()
str(3.14) → "3.14"
str(True) → "True"
Every Python object has a string representation.
Everything else is True:
bool(42) → True
bool("hi") → True
How to Apply Type Conversion
Example 1: User Input Calculator
Build a simple program that reads two numbers from the user and prints their sum.
Example 2: Chaining Conversions
Sometimes you need to convert through an intermediate type. Remember: int("3.14") fails, but you can chain two conversions.
Example 3: Building Strings from Numbers
You often need to include numbers inside messages. Two approaches:
The Truthiness Rule
Common Mistakes
Conversion Summary Table
| Input | int() | float() | str() | bool() |
|---|---|---|---|---|
| 42 | 42 | 42.0 | "42" | True |
| 3.14 | 3 | 3.14 | "3.14" | True |
| "7" | 7 | 7.0 | "7" | True |
| "" | Error | Error | "" | False |
| 0 | 0 | 0.0 | "0" | False |
| True | 1 | 1.0 | "True" | True |
Question 1 of 5
What is the output of int(7.9)?
Question 2 of 5
What happens when you run int("3.5")?
Question 3 of 5
What is the result of bool("")?
Question 4 of 5
Given x = input() and the user types 42, what is type(x)?
Question 5 of 5
What does str(3 + 4.0) + "!" evaluate to?