Course topics

By WebNest Studio Engineering Team

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.

Why it matters

Data arrives as text: from input(), from files, from web forms and from APIs. Before it can be used in a calculation it has to be converted, and the conversion can fail when the text is not what you expected. Handling that failure is the difference between a program that reports a problem and one that crashes.

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.

Exercise

Write a function that converts text to an integer and returns a default value when the text is not a valid whole number.

Expected output: 42, 0, 7 (one per line)

Python · starter code
def to_int(text, default=0):
    # TODO: return the text converted to an int, or the default if that fails
    pass


print(to_int("42"))
print(to_int("4x"))
print(to_int("  7 "))
Show hints
  • int() raises ValueError for text that is not a whole number.
  • int() already ignores spaces before and after the digits.
Show solution
Python · solution
def to_int(text, default=0):
    try:
        return int(text)
    except ValueError:
        return default


print(to_int("42"))
print(to_int("4x"))
print(to_int("  7 "))

Quick quiz

1. What does int(3.9) return?

  • A. 4
  • B. It raises an error
  • C. 3.9
  • D. 3
Show answer

D. int() cuts off the fractional part. It does not round.

2. What does bool("False") return?

  • A. False
  • B. True
  • C. None
  • D. It raises an error
Show answer

B. Any non-empty string is truthy, whatever its text says.

3. What does "5" + 5 do?

  • A. Returns 10
  • B. Raises TypeError
  • C. Returns "55"
  • D. Returns "10"
Show answer

B. Python does not convert between text and numbers automatically. Convert one side explicitly.

Interview questions

What is the difference between implicit and explicit type conversion?

Show answer

Implicit conversion is done by Python without being asked, and only where no information is lost: an int combined with a float becomes a float. Explicit conversion, or casting, is requested by the programmer with a function such as int(), float(), str() or list(). Python never converts between strings and numbers implicitly.

How do you convert the string "ff" to the number 255?

Show answer

Pass the base as the second argument: int("ff", 16). The same works for binary with base 2 and octal with base 8. In the other direction, hex(), bin() and oct() return the text form of a number in those bases.

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 in the playground

Write and run your own code for this topic, or start from the exercise or an example. Runs Python in your browser. Your code for each topic is kept in this browser.

Run the examples

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

WebNest Studio

Written by

WebNest Studio Engineering Team

Practical lessons from developers working with Java, Python, React, databases and production systems.

Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering