Advertisement
🌱 Beginner

Python Type Conversion – int(), float(), str(), bool() and More

Type conversion (or type casting) is the process of converting a value from one data type to another. Python supports both implicit conversion (done automatically) and explicit conversion (done by the programmer using built-in functions). Understanding this is essential because many bugs come from using the wrong type.

⏱️ 18 min read 🎯 Beginner 📅 Updated 2026

Implicit Type Conversion

Python automatically converts types when it's safe to do so. This only happens when there's no risk of losing data.

Python
# Python automatically converts int to float when mixed
result = 5 + 2.0      # int + float = float
print(result)          # 7.0
print(type(result))    # <class 'float'>

# Another example
x = True + 5  # bool + int = int (True == 1)
print(x)      # 6
▶ Output
7.0 <class 'float'> 6

Explicit Type Conversion – The Big 5

Use these built-in functions to explicitly convert types: int(), float(), str(), bool(), list().

Python
# int() - convert to integer
print(int(3.9))       # 3 (truncates, does NOT round)
print(int("42"))      # 42
print(int(True))      # 1
print(int(False))     # 0

# float() - convert to float
print(float(5))       # 5.0
print(float("3.14"))  # 3.14

# str() - convert to string
print(str(42))        # "42"
print(str(3.14))      # "3.14"
print(str(True))      # "True"

# bool() - convert to boolean
print(bool(0))        # False
print(bool(1))        # True
print(bool(""))       # False
print(bool("hello"))  # True
▶ Output
3 42 1 0 5.0 3.14 42 3.14 True False True False True
Advertisement

Converting Collections

Python can convert between list, tuple, set, and dict (with some restrictions).

Python
my_list = [1, 2, 3, 2, 1]

print(tuple(my_list))   # (1, 2, 3, 2, 1) - ordered, immutable
print(set(my_list))     # {1, 2, 3} - unique values only
print(list(set(my_list)))  # back to list, but unordered

# String to list of characters
print(list("hello"))  # ['h', 'e', 'l', 'l', 'o']
▶ Output
(1, 2, 3, 2, 1) {1, 2, 3} [1, 2, 3] ['h', 'e', 'l', 'l', 'o']

Conversion Errors – When Conversion Fails

Not all conversions are valid. Always handle potential ValueError when converting user input.

Python
# This will raise ValueError
try:
    x = int("hello")   # Cannot convert "hello" to int
except ValueError as e:
    print(f"Error: {e}")

# Safe conversion pattern
def safe_int(value, default=0):
    try:
        return int(value)
    except (ValueError, TypeError):
        return default

print(safe_int("123"))   # 123
print(safe_int("abc"))   # 0 (default)
▶ Output
Error: invalid literal for int() with base 10: 'hello' 123 0
💡
Tip

Always wrap user input conversions in try/except to handle invalid input gracefully.

Type Conversion: Explicit Casts and the input() Trap

Python doesn't silently convert types the way some languages do — you cast explicitly with int(), str(), float(). The #1 beginner bug lives here: input() always returns a string, even for numbers.

age = input("Age? ")     # ALWAYS a str, e.g. "30"
age + 1                   # ❌ TypeError: can't add int to str
age = int(input("Age? ")) # ✅ convert first

int("42")                 # 42
int("3.9")                # ❌ ValueError — use int(float("3.9"))
str(42)                   # "42"
float("1e3")              # 1000.0
ConversionWatch out for
int("abc")ValueError on non-numeric text
int(3.9)truncates to 3 (doesn't round)
bool([])False — empty containers are falsy

The input() rule: wrap numeric input in int() or float() immediately. Guard against bad input with try/except ValueError, since a user typing "abc" into int() crashes. Note int() truncates floats toward zero (int(3.9) == 3) — use round() if you want nearest. Understanding truthiness helps too: bool() of empty strings, empty lists, 0, and None is all False.

🏋️ Practical Exercise

Practice converting between types:

  1. Convert the string "42" to an integer and add 8 to it.
  2. Convert a float 3.99 to an int and note what happens to the decimals.
  3. Convert an integer to a string and concatenate it into a sentence.
  4. Convert a list of numbers to a set and back to a list, observing the change.

🔥 Challenge Exercise

Write a mini calculator that reads two numbers as strings (as input() would return them), converts them safely to floats, and prints their sum. Wrap the conversion in a try/except ValueError so that non-numeric input like "abc" prints a friendly error instead of crashing. Bonus: if both inputs are whole numbers, show the result as an int.

📋 Summary

  • Implicit conversion (coercion) happens automatically, e.g. int + float becomes a float.
  • Explicit conversion uses functions: int(), float(), str(), bool(), list().
  • Converting a float to an int truncates the decimal part toward zero — it does not round.
  • Invalid conversions (e.g. int("abc")) raise a ValueError.
  • Collection conversions can change data — set() removes duplicates and ordering.
  • Always validate or wrap conversions of user input in try/except.

Interview Questions on Type Conversion

  • What is the difference between implicit and explicit type conversion?
  • What are the main type conversion functions in Python?
  • What happens when you convert a float to an int?
  • What error is raised when converting an invalid string to a number?
  • How do you convert a list to a set, and what side effect does that have?
  • Why can’t you add a string and an integer directly?
  • How do you safely convert user input to a number?

FAQ

Does converting a float to an int round the number? +

No. int(3.99) returns 3 — it truncates toward zero rather than rounding. Use round(3.99) if you want rounding to the nearest integer.

Why do I get a TypeError when adding a string and a number? +

Python does not implicitly convert between strings and numbers because the intent is ambiguous. Convert explicitly: int(s) + n to add numerically, or s + str(n) to concatenate.

What is the difference between implicit and explicit conversion? +

Implicit conversion is done by Python automatically in mixed-type expressions (e.g. 2 + 3.0 yields a float). Explicit conversion is done by you calling a function like int() or str().

How do I convert user input safely? +

Wrap the conversion in try/except ValueError. Since input() always returns a string, attempting int(value) on non-numeric text raises ValueError, which you can catch and handle with a prompt to retry.