Skip to content
Kuza Ndoto Academy

Type Conversion

Beginner → IntermediateChapter 2 · Page 11 of 563 min readUpdated 15 Nov 2026

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

FunctionConverts toExampleResult
int()Integerint("42")42
float()Floatfloat("3.5")3.5
str()Stringstr(2026)'2026'
bool()Booleanbool(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"))
136.5 42 10.0 1000.0

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}")
Hours worked: 6 Rate per hour (KES): 312.5 Pay: KES 1,875.00

When conversion fails

Python only converts text that really looks like the target type. Otherwise it raises a ValueError:

int("abc")
ValueError: invalid literal for int() with base 10: 'abc'
int("3.7")
ValueError: invalid literal for int() with base 10: '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.

Tip

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))
3 -3 4

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 Age: 21 4
Common mistake

"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"))
False False False False True True True True

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)
7.5 10.0 2

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))
10 255 0b1010 0xff

Key points

  • int(), float(), str() and bool() return converted copies of a value.
  • Converting invalid text raises ValueError; int("3.7") fails, so use int(float("3.7")).
  • int() on a float truncates towards zero; use round() to round.
  • Zero, empty and None values are falsy; everything else, including "False", is truthy.
  • Python mixes ints and floats automatically but never strings and numbers.
Up next · Python BasicsOperatorsArithmetic, comparison, logical and assignment operators.
→

Tip: use the ← and → keys to move between pages.