Type Conversion
Type conversion (also called casting) means turning a value of one type into another, such as the text "25" into the number 25. You need it whenever data arrives in the wrong form, which happens all the time with user input, files and web data.
The conversion functions
| Function | Converts to | Example | Result |
|---|---|---|---|
int() | Integer | int("42") | 42 |
float() | Float | float("3.5") | 3.5 |
str() | String | str(2026) | '2026' |
bool() | Boolean | bool(0) | False |
Each function returns a new value; the original is unchanged. If you want to keep the result, assign it to a variable.
Text to numbers
quantity = "3"
unit_price = "45.50"
total = int(quantity) * float(unit_price)
print(total)
print(int(" 42 ")) # spaces around the digits are allowed
print(float("10"))
print(float("1e3"))
This is exactly what you do with input(), which always returns a string:
hours = int(input("Hours worked: "))
rate = float(input("Rate per hour (KES): "))
print(f"Pay: KES {hours * rate:,.2f}")
When conversion fails
Python only converts text that really looks like the target type. Otherwise it raises a ValueError:
int("abc")
int("3.7")
The second one catches many beginners. int() won't accept a decimal string. Convert to float first, then to int: int(float("3.7")) gives 3.
To check whether text is a whole number before converting, use text.isdigit(), which is True only if every character is a digit (so "-5" and "3.7" return False). The more robust approach, catching the error itself, is covered on Try, Except & Finally.
Floats to integers
int() on a float simply chops off the decimal part. It does not round. Use round() if you want the nearest whole number.
print(int(3.99)) print(int(-3.99)) print(round(3.99))
Notice that int(-3.99) gives -3: int() moves towards zero.
Numbers to text
+ can't join a string and a number. Convert the number with str(), or avoid the problem with an f-string.
age = 21
print("Age: " + str(age))
print(f"Age: {age}")
print(len(str(2026))) # how many digits?
"Age: " + 21 raises TypeError: can only concatenate str (not "int") to str. Python never guesses whether you meant text or maths, so you must convert one side yourself.
Converting to bool: truthy and falsy
bool() follows one simple rule. "Empty" or "zero" values are False (we call them falsy), and everything else is True (truthy).
print(bool(0))
print(bool(0.0))
print(bool(""))
print(bool(None))
print(bool(42))
print(bool("hello"))
print(bool(" "))
print(bool("False"))
The last two are traps. A string containing a single space is not empty, so it's truthy. And "False" is a non-empty string of five letters, so it is True! To turn user text into a Boolean, compare it instead: answer.lower() == "yes". Truthiness becomes very useful in if statements.
Implicit conversion
Sometimes Python converts for you automatically, but only when no information can be lost. Mixing an int and a float gives a float, and True/False act as 1 and 0 in arithmetic.
print(3 + 4.5) print(10 * 1.0) print(True + 1)
Python will not silently convert between strings and numbers. This strictness is deliberate: it catches bugs early instead of producing odd results.
Other bases
int() can also read numbers written in other bases if you tell it which base the text uses. This is useful in computing topics such as binary.
print(int("1010", 2)) # binary
print(int("ff", 16)) # hexadecimal
print(bin(10))
print(hex(255))
Key points
int(),float(),str()andbool()return converted copies of a value.- Converting invalid text raises
ValueError;int("3.7")fails, so useint(float("3.7")). int()on a float truncates towards zero; useround()to round.- Zero, empty and
Nonevalues are falsy; everything else, including"False", is truthy. - Python mixes ints and floats automatically but never strings and numbers.
Tip: use the ← and → keys to move between pages.
