Course topics

By WebNest Studio

Python Tutorial

Type Casting and Type Conversion in Python

Data often arrives in the wrong type: numbers typed by a user are strings, values from a CSV file are strings, and sometimes you need a list from a string or a string from a number. Type conversion changes a value from one type to another.

Python performs some conversions automatically (implicit), and you perform others with functions like int(), float(), str(), list() and bool() (explicit, also called type casting). This lesson covers both, plus what happens when conversion fails.

Implicit Conversion

Python automatically widens numeric types in mixed arithmetic: int + float produces a float and int + complex a complex, so no precision is lost. It never silently converts between strings and numbers — "5" + 3 raises TypeError.

Explicit Conversion Functions

The main casting functions:

  • int(x) — from float (truncates toward zero), from string of digits, or with a base: int("ff", 16).
  • float(x) — from int or numeric string, including "1e3", "inf", "nan".
  • str(x) — a readable string of any object.
  • bool(x) — truthiness of any value.
  • list(x), tuple(x), set(x), dict(pairs) — between collection types.
  • chr(n) / ord(c) — between characters and Unicode code points; bin(), oct(), hex() — integers to base strings.

When Conversion Fails

int("12.5") and int("abc") raise ValueError; int(None) raises TypeError. Wrap conversions of external data in try/except. To turn "12.5" into an int, convert to float first. Note that bool("False") is True because the string is not empty.

Examples

Implicit and explicit numeric conversions

Python
result = 10 + 2.5
print(result, type(result))

print(int(9.99), int(-9.99), int("42"), int("ff", 16), int("1010", 2))
print(float(7), float("3.5"), float("1e3"))
print(str(3.14) + " is pi")
print(int(float("12.5")))
Output
12.5 <class 'float'>
9 -9 42 255 10
7.0 3.5 1000.0
3.14 is pi
12

Collections, characters and bases

Python
print(list("abc"), tuple([1, 2]), set([1, 1, 2]))
print(dict([("a", 1), ("b", 2)]))
print(ord("A"), chr(97), chr(8377))
print(bin(10), oct(10), hex(255))
print(bool("False"), bool(""), bool(0.0))
Output
['a', 'b', 'c'] (1, 2) {1, 2}
{'a': 1, 'b': 2}
65 a ₹
0b1010 0o12 0xff
True False False

Safe conversion of user data

Python
def to_int(text, default=0):
    try:
        return int(text)
    except (ValueError, TypeError):
        return default

for raw in ["25", " 7 ", "12.5", "abc", None]:
    print(repr(raw), "->", to_int(raw))

try:
    print("5" + 3)
except TypeError as error:
    print("TypeError:", error)
Output
'25' -> 25
' 7 ' -> 7
'12.5' -> 0
'abc' -> 0
None -> 0
TypeError: can only concatenate str (not "int") to str

Common Mistakes

  • Expecting int("12.5") to work — convert with float() first.
  • Expecting int(9.99) to round — it truncates to 9; use round() to round.
  • Treating bool("False") as False.
  • Not handling ValueError when converting user or file input.

Key Points to Remember

  • Python implicitly widens numbers (int → float → complex) but never mixes str and numbers.
  • int(), float(), str(), bool(), list(), tuple(), set(), dict() convert explicitly.
  • int(x, base) parses binary/hex strings; bin/oct/hex format them.
  • Invalid conversions raise ValueError or TypeError — catch them for external data.

Practice the examples

Change an input, predict the result, then compare it with the output. Explain why the result changes.